clang 20.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"
42#include "clang/AST/ASTLambda.h"
43#include "clang/AST/Attr.h"
45#include "clang/AST/CharUnits.h"
47#include "clang/AST/Expr.h"
48#include "clang/AST/OSLog.h"
52#include "clang/AST/TypeLoc.h"
56#include "llvm/ADT/APFixedPoint.h"
57#include "llvm/ADT/SmallBitVector.h"
58#include "llvm/ADT/StringExtras.h"
59#include "llvm/Support/Debug.h"
60#include "llvm/Support/SaveAndRestore.h"
61#include "llvm/Support/SipHash.h"
62#include "llvm/Support/TimeProfiler.h"
63#include "llvm/Support/raw_ostream.h"
64#include <cstring>
65#include <functional>
66#include <optional>
67
68#define DEBUG_TYPE "exprconstant"
69
70using namespace clang;
71using llvm::APFixedPoint;
72using llvm::APInt;
73using llvm::APSInt;
74using llvm::APFloat;
75using llvm::FixedPointSemantics;
76
77namespace {
78 struct LValue;
79 class CallStackFrame;
80 class EvalInfo;
81
82 using SourceLocExprScopeGuard =
84
85 static QualType getType(APValue::LValueBase B) {
86 return B.getType();
87 }
88
89 /// Get an LValue path entry, which is known to not be an array index, as a
90 /// field declaration.
91 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
92 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
93 }
94 /// Get an LValue path entry, which is known to not be an array index, as a
95 /// base class declaration.
96 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
97 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
98 }
99 /// Determine whether this LValue path entry for a base class names a virtual
100 /// base class.
101 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
102 return E.getAsBaseOrMember().getInt();
103 }
104
105 /// Given an expression, determine the type used to store the result of
106 /// evaluating that expression.
107 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
108 if (E->isPRValue())
109 return E->getType();
110 return Ctx.getLValueReferenceType(E->getType());
111 }
112
113 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
114 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
115 if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
116 return DirectCallee->getAttr<AllocSizeAttr>();
117 if (const Decl *IndirectCallee = CE->getCalleeDecl())
118 return IndirectCallee->getAttr<AllocSizeAttr>();
119 return nullptr;
120 }
121
122 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
123 /// This will look through a single cast.
124 ///
125 /// Returns null if we couldn't unwrap a function with alloc_size.
126 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
127 if (!E->getType()->isPointerType())
128 return nullptr;
129
130 E = E->IgnoreParens();
131 // If we're doing a variable assignment from e.g. malloc(N), there will
132 // probably be a cast of some kind. In exotic cases, we might also see a
133 // top-level ExprWithCleanups. Ignore them either way.
134 if (const auto *FE = dyn_cast<FullExpr>(E))
135 E = FE->getSubExpr()->IgnoreParens();
136
137 if (const auto *Cast = dyn_cast<CastExpr>(E))
138 E = Cast->getSubExpr()->IgnoreParens();
139
140 if (const auto *CE = dyn_cast<CallExpr>(E))
141 return getAllocSizeAttr(CE) ? CE : nullptr;
142 return nullptr;
143 }
144
145 /// Determines whether or not the given Base contains a call to a function
146 /// with the alloc_size attribute.
147 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
148 const auto *E = Base.dyn_cast<const Expr *>();
149 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
150 }
151
152 /// Determines whether the given kind of constant expression is only ever
153 /// used for name mangling. If so, it's permitted to reference things that we
154 /// can't generate code for (in particular, dllimported functions).
155 static bool isForManglingOnly(ConstantExprKind Kind) {
156 switch (Kind) {
157 case ConstantExprKind::Normal:
158 case ConstantExprKind::ClassTemplateArgument:
159 case ConstantExprKind::ImmediateInvocation:
160 // Note that non-type template arguments of class type are emitted as
161 // template parameter objects.
162 return false;
163
164 case ConstantExprKind::NonClassTemplateArgument:
165 return true;
166 }
167 llvm_unreachable("unknown ConstantExprKind");
168 }
169
170 static bool isTemplateArgument(ConstantExprKind Kind) {
171 switch (Kind) {
172 case ConstantExprKind::Normal:
173 case ConstantExprKind::ImmediateInvocation:
174 return false;
175
176 case ConstantExprKind::ClassTemplateArgument:
177 case ConstantExprKind::NonClassTemplateArgument:
178 return true;
179 }
180 llvm_unreachable("unknown ConstantExprKind");
181 }
182
183 /// The bound to claim that an array of unknown bound has.
184 /// The value in MostDerivedArraySize is undefined in this case. So, set it
185 /// to an arbitrary value that's likely to loudly break things if it's used.
186 static const uint64_t AssumedSizeForUnsizedArray =
187 std::numeric_limits<uint64_t>::max() / 2;
188
189 /// Determines if an LValue with the given LValueBase will have an unsized
190 /// array in its designator.
191 /// Find the path length and type of the most-derived subobject in the given
192 /// path, and find the size of the containing array, if any.
193 static unsigned
194 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
196 uint64_t &ArraySize, QualType &Type, bool &IsArray,
197 bool &FirstEntryIsUnsizedArray) {
198 // This only accepts LValueBases from APValues, and APValues don't support
199 // arrays that lack size info.
200 assert(!isBaseAnAllocSizeCall(Base) &&
201 "Unsized arrays shouldn't appear here");
202 unsigned MostDerivedLength = 0;
203 Type = getType(Base);
204
205 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
206 if (Type->isArrayType()) {
207 const ArrayType *AT = Ctx.getAsArrayType(Type);
208 Type = AT->getElementType();
209 MostDerivedLength = I + 1;
210 IsArray = true;
211
212 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
213 ArraySize = CAT->getZExtSize();
214 } else {
215 assert(I == 0 && "unexpected unsized array designator");
216 FirstEntryIsUnsizedArray = true;
217 ArraySize = AssumedSizeForUnsizedArray;
218 }
219 } else if (Type->isAnyComplexType()) {
220 const ComplexType *CT = Type->castAs<ComplexType>();
221 Type = CT->getElementType();
222 ArraySize = 2;
223 MostDerivedLength = I + 1;
224 IsArray = true;
225 } else if (const auto *VT = Type->getAs<VectorType>()) {
226 Type = VT->getElementType();
227 ArraySize = VT->getNumElements();
228 MostDerivedLength = I + 1;
229 IsArray = true;
230 } else if (const FieldDecl *FD = getAsField(Path[I])) {
231 Type = FD->getType();
232 ArraySize = 0;
233 MostDerivedLength = I + 1;
234 IsArray = false;
235 } else {
236 // Path[I] describes a base class.
237 ArraySize = 0;
238 IsArray = false;
239 }
240 }
241 return MostDerivedLength;
242 }
243
244 /// A path from a glvalue to a subobject of that glvalue.
245 struct SubobjectDesignator {
246 /// True if the subobject was named in a manner not supported by C++11. Such
247 /// lvalues can still be folded, but they are not core constant expressions
248 /// and we cannot perform lvalue-to-rvalue conversions on them.
249 LLVM_PREFERRED_TYPE(bool)
250 unsigned Invalid : 1;
251
252 /// Is this a pointer one past the end of an object?
253 LLVM_PREFERRED_TYPE(bool)
254 unsigned IsOnePastTheEnd : 1;
255
256 /// Indicator of whether the first entry is an unsized array.
257 LLVM_PREFERRED_TYPE(bool)
258 unsigned FirstEntryIsAnUnsizedArray : 1;
259
260 /// Indicator of whether the most-derived object is an array element.
261 LLVM_PREFERRED_TYPE(bool)
262 unsigned MostDerivedIsArrayElement : 1;
263
264 /// The length of the path to the most-derived object of which this is a
265 /// subobject.
266 unsigned MostDerivedPathLength : 28;
267
268 /// The size of the array of which the most-derived object is an element.
269 /// This will always be 0 if the most-derived object is not an array
270 /// element. 0 is not an indicator of whether or not the most-derived object
271 /// is an array, however, because 0-length arrays are allowed.
272 ///
273 /// If the current array is an unsized array, the value of this is
274 /// undefined.
275 uint64_t MostDerivedArraySize;
276 /// The type of the most derived object referred to by this address.
277 QualType MostDerivedType;
278
279 typedef APValue::LValuePathEntry PathEntry;
280
281 /// The entries on the path from the glvalue to the designated subobject.
283
284 SubobjectDesignator() : Invalid(true) {}
285
286 explicit SubobjectDesignator(QualType T)
287 : Invalid(false), IsOnePastTheEnd(false),
288 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
289 MostDerivedPathLength(0), MostDerivedArraySize(0),
290 MostDerivedType(T) {}
291
292 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
293 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
294 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
295 MostDerivedPathLength(0), MostDerivedArraySize(0) {
296 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
297 if (!Invalid) {
298 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
299 ArrayRef<PathEntry> VEntries = V.getLValuePath();
300 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
301 if (V.getLValueBase()) {
302 bool IsArray = false;
303 bool FirstIsUnsizedArray = false;
304 MostDerivedPathLength = findMostDerivedSubobject(
305 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
306 MostDerivedType, IsArray, FirstIsUnsizedArray);
307 MostDerivedIsArrayElement = IsArray;
308 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
309 }
310 }
311 }
312
313 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
314 unsigned NewLength) {
315 if (Invalid)
316 return;
317
318 assert(Base && "cannot truncate path for null pointer");
319 assert(NewLength <= Entries.size() && "not a truncation");
320
321 if (NewLength == Entries.size())
322 return;
323 Entries.resize(NewLength);
324
325 bool IsArray = false;
326 bool FirstIsUnsizedArray = false;
327 MostDerivedPathLength = findMostDerivedSubobject(
328 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
329 FirstIsUnsizedArray);
330 MostDerivedIsArrayElement = IsArray;
331 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
332 }
333
334 void setInvalid() {
335 Invalid = true;
336 Entries.clear();
337 }
338
339 /// Determine whether the most derived subobject is an array without a
340 /// known bound.
341 bool isMostDerivedAnUnsizedArray() const {
342 assert(!Invalid && "Calling this makes no sense on invalid designators");
343 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
344 }
345
346 /// Determine what the most derived array's size is. Results in an assertion
347 /// failure if the most derived array lacks a size.
348 uint64_t getMostDerivedArraySize() const {
349 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
350 return MostDerivedArraySize;
351 }
352
353 /// Determine whether this is a one-past-the-end pointer.
354 bool isOnePastTheEnd() const {
355 assert(!Invalid);
356 if (IsOnePastTheEnd)
357 return true;
358 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
359 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
360 MostDerivedArraySize)
361 return true;
362 return false;
363 }
364
365 /// Get the range of valid index adjustments in the form
366 /// {maximum value that can be subtracted from this pointer,
367 /// maximum value that can be added to this pointer}
368 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
369 if (Invalid || isMostDerivedAnUnsizedArray())
370 return {0, 0};
371
372 // [expr.add]p4: For the purposes of these operators, a pointer to a
373 // nonarray object behaves the same as a pointer to the first element of
374 // an array of length one with the type of the object as its element type.
375 bool IsArray = MostDerivedPathLength == Entries.size() &&
376 MostDerivedIsArrayElement;
377 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
378 : (uint64_t)IsOnePastTheEnd;
379 uint64_t ArraySize =
380 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
381 return {ArrayIndex, ArraySize - ArrayIndex};
382 }
383
384 /// Check that this refers to a valid subobject.
385 bool isValidSubobject() const {
386 if (Invalid)
387 return false;
388 return !isOnePastTheEnd();
389 }
390 /// Check that this refers to a valid subobject, and if not, produce a
391 /// relevant diagnostic and set the designator as invalid.
392 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
393
394 /// Get the type of the designated object.
395 QualType getType(ASTContext &Ctx) const {
396 assert(!Invalid && "invalid designator has no subobject type");
397 return MostDerivedPathLength == Entries.size()
398 ? MostDerivedType
399 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
400 }
401
402 /// Update this designator to refer to the first element within this array.
403 void addArrayUnchecked(const ConstantArrayType *CAT) {
404 Entries.push_back(PathEntry::ArrayIndex(0));
405
406 // This is a most-derived object.
407 MostDerivedType = CAT->getElementType();
408 MostDerivedIsArrayElement = true;
409 MostDerivedArraySize = CAT->getZExtSize();
410 MostDerivedPathLength = Entries.size();
411 }
412 /// Update this designator to refer to the first element within the array of
413 /// elements of type T. This is an array of unknown size.
414 void addUnsizedArrayUnchecked(QualType ElemTy) {
415 Entries.push_back(PathEntry::ArrayIndex(0));
416
417 MostDerivedType = ElemTy;
418 MostDerivedIsArrayElement = true;
419 // The value in MostDerivedArraySize is undefined in this case. So, set it
420 // to an arbitrary value that's likely to loudly break things if it's
421 // used.
422 MostDerivedArraySize = AssumedSizeForUnsizedArray;
423 MostDerivedPathLength = Entries.size();
424 }
425 /// Update this designator to refer to the given base or member of this
426 /// object.
427 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
428 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
429
430 // If this isn't a base class, it's a new most-derived object.
431 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
432 MostDerivedType = FD->getType();
433 MostDerivedIsArrayElement = false;
434 MostDerivedArraySize = 0;
435 MostDerivedPathLength = Entries.size();
436 }
437 }
438 /// Update this designator to refer to the given complex component.
439 void addComplexUnchecked(QualType EltTy, bool Imag) {
440 Entries.push_back(PathEntry::ArrayIndex(Imag));
441
442 // This is technically a most-derived object, though in practice this
443 // is unlikely to matter.
444 MostDerivedType = EltTy;
445 MostDerivedIsArrayElement = true;
446 MostDerivedArraySize = 2;
447 MostDerivedPathLength = Entries.size();
448 }
449
450 void addVectorElementUnchecked(QualType EltTy, uint64_t Size,
451 uint64_t Idx) {
452 Entries.push_back(PathEntry::ArrayIndex(Idx));
453 MostDerivedType = EltTy;
454 MostDerivedPathLength = Entries.size();
455 MostDerivedArraySize = 0;
456 MostDerivedIsArrayElement = false;
457 }
458
459 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
460 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
461 const APSInt &N);
462 /// Add N to the address of this subobject.
463 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
464 if (Invalid || !N) return;
465 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
466 if (isMostDerivedAnUnsizedArray()) {
467 diagnoseUnsizedArrayPointerArithmetic(Info, E);
468 // Can't verify -- trust that the user is doing the right thing (or if
469 // not, trust that the caller will catch the bad behavior).
470 // FIXME: Should we reject if this overflows, at least?
471 Entries.back() = PathEntry::ArrayIndex(
472 Entries.back().getAsArrayIndex() + TruncatedN);
473 return;
474 }
475
476 // [expr.add]p4: For the purposes of these operators, a pointer to a
477 // nonarray object behaves the same as a pointer to the first element of
478 // an array of length one with the type of the object as its element type.
479 bool IsArray = MostDerivedPathLength == Entries.size() &&
480 MostDerivedIsArrayElement;
481 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
482 : (uint64_t)IsOnePastTheEnd;
483 uint64_t ArraySize =
484 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
485
486 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
487 // Calculate the actual index in a wide enough type, so we can include
488 // it in the note.
489 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
490 (llvm::APInt&)N += ArrayIndex;
491 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
492 diagnosePointerArithmetic(Info, E, N);
493 setInvalid();
494 return;
495 }
496
497 ArrayIndex += TruncatedN;
498 assert(ArrayIndex <= ArraySize &&
499 "bounds check succeeded for out-of-bounds index");
500
501 if (IsArray)
502 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
503 else
504 IsOnePastTheEnd = (ArrayIndex != 0);
505 }
506 };
507
508 /// A scope at the end of which an object can need to be destroyed.
509 enum class ScopeKind {
510 Block,
511 FullExpression,
512 Call
513 };
514
515 /// A reference to a particular call and its arguments.
516 struct CallRef {
517 CallRef() : OrigCallee(), CallIndex(0), Version() {}
518 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
519 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
520
521 explicit operator bool() const { return OrigCallee; }
522
523 /// Get the parameter that the caller initialized, corresponding to the
524 /// given parameter in the callee.
525 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
526 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
527 : PVD;
528 }
529
530 /// The callee at the point where the arguments were evaluated. This might
531 /// be different from the actual callee (a different redeclaration, or a
532 /// virtual override), but this function's parameters are the ones that
533 /// appear in the parameter map.
534 const FunctionDecl *OrigCallee;
535 /// The call index of the frame that holds the argument values.
536 unsigned CallIndex;
537 /// The version of the parameters corresponding to this call.
538 unsigned Version;
539 };
540
541 /// A stack frame in the constexpr call stack.
542 class CallStackFrame : public interp::Frame {
543 public:
544 EvalInfo &Info;
545
546 /// Parent - The caller of this stack frame.
547 CallStackFrame *Caller;
548
549 /// Callee - The function which was called.
550 const FunctionDecl *Callee;
551
552 /// This - The binding for the this pointer in this call, if any.
553 const LValue *This;
554
555 /// CallExpr - The syntactical structure of member function calls
556 const Expr *CallExpr;
557
558 /// Information on how to find the arguments to this call. Our arguments
559 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
560 /// key and this value as the version.
561 CallRef Arguments;
562
563 /// Source location information about the default argument or default
564 /// initializer expression we're evaluating, if any.
565 CurrentSourceLocExprScope CurSourceLocExprScope;
566
567 // Note that we intentionally use std::map here so that references to
568 // values are stable.
569 typedef std::pair<const void *, unsigned> MapKeyTy;
570 typedef std::map<MapKeyTy, APValue> MapTy;
571 /// Temporaries - Temporary lvalues materialized within this stack frame.
572 MapTy Temporaries;
573
574 /// CallRange - The source range of the call expression for this call.
575 SourceRange CallRange;
576
577 /// Index - The call index of this call.
578 unsigned Index;
579
580 /// The stack of integers for tracking version numbers for temporaries.
581 SmallVector<unsigned, 2> TempVersionStack = {1};
582 unsigned CurTempVersion = TempVersionStack.back();
583
584 unsigned getTempVersion() const { return TempVersionStack.back(); }
585
586 void pushTempVersion() {
587 TempVersionStack.push_back(++CurTempVersion);
588 }
589
590 void popTempVersion() {
591 TempVersionStack.pop_back();
592 }
593
594 CallRef createCall(const FunctionDecl *Callee) {
595 return {Callee, Index, ++CurTempVersion};
596 }
597
598 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
599 // on the overall stack usage of deeply-recursing constexpr evaluations.
600 // (We should cache this map rather than recomputing it repeatedly.)
601 // But let's try this and see how it goes; we can look into caching the map
602 // as a later change.
603
604 /// LambdaCaptureFields - Mapping from captured variables/this to
605 /// corresponding data members in the closure class.
606 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
607 FieldDecl *LambdaThisCaptureField = nullptr;
608
609 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
610 const FunctionDecl *Callee, const LValue *This,
611 const Expr *CallExpr, CallRef Arguments);
612 ~CallStackFrame();
613
614 // Return the temporary for Key whose version number is Version.
615 APValue *getTemporary(const void *Key, unsigned Version) {
616 MapKeyTy KV(Key, Version);
617 auto LB = Temporaries.lower_bound(KV);
618 if (LB != Temporaries.end() && LB->first == KV)
619 return &LB->second;
620 return nullptr;
621 }
622
623 // Return the current temporary for Key in the map.
624 APValue *getCurrentTemporary(const void *Key) {
625 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
626 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
627 return &std::prev(UB)->second;
628 return nullptr;
629 }
630
631 // Return the version number of the current temporary for Key.
632 unsigned getCurrentTemporaryVersion(const void *Key) const {
633 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
634 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
635 return std::prev(UB)->first.second;
636 return 0;
637 }
638
639 /// Allocate storage for an object of type T in this stack frame.
640 /// Populates LV with a handle to the created object. Key identifies
641 /// the temporary within the stack frame, and must not be reused without
642 /// bumping the temporary version number.
643 template<typename KeyT>
644 APValue &createTemporary(const KeyT *Key, QualType T,
645 ScopeKind Scope, LValue &LV);
646
647 /// Allocate storage for a parameter of a function call made in this frame.
648 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
649
650 void describe(llvm::raw_ostream &OS) const override;
651
652 Frame *getCaller() const override { return Caller; }
653 SourceRange getCallRange() const override { return CallRange; }
654 const FunctionDecl *getCallee() const override { return Callee; }
655
656 bool isStdFunction() const {
657 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
658 if (DC->isStdNamespace())
659 return true;
660 return false;
661 }
662
663 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
664 /// permitted. See MSConstexprDocs for description of permitted contexts.
665 bool CanEvalMSConstexpr = false;
666
667 private:
668 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
669 ScopeKind Scope);
670 };
671
672 /// Temporarily override 'this'.
673 class ThisOverrideRAII {
674 public:
675 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
676 : Frame(Frame), OldThis(Frame.This) {
677 if (Enable)
678 Frame.This = NewThis;
679 }
680 ~ThisOverrideRAII() {
681 Frame.This = OldThis;
682 }
683 private:
684 CallStackFrame &Frame;
685 const LValue *OldThis;
686 };
687
688 // A shorthand time trace scope struct, prints source range, for example
689 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
690 class ExprTimeTraceScope {
691 public:
692 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
693 : TimeScope(Name, [E, &Ctx] {
694 return E->getSourceRange().printToString(Ctx.getSourceManager());
695 }) {}
696
697 private:
698 llvm::TimeTraceScope TimeScope;
699 };
700
701 /// RAII object used to change the current ability of
702 /// [[msvc::constexpr]] evaulation.
703 struct MSConstexprContextRAII {
704 CallStackFrame &Frame;
705 bool OldValue;
706 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
707 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
708 Frame.CanEvalMSConstexpr = Value;
709 }
710
711 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
712 };
713}
714
715static bool HandleDestruction(EvalInfo &Info, const Expr *E,
716 const LValue &This, QualType ThisType);
717static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
719 QualType T);
720
721namespace {
722 /// A cleanup, and a flag indicating whether it is lifetime-extended.
723 class Cleanup {
724 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
726 QualType T;
727
728 public:
729 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
730 ScopeKind Scope)
731 : Value(Val, Scope), Base(Base), T(T) {}
732
733 /// Determine whether this cleanup should be performed at the end of the
734 /// given kind of scope.
735 bool isDestroyedAtEndOf(ScopeKind K) const {
736 return (int)Value.getInt() >= (int)K;
737 }
738 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
739 if (RunDestructors) {
741 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
742 Loc = VD->getLocation();
743 else if (const Expr *E = Base.dyn_cast<const Expr*>())
744 Loc = E->getExprLoc();
745 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
746 }
747 *Value.getPointer() = APValue();
748 return true;
749 }
750
751 bool hasSideEffect() {
752 return T.isDestructedType();
753 }
754 };
755
756 /// A reference to an object whose construction we are currently evaluating.
757 struct ObjectUnderConstruction {
760 friend bool operator==(const ObjectUnderConstruction &LHS,
761 const ObjectUnderConstruction &RHS) {
762 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
763 }
764 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
765 return llvm::hash_combine(Obj.Base, Obj.Path);
766 }
767 };
768 enum class ConstructionPhase {
769 None,
770 Bases,
771 AfterBases,
772 AfterFields,
773 Destroying,
774 DestroyingBases
775 };
776}
777
778namespace llvm {
779template<> struct DenseMapInfo<ObjectUnderConstruction> {
780 using Base = DenseMapInfo<APValue::LValueBase>;
781 static ObjectUnderConstruction getEmptyKey() {
782 return {Base::getEmptyKey(), {}}; }
783 static ObjectUnderConstruction getTombstoneKey() {
784 return {Base::getTombstoneKey(), {}};
785 }
786 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
787 return hash_value(Object);
788 }
789 static bool isEqual(const ObjectUnderConstruction &LHS,
790 const ObjectUnderConstruction &RHS) {
791 return LHS == RHS;
792 }
793};
794}
795
796namespace {
797 /// A dynamically-allocated heap object.
798 struct DynAlloc {
799 /// The value of this heap-allocated object.
801 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
802 /// or a CallExpr (the latter is for direct calls to operator new inside
803 /// std::allocator<T>::allocate).
804 const Expr *AllocExpr = nullptr;
805
806 enum Kind {
807 New,
808 ArrayNew,
809 StdAllocator
810 };
811
812 /// Get the kind of the allocation. This must match between allocation
813 /// and deallocation.
814 Kind getKind() const {
815 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
816 return NE->isArray() ? ArrayNew : New;
817 assert(isa<CallExpr>(AllocExpr));
818 return StdAllocator;
819 }
820 };
821
822 struct DynAllocOrder {
823 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
824 return L.getIndex() < R.getIndex();
825 }
826 };
827
828 /// EvalInfo - This is a private struct used by the evaluator to capture
829 /// information about a subexpression as it is folded. It retains information
830 /// about the AST context, but also maintains information about the folded
831 /// expression.
832 ///
833 /// If an expression could be evaluated, it is still possible it is not a C
834 /// "integer constant expression" or constant expression. If not, this struct
835 /// captures information about how and why not.
836 ///
837 /// One bit of information passed *into* the request for constant folding
838 /// indicates whether the subexpression is "evaluated" or not according to C
839 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
840 /// evaluate the expression regardless of what the RHS is, but C only allows
841 /// certain things in certain situations.
842 class EvalInfo : public interp::State {
843 public:
844 ASTContext &Ctx;
845
846 /// EvalStatus - Contains information about the evaluation.
847 Expr::EvalStatus &EvalStatus;
848
849 /// CurrentCall - The top of the constexpr call stack.
850 CallStackFrame *CurrentCall;
851
852 /// CallStackDepth - The number of calls in the call stack right now.
853 unsigned CallStackDepth;
854
855 /// NextCallIndex - The next call index to assign.
856 unsigned NextCallIndex;
857
858 /// StepsLeft - The remaining number of evaluation steps we're permitted
859 /// to perform. This is essentially a limit for the number of statements
860 /// we will evaluate.
861 unsigned StepsLeft;
862
863 /// Enable the experimental new constant interpreter. If an expression is
864 /// not supported by the interpreter, an error is triggered.
865 bool EnableNewConstInterp;
866
867 /// BottomFrame - The frame in which evaluation started. This must be
868 /// initialized after CurrentCall and CallStackDepth.
869 CallStackFrame BottomFrame;
870
871 /// A stack of values whose lifetimes end at the end of some surrounding
872 /// evaluation frame.
874
875 /// EvaluatingDecl - This is the declaration whose initializer is being
876 /// evaluated, if any.
877 APValue::LValueBase EvaluatingDecl;
878
879 enum class EvaluatingDeclKind {
880 None,
881 /// We're evaluating the construction of EvaluatingDecl.
882 Ctor,
883 /// We're evaluating the destruction of EvaluatingDecl.
884 Dtor,
885 };
886 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
887
888 /// EvaluatingDeclValue - This is the value being constructed for the
889 /// declaration whose initializer is being evaluated, if any.
890 APValue *EvaluatingDeclValue;
891
892 /// Set of objects that are currently being constructed.
893 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
894 ObjectsUnderConstruction;
895
896 /// Current heap allocations, along with the location where each was
897 /// allocated. We use std::map here because we need stable addresses
898 /// for the stored APValues.
899 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
900
901 /// The number of heap allocations performed so far in this evaluation.
902 unsigned NumHeapAllocs = 0;
903
904 struct EvaluatingConstructorRAII {
905 EvalInfo &EI;
906 ObjectUnderConstruction Object;
907 bool DidInsert;
908 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
909 bool HasBases)
910 : EI(EI), Object(Object) {
911 DidInsert =
912 EI.ObjectsUnderConstruction
913 .insert({Object, HasBases ? ConstructionPhase::Bases
914 : ConstructionPhase::AfterBases})
915 .second;
916 }
917 void finishedConstructingBases() {
918 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
919 }
920 void finishedConstructingFields() {
921 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
922 }
923 ~EvaluatingConstructorRAII() {
924 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
925 }
926 };
927
928 struct EvaluatingDestructorRAII {
929 EvalInfo &EI;
930 ObjectUnderConstruction Object;
931 bool DidInsert;
932 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
933 : EI(EI), Object(Object) {
934 DidInsert = EI.ObjectsUnderConstruction
935 .insert({Object, ConstructionPhase::Destroying})
936 .second;
937 }
938 void startedDestroyingBases() {
939 EI.ObjectsUnderConstruction[Object] =
940 ConstructionPhase::DestroyingBases;
941 }
942 ~EvaluatingDestructorRAII() {
943 if (DidInsert)
944 EI.ObjectsUnderConstruction.erase(Object);
945 }
946 };
947
948 ConstructionPhase
949 isEvaluatingCtorDtor(APValue::LValueBase Base,
951 return ObjectsUnderConstruction.lookup({Base, Path});
952 }
953
954 /// If we're currently speculatively evaluating, the outermost call stack
955 /// depth at which we can mutate state, otherwise 0.
956 unsigned SpeculativeEvaluationDepth = 0;
957
958 /// The current array initialization index, if we're performing array
959 /// initialization.
960 uint64_t ArrayInitIndex = -1;
961
962 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
963 /// notes attached to it will also be stored, otherwise they will not be.
964 bool HasActiveDiagnostic;
965
966 /// Have we emitted a diagnostic explaining why we couldn't constant
967 /// fold (not just why it's not strictly a constant expression)?
968 bool HasFoldFailureDiagnostic;
969
970 /// Whether we're checking that an expression is a potential constant
971 /// expression. If so, do not fail on constructs that could become constant
972 /// later on (such as a use of an undefined global).
973 bool CheckingPotentialConstantExpression = false;
974
975 /// Whether we're checking for an expression that has undefined behavior.
976 /// If so, we will produce warnings if we encounter an operation that is
977 /// always undefined.
978 ///
979 /// Note that we still need to evaluate the expression normally when this
980 /// is set; this is used when evaluating ICEs in C.
981 bool CheckingForUndefinedBehavior = false;
982
983 enum EvaluationMode {
984 /// Evaluate as a constant expression. Stop if we find that the expression
985 /// is not a constant expression.
986 EM_ConstantExpression,
987
988 /// Evaluate as a constant expression. Stop if we find that the expression
989 /// is not a constant expression. Some expressions can be retried in the
990 /// optimizer if we don't constant fold them here, but in an unevaluated
991 /// context we try to fold them immediately since the optimizer never
992 /// gets a chance to look at it.
993 EM_ConstantExpressionUnevaluated,
994
995 /// Fold the expression to a constant. Stop if we hit a side-effect that
996 /// we can't model.
997 EM_ConstantFold,
998
999 /// Evaluate in any way we know how. Don't worry about side-effects that
1000 /// can't be modeled.
1001 EM_IgnoreSideEffects,
1002 } EvalMode;
1003
1004 /// Are we checking whether the expression is a potential constant
1005 /// expression?
1006 bool checkingPotentialConstantExpression() const override {
1007 return CheckingPotentialConstantExpression;
1008 }
1009
1010 /// Are we checking an expression for overflow?
1011 // FIXME: We should check for any kind of undefined or suspicious behavior
1012 // in such constructs, not just overflow.
1013 bool checkingForUndefinedBehavior() const override {
1014 return CheckingForUndefinedBehavior;
1015 }
1016
1017 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
1018 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
1019 CallStackDepth(0), NextCallIndex(1),
1020 StepsLeft(C.getLangOpts().ConstexprStepLimit),
1021 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
1022 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
1023 /*This=*/nullptr,
1024 /*CallExpr=*/nullptr, CallRef()),
1025 EvaluatingDecl((const ValueDecl *)nullptr),
1026 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
1027 HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
1028
1029 ~EvalInfo() {
1030 discardCleanups();
1031 }
1032
1033 ASTContext &getCtx() const override { return Ctx; }
1034
1035 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
1036 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
1037 EvaluatingDecl = Base;
1038 IsEvaluatingDecl = EDK;
1039 EvaluatingDeclValue = &Value;
1040 }
1041
1042 bool CheckCallLimit(SourceLocation Loc) {
1043 // Don't perform any constexpr calls (other than the call we're checking)
1044 // when checking a potential constant expression.
1045 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1046 return false;
1047 if (NextCallIndex == 0) {
1048 // NextCallIndex has wrapped around.
1049 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1050 return false;
1051 }
1052 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1053 return true;
1054 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1055 << getLangOpts().ConstexprCallDepth;
1056 return false;
1057 }
1058
1059 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
1060 uint64_t ElemCount, bool Diag) {
1061 // FIXME: GH63562
1062 // APValue stores array extents as unsigned,
1063 // so anything that is greater that unsigned would overflow when
1064 // constructing the array, we catch this here.
1065 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
1066 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
1067 if (Diag)
1068 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
1069 return false;
1070 }
1071
1072 // FIXME: GH63562
1073 // Arrays allocate an APValue per element.
1074 // We use the number of constexpr steps as a proxy for the maximum size
1075 // of arrays to avoid exhausting the system resources, as initialization
1076 // of each element is likely to take some number of steps anyway.
1077 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
1078 if (ElemCount > Limit) {
1079 if (Diag)
1080 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
1081 << ElemCount << Limit;
1082 return false;
1083 }
1084 return true;
1085 }
1086
1087 std::pair<CallStackFrame *, unsigned>
1088 getCallFrameAndDepth(unsigned CallIndex) {
1089 assert(CallIndex && "no call index in getCallFrameAndDepth");
1090 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1091 // be null in this loop.
1092 unsigned Depth = CallStackDepth;
1093 CallStackFrame *Frame = CurrentCall;
1094 while (Frame->Index > CallIndex) {
1095 Frame = Frame->Caller;
1096 --Depth;
1097 }
1098 if (Frame->Index == CallIndex)
1099 return {Frame, Depth};
1100 return {nullptr, 0};
1101 }
1102
1103 bool nextStep(const Stmt *S) {
1104 if (!StepsLeft) {
1105 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1106 return false;
1107 }
1108 --StepsLeft;
1109 return true;
1110 }
1111
1112 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1113
1114 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1115 std::optional<DynAlloc *> Result;
1116 auto It = HeapAllocs.find(DA);
1117 if (It != HeapAllocs.end())
1118 Result = &It->second;
1119 return Result;
1120 }
1121
1122 /// Get the allocated storage for the given parameter of the given call.
1123 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1124 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1125 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1126 : nullptr;
1127 }
1128
1129 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1130 struct StdAllocatorCaller {
1131 unsigned FrameIndex;
1132 QualType ElemType;
1133 explicit operator bool() const { return FrameIndex != 0; };
1134 };
1135
1136 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1137 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1138 Call = Call->Caller) {
1139 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1140 if (!MD)
1141 continue;
1142 const IdentifierInfo *FnII = MD->getIdentifier();
1143 if (!FnII || !FnII->isStr(FnName))
1144 continue;
1145
1146 const auto *CTSD =
1147 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1148 if (!CTSD)
1149 continue;
1150
1151 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1152 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1153 if (CTSD->isInStdNamespace() && ClassII &&
1154 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1155 TAL[0].getKind() == TemplateArgument::Type)
1156 return {Call->Index, TAL[0].getAsType()};
1157 }
1158
1159 return {};
1160 }
1161
1162 void performLifetimeExtension() {
1163 // Disable the cleanups for lifetime-extended temporaries.
1164 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1165 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1166 });
1167 }
1168
1169 /// Throw away any remaining cleanups at the end of evaluation. If any
1170 /// cleanups would have had a side-effect, note that as an unmodeled
1171 /// side-effect and return false. Otherwise, return true.
1172 bool discardCleanups() {
1173 for (Cleanup &C : CleanupStack) {
1174 if (C.hasSideEffect() && !noteSideEffect()) {
1175 CleanupStack.clear();
1176 return false;
1177 }
1178 }
1179 CleanupStack.clear();
1180 return true;
1181 }
1182
1183 private:
1184 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1185 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1186
1187 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1188 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1189
1190 void setFoldFailureDiagnostic(bool Flag) override {
1191 HasFoldFailureDiagnostic = Flag;
1192 }
1193
1194 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1195
1196 // If we have a prior diagnostic, it will be noting that the expression
1197 // isn't a constant expression. This diagnostic is more important,
1198 // unless we require this evaluation to produce a constant expression.
1199 //
1200 // FIXME: We might want to show both diagnostics to the user in
1201 // EM_ConstantFold mode.
1202 bool hasPriorDiagnostic() override {
1203 if (!EvalStatus.Diag->empty()) {
1204 switch (EvalMode) {
1205 case EM_ConstantFold:
1206 case EM_IgnoreSideEffects:
1207 if (!HasFoldFailureDiagnostic)
1208 break;
1209 // We've already failed to fold something. Keep that diagnostic.
1210 [[fallthrough]];
1211 case EM_ConstantExpression:
1212 case EM_ConstantExpressionUnevaluated:
1213 setActiveDiagnostic(false);
1214 return true;
1215 }
1216 }
1217 return false;
1218 }
1219
1220 unsigned getCallStackDepth() override { return CallStackDepth; }
1221
1222 public:
1223 /// Should we continue evaluation after encountering a side-effect that we
1224 /// couldn't model?
1225 bool keepEvaluatingAfterSideEffect() {
1226 switch (EvalMode) {
1227 case EM_IgnoreSideEffects:
1228 return true;
1229
1230 case EM_ConstantExpression:
1231 case EM_ConstantExpressionUnevaluated:
1232 case EM_ConstantFold:
1233 // By default, assume any side effect might be valid in some other
1234 // evaluation of this expression from a different context.
1235 return checkingPotentialConstantExpression() ||
1236 checkingForUndefinedBehavior();
1237 }
1238 llvm_unreachable("Missed EvalMode case");
1239 }
1240
1241 /// Note that we have had a side-effect, and determine whether we should
1242 /// keep evaluating.
1243 bool noteSideEffect() {
1244 EvalStatus.HasSideEffects = true;
1245 return keepEvaluatingAfterSideEffect();
1246 }
1247
1248 /// Should we continue evaluation after encountering undefined behavior?
1249 bool keepEvaluatingAfterUndefinedBehavior() {
1250 switch (EvalMode) {
1251 case EM_IgnoreSideEffects:
1252 case EM_ConstantFold:
1253 return true;
1254
1255 case EM_ConstantExpression:
1256 case EM_ConstantExpressionUnevaluated:
1257 return checkingForUndefinedBehavior();
1258 }
1259 llvm_unreachable("Missed EvalMode case");
1260 }
1261
1262 /// Note that we hit something that was technically undefined behavior, but
1263 /// that we can evaluate past it (such as signed overflow or floating-point
1264 /// division by zero.)
1265 bool noteUndefinedBehavior() override {
1266 EvalStatus.HasUndefinedBehavior = true;
1267 return keepEvaluatingAfterUndefinedBehavior();
1268 }
1269
1270 /// Should we continue evaluation as much as possible after encountering a
1271 /// construct which can't be reduced to a value?
1272 bool keepEvaluatingAfterFailure() const override {
1273 if (!StepsLeft)
1274 return false;
1275
1276 switch (EvalMode) {
1277 case EM_ConstantExpression:
1278 case EM_ConstantExpressionUnevaluated:
1279 case EM_ConstantFold:
1280 case EM_IgnoreSideEffects:
1281 return checkingPotentialConstantExpression() ||
1282 checkingForUndefinedBehavior();
1283 }
1284 llvm_unreachable("Missed EvalMode case");
1285 }
1286
1287 /// Notes that we failed to evaluate an expression that other expressions
1288 /// directly depend on, and determine if we should keep evaluating. This
1289 /// should only be called if we actually intend to keep evaluating.
1290 ///
1291 /// Call noteSideEffect() instead if we may be able to ignore the value that
1292 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1293 ///
1294 /// (Foo(), 1) // use noteSideEffect
1295 /// (Foo() || true) // use noteSideEffect
1296 /// Foo() + 1 // use noteFailure
1297 [[nodiscard]] bool noteFailure() {
1298 // Failure when evaluating some expression often means there is some
1299 // subexpression whose evaluation was skipped. Therefore, (because we
1300 // don't track whether we skipped an expression when unwinding after an
1301 // evaluation failure) every evaluation failure that bubbles up from a
1302 // subexpression implies that a side-effect has potentially happened. We
1303 // skip setting the HasSideEffects flag to true until we decide to
1304 // continue evaluating after that point, which happens here.
1305 bool KeepGoing = keepEvaluatingAfterFailure();
1306 EvalStatus.HasSideEffects |= KeepGoing;
1307 return KeepGoing;
1308 }
1309
1310 class ArrayInitLoopIndex {
1311 EvalInfo &Info;
1312 uint64_t OuterIndex;
1313
1314 public:
1315 ArrayInitLoopIndex(EvalInfo &Info)
1316 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1317 Info.ArrayInitIndex = 0;
1318 }
1319 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1320
1321 operator uint64_t&() { return Info.ArrayInitIndex; }
1322 };
1323 };
1324
1325 /// Object used to treat all foldable expressions as constant expressions.
1326 struct FoldConstant {
1327 EvalInfo &Info;
1328 bool Enabled;
1329 bool HadNoPriorDiags;
1330 EvalInfo::EvaluationMode OldMode;
1331
1332 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1333 : Info(Info),
1334 Enabled(Enabled),
1335 HadNoPriorDiags(Info.EvalStatus.Diag &&
1336 Info.EvalStatus.Diag->empty() &&
1337 !Info.EvalStatus.HasSideEffects),
1338 OldMode(Info.EvalMode) {
1339 if (Enabled)
1340 Info.EvalMode = EvalInfo::EM_ConstantFold;
1341 }
1342 void keepDiagnostics() { Enabled = false; }
1343 ~FoldConstant() {
1344 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1345 !Info.EvalStatus.HasSideEffects)
1346 Info.EvalStatus.Diag->clear();
1347 Info.EvalMode = OldMode;
1348 }
1349 };
1350
1351 /// RAII object used to set the current evaluation mode to ignore
1352 /// side-effects.
1353 struct IgnoreSideEffectsRAII {
1354 EvalInfo &Info;
1355 EvalInfo::EvaluationMode OldMode;
1356 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1357 : Info(Info), OldMode(Info.EvalMode) {
1358 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1359 }
1360
1361 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1362 };
1363
1364 /// RAII object used to optionally suppress diagnostics and side-effects from
1365 /// a speculative evaluation.
1366 class SpeculativeEvaluationRAII {
1367 EvalInfo *Info = nullptr;
1368 Expr::EvalStatus OldStatus;
1369 unsigned OldSpeculativeEvaluationDepth = 0;
1370
1371 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1372 Info = Other.Info;
1373 OldStatus = Other.OldStatus;
1374 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1375 Other.Info = nullptr;
1376 }
1377
1378 void maybeRestoreState() {
1379 if (!Info)
1380 return;
1381
1382 Info->EvalStatus = OldStatus;
1383 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1384 }
1385
1386 public:
1387 SpeculativeEvaluationRAII() = default;
1388
1389 SpeculativeEvaluationRAII(
1390 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1391 : Info(&Info), OldStatus(Info.EvalStatus),
1392 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1393 Info.EvalStatus.Diag = NewDiag;
1394 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1395 }
1396
1397 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1398 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1399 moveFromAndCancel(std::move(Other));
1400 }
1401
1402 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1403 maybeRestoreState();
1404 moveFromAndCancel(std::move(Other));
1405 return *this;
1406 }
1407
1408 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1409 };
1410
1411 /// RAII object wrapping a full-expression or block scope, and handling
1412 /// the ending of the lifetime of temporaries created within it.
1413 template<ScopeKind Kind>
1414 class ScopeRAII {
1415 EvalInfo &Info;
1416 unsigned OldStackSize;
1417 public:
1418 ScopeRAII(EvalInfo &Info)
1419 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1420 // Push a new temporary version. This is needed to distinguish between
1421 // temporaries created in different iterations of a loop.
1422 Info.CurrentCall->pushTempVersion();
1423 }
1424 bool destroy(bool RunDestructors = true) {
1425 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1426 OldStackSize = -1U;
1427 return OK;
1428 }
1429 ~ScopeRAII() {
1430 if (OldStackSize != -1U)
1431 destroy(false);
1432 // Body moved to a static method to encourage the compiler to inline away
1433 // instances of this class.
1434 Info.CurrentCall->popTempVersion();
1435 }
1436 private:
1437 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1438 unsigned OldStackSize) {
1439 assert(OldStackSize <= Info.CleanupStack.size() &&
1440 "running cleanups out of order?");
1441
1442 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1443 // for a full-expression scope.
1444 bool Success = true;
1445 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1446 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1447 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1448 Success = false;
1449 break;
1450 }
1451 }
1452 }
1453
1454 // Compact any retained cleanups.
1455 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1456 if (Kind != ScopeKind::Block)
1457 NewEnd =
1458 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1459 return C.isDestroyedAtEndOf(Kind);
1460 });
1461 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1462 return Success;
1463 }
1464 };
1465 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1466 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1467 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1468}
1469
1470bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1471 CheckSubobjectKind CSK) {
1472 if (Invalid)
1473 return false;
1474 if (isOnePastTheEnd()) {
1475 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1476 << CSK;
1477 setInvalid();
1478 return false;
1479 }
1480 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1481 // must actually be at least one array element; even a VLA cannot have a
1482 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1483 return true;
1484}
1485
1486void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1487 const Expr *E) {
1488 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1489 // Do not set the designator as invalid: we can represent this situation,
1490 // and correct handling of __builtin_object_size requires us to do so.
1491}
1492
1493void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1494 const Expr *E,
1495 const APSInt &N) {
1496 // If we're complaining, we must be able to statically determine the size of
1497 // the most derived array.
1498 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1499 Info.CCEDiag(E, diag::note_constexpr_array_index)
1500 << N << /*array*/ 0
1501 << static_cast<unsigned>(getMostDerivedArraySize());
1502 else
1503 Info.CCEDiag(E, diag::note_constexpr_array_index)
1504 << N << /*non-array*/ 1;
1505 setInvalid();
1506}
1507
1508CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1509 const FunctionDecl *Callee, const LValue *This,
1510 const Expr *CallExpr, CallRef Call)
1511 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1512 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1513 Index(Info.NextCallIndex++) {
1514 Info.CurrentCall = this;
1515 ++Info.CallStackDepth;
1516}
1517
1518CallStackFrame::~CallStackFrame() {
1519 assert(Info.CurrentCall == this && "calls retired out of order");
1520 --Info.CallStackDepth;
1521 Info.CurrentCall = Caller;
1522}
1523
1524static bool isRead(AccessKinds AK) {
1525 return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1526}
1527
1529 switch (AK) {
1530 case AK_Read:
1532 case AK_MemberCall:
1533 case AK_DynamicCast:
1534 case AK_TypeId:
1535 return false;
1536 case AK_Assign:
1537 case AK_Increment:
1538 case AK_Decrement:
1539 case AK_Construct:
1540 case AK_Destroy:
1541 return true;
1542 }
1543 llvm_unreachable("unknown access kind");
1544}
1545
1546static bool isAnyAccess(AccessKinds AK) {
1547 return isRead(AK) || isModification(AK);
1548}
1549
1550/// Is this an access per the C++ definition?
1552 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1553}
1554
1555/// Is this kind of axcess valid on an indeterminate object value?
1557 switch (AK) {
1558 case AK_Read:
1559 case AK_Increment:
1560 case AK_Decrement:
1561 // These need the object's value.
1562 return false;
1563
1565 case AK_Assign:
1566 case AK_Construct:
1567 case AK_Destroy:
1568 // Construction and destruction don't need the value.
1569 return true;
1570
1571 case AK_MemberCall:
1572 case AK_DynamicCast:
1573 case AK_TypeId:
1574 // These aren't really meaningful on scalars.
1575 return true;
1576 }
1577 llvm_unreachable("unknown access kind");
1578}
1579
1580namespace {
1581 struct ComplexValue {
1582 private:
1583 bool IsInt;
1584
1585 public:
1586 APSInt IntReal, IntImag;
1587 APFloat FloatReal, FloatImag;
1588
1589 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1590
1591 void makeComplexFloat() { IsInt = false; }
1592 bool isComplexFloat() const { return !IsInt; }
1593 APFloat &getComplexFloatReal() { return FloatReal; }
1594 APFloat &getComplexFloatImag() { return FloatImag; }
1595
1596 void makeComplexInt() { IsInt = true; }
1597 bool isComplexInt() const { return IsInt; }
1598 APSInt &getComplexIntReal() { return IntReal; }
1599 APSInt &getComplexIntImag() { return IntImag; }
1600
1601 void moveInto(APValue &v) const {
1602 if (isComplexFloat())
1603 v = APValue(FloatReal, FloatImag);
1604 else
1605 v = APValue(IntReal, IntImag);
1606 }
1607 void setFrom(const APValue &v) {
1608 assert(v.isComplexFloat() || v.isComplexInt());
1609 if (v.isComplexFloat()) {
1610 makeComplexFloat();
1611 FloatReal = v.getComplexFloatReal();
1612 FloatImag = v.getComplexFloatImag();
1613 } else {
1614 makeComplexInt();
1615 IntReal = v.getComplexIntReal();
1616 IntImag = v.getComplexIntImag();
1617 }
1618 }
1619 };
1620
1621 struct LValue {
1623 CharUnits Offset;
1624 SubobjectDesignator Designator;
1625 bool IsNullPtr : 1;
1626 bool InvalidBase : 1;
1627
1628 const APValue::LValueBase getLValueBase() const { return Base; }
1629 CharUnits &getLValueOffset() { return Offset; }
1630 const CharUnits &getLValueOffset() const { return Offset; }
1631 SubobjectDesignator &getLValueDesignator() { return Designator; }
1632 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1633 bool isNullPointer() const { return IsNullPtr;}
1634
1635 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1636 unsigned getLValueVersion() const { return Base.getVersion(); }
1637
1638 void moveInto(APValue &V) const {
1639 if (Designator.Invalid)
1640 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1641 else {
1642 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1643 V = APValue(Base, Offset, Designator.Entries,
1644 Designator.IsOnePastTheEnd, IsNullPtr);
1645 }
1646 }
1647 void setFrom(ASTContext &Ctx, const APValue &V) {
1648 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1649 Base = V.getLValueBase();
1650 Offset = V.getLValueOffset();
1651 InvalidBase = false;
1652 Designator = SubobjectDesignator(Ctx, V);
1653 IsNullPtr = V.isNullPointer();
1654 }
1655
1656 void set(APValue::LValueBase B, bool BInvalid = false) {
1657#ifndef NDEBUG
1658 // We only allow a few types of invalid bases. Enforce that here.
1659 if (BInvalid) {
1660 const auto *E = B.get<const Expr *>();
1661 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1662 "Unexpected type of invalid base");
1663 }
1664#endif
1665
1666 Base = B;
1667 Offset = CharUnits::fromQuantity(0);
1668 InvalidBase = BInvalid;
1669 Designator = SubobjectDesignator(getType(B));
1670 IsNullPtr = false;
1671 }
1672
1673 void setNull(ASTContext &Ctx, QualType PointerTy) {
1674 Base = (const ValueDecl *)nullptr;
1675 Offset =
1677 InvalidBase = false;
1678 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1679 IsNullPtr = true;
1680 }
1681
1682 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1683 set(B, true);
1684 }
1685
1686 std::string toString(ASTContext &Ctx, QualType T) const {
1687 APValue Printable;
1688 moveInto(Printable);
1689 return Printable.getAsString(Ctx, T);
1690 }
1691
1692 private:
1693 // Check that this LValue is not based on a null pointer. If it is, produce
1694 // a diagnostic and mark the designator as invalid.
1695 template <typename GenDiagType>
1696 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1697 if (Designator.Invalid)
1698 return false;
1699 if (IsNullPtr) {
1700 GenDiag();
1701 Designator.setInvalid();
1702 return false;
1703 }
1704 return true;
1705 }
1706
1707 public:
1708 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1709 CheckSubobjectKind CSK) {
1710 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1711 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1712 });
1713 }
1714
1715 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1716 AccessKinds AK) {
1717 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1718 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1719 });
1720 }
1721
1722 // Check this LValue refers to an object. If not, set the designator to be
1723 // invalid and emit a diagnostic.
1724 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1725 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1726 Designator.checkSubobject(Info, E, CSK);
1727 }
1728
1729 void addDecl(EvalInfo &Info, const Expr *E,
1730 const Decl *D, bool Virtual = false) {
1731 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1732 Designator.addDeclUnchecked(D, Virtual);
1733 }
1734 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1735 if (!Designator.Entries.empty()) {
1736 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1737 Designator.setInvalid();
1738 return;
1739 }
1740 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1741 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1742 Designator.FirstEntryIsAnUnsizedArray = true;
1743 Designator.addUnsizedArrayUnchecked(ElemTy);
1744 }
1745 }
1746 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1747 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1748 Designator.addArrayUnchecked(CAT);
1749 }
1750 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1751 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1752 Designator.addComplexUnchecked(EltTy, Imag);
1753 }
1754 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1755 uint64_t Size, uint64_t Idx) {
1756 if (checkSubobject(Info, E, CSK_VectorElement))
1757 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1758 }
1759 void clearIsNullPointer() {
1760 IsNullPtr = false;
1761 }
1762 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1763 const APSInt &Index, CharUnits ElementSize) {
1764 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1765 // but we're not required to diagnose it and it's valid in C++.)
1766 if (!Index)
1767 return;
1768
1769 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1770 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1771 // offsets.
1772 uint64_t Offset64 = Offset.getQuantity();
1773 uint64_t ElemSize64 = ElementSize.getQuantity();
1774 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1775 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1776
1777 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1778 Designator.adjustIndex(Info, E, Index);
1779 clearIsNullPointer();
1780 }
1781 void adjustOffset(CharUnits N) {
1782 Offset += N;
1783 if (N.getQuantity())
1784 clearIsNullPointer();
1785 }
1786 };
1787
1788 struct MemberPtr {
1789 MemberPtr() {}
1790 explicit MemberPtr(const ValueDecl *Decl)
1791 : DeclAndIsDerivedMember(Decl, false) {}
1792
1793 /// The member or (direct or indirect) field referred to by this member
1794 /// pointer, or 0 if this is a null member pointer.
1795 const ValueDecl *getDecl() const {
1796 return DeclAndIsDerivedMember.getPointer();
1797 }
1798 /// Is this actually a member of some type derived from the relevant class?
1799 bool isDerivedMember() const {
1800 return DeclAndIsDerivedMember.getInt();
1801 }
1802 /// Get the class which the declaration actually lives in.
1803 const CXXRecordDecl *getContainingRecord() const {
1804 return cast<CXXRecordDecl>(
1805 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1806 }
1807
1808 void moveInto(APValue &V) const {
1809 V = APValue(getDecl(), isDerivedMember(), Path);
1810 }
1811 void setFrom(const APValue &V) {
1812 assert(V.isMemberPointer());
1813 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1814 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1815 Path.clear();
1816 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1817 Path.insert(Path.end(), P.begin(), P.end());
1818 }
1819
1820 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1821 /// whether the member is a member of some class derived from the class type
1822 /// of the member pointer.
1823 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1824 /// Path - The path of base/derived classes from the member declaration's
1825 /// class (exclusive) to the class type of the member pointer (inclusive).
1827
1828 /// Perform a cast towards the class of the Decl (either up or down the
1829 /// hierarchy).
1830 bool castBack(const CXXRecordDecl *Class) {
1831 assert(!Path.empty());
1832 const CXXRecordDecl *Expected;
1833 if (Path.size() >= 2)
1834 Expected = Path[Path.size() - 2];
1835 else
1836 Expected = getContainingRecord();
1837 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1838 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1839 // if B does not contain the original member and is not a base or
1840 // derived class of the class containing the original member, the result
1841 // of the cast is undefined.
1842 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1843 // (D::*). We consider that to be a language defect.
1844 return false;
1845 }
1846 Path.pop_back();
1847 return true;
1848 }
1849 /// Perform a base-to-derived member pointer cast.
1850 bool castToDerived(const CXXRecordDecl *Derived) {
1851 if (!getDecl())
1852 return true;
1853 if (!isDerivedMember()) {
1854 Path.push_back(Derived);
1855 return true;
1856 }
1857 if (!castBack(Derived))
1858 return false;
1859 if (Path.empty())
1860 DeclAndIsDerivedMember.setInt(false);
1861 return true;
1862 }
1863 /// Perform a derived-to-base member pointer cast.
1864 bool castToBase(const CXXRecordDecl *Base) {
1865 if (!getDecl())
1866 return true;
1867 if (Path.empty())
1868 DeclAndIsDerivedMember.setInt(true);
1869 if (isDerivedMember()) {
1870 Path.push_back(Base);
1871 return true;
1872 }
1873 return castBack(Base);
1874 }
1875 };
1876
1877 /// Compare two member pointers, which are assumed to be of the same type.
1878 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1879 if (!LHS.getDecl() || !RHS.getDecl())
1880 return !LHS.getDecl() && !RHS.getDecl();
1881 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1882 return false;
1883 return LHS.Path == RHS.Path;
1884 }
1885}
1886
1887static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1888static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1889 const LValue &This, const Expr *E,
1890 bool AllowNonLiteralTypes = false);
1891static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1892 bool InvalidBaseOK = false);
1893static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1894 bool InvalidBaseOK = false);
1895static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1896 EvalInfo &Info);
1897static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1898static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1899static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1900 EvalInfo &Info);
1901static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1902static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1903static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1904 EvalInfo &Info);
1905static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1906static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1907 EvalInfo &Info,
1908 std::string *StringResult = nullptr);
1909
1910/// Evaluate an integer or fixed point expression into an APResult.
1911static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1912 EvalInfo &Info);
1913
1914/// Evaluate only a fixed point expression into an APResult.
1915static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1916 EvalInfo &Info);
1917
1918//===----------------------------------------------------------------------===//
1919// Misc utilities
1920//===----------------------------------------------------------------------===//
1921
1922/// Negate an APSInt in place, converting it to a signed form if necessary, and
1923/// preserving its value (by extending by up to one bit as needed).
1924static void negateAsSigned(APSInt &Int) {
1925 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1926 Int = Int.extend(Int.getBitWidth() + 1);
1927 Int.setIsSigned(true);
1928 }
1929 Int = -Int;
1930}
1931
1932template<typename KeyT>
1933APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1934 ScopeKind Scope, LValue &LV) {
1935 unsigned Version = getTempVersion();
1936 APValue::LValueBase Base(Key, Index, Version);
1937 LV.set(Base);
1938 return createLocal(Base, Key, T, Scope);
1939}
1940
1941/// Allocate storage for a parameter of a function call made in this frame.
1942APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1943 LValue &LV) {
1944 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1945 APValue::LValueBase Base(PVD, Index, Args.Version);
1946 LV.set(Base);
1947 // We always destroy parameters at the end of the call, even if we'd allow
1948 // them to live to the end of the full-expression at runtime, in order to
1949 // give portable results and match other compilers.
1950 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1951}
1952
1953APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1954 QualType T, ScopeKind Scope) {
1955 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1956 unsigned Version = Base.getVersion();
1957 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1958 assert(Result.isAbsent() && "local created multiple times");
1959
1960 // If we're creating a local immediately in the operand of a speculative
1961 // evaluation, don't register a cleanup to be run outside the speculative
1962 // evaluation context, since we won't actually be able to initialize this
1963 // object.
1964 if (Index <= Info.SpeculativeEvaluationDepth) {
1965 if (T.isDestructedType())
1966 Info.noteSideEffect();
1967 } else {
1968 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1969 }
1970 return Result;
1971}
1972
1973APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1974 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1975 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1976 return nullptr;
1977 }
1978
1979 DynamicAllocLValue DA(NumHeapAllocs++);
1981 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1982 std::forward_as_tuple(DA), std::tuple<>());
1983 assert(Result.second && "reused a heap alloc index?");
1984 Result.first->second.AllocExpr = E;
1985 return &Result.first->second.Value;
1986}
1987
1988/// Produce a string describing the given constexpr call.
1989void CallStackFrame::describe(raw_ostream &Out) const {
1990 unsigned ArgIndex = 0;
1991 bool IsMemberCall =
1992 isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
1993 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
1994
1995 if (!IsMemberCall)
1996 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1997 /*Qualified=*/false);
1998
1999 if (This && IsMemberCall) {
2000 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
2001 const Expr *Object = MCE->getImplicitObjectArgument();
2002 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
2003 /*Indentation=*/0);
2004 if (Object->getType()->isPointerType())
2005 Out << "->";
2006 else
2007 Out << ".";
2008 } else if (const auto *OCE =
2009 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
2010 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
2011 Info.Ctx.getPrintingPolicy(),
2012 /*Indentation=*/0);
2013 Out << ".";
2014 } else {
2015 APValue Val;
2016 This->moveInto(Val);
2017 Val.printPretty(
2018 Out, Info.Ctx,
2019 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
2020 Out << ".";
2021 }
2022 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2023 /*Qualified=*/false);
2024 IsMemberCall = false;
2025 }
2026
2027 Out << '(';
2028
2029 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2030 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2031 if (ArgIndex > (unsigned)IsMemberCall)
2032 Out << ", ";
2033
2034 const ParmVarDecl *Param = *I;
2035 APValue *V = Info.getParamSlot(Arguments, Param);
2036 if (V)
2037 V->printPretty(Out, Info.Ctx, Param->getType());
2038 else
2039 Out << "<...>";
2040
2041 if (ArgIndex == 0 && IsMemberCall)
2042 Out << "->" << *Callee << '(';
2043 }
2044
2045 Out << ')';
2046}
2047
2048/// Evaluate an expression to see if it had side-effects, and discard its
2049/// result.
2050/// \return \c true if the caller should keep evaluating.
2051static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2052 assert(!E->isValueDependent());
2053 APValue Scratch;
2054 if (!Evaluate(Scratch, Info, E))
2055 // We don't need the value, but we might have skipped a side effect here.
2056 return Info.noteSideEffect();
2057 return true;
2058}
2059
2060/// Should this call expression be treated as a no-op?
2061static bool IsNoOpCall(const CallExpr *E) {
2062 unsigned Builtin = E->getBuiltinCallee();
2063 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2064 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2065 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
2066 Builtin == Builtin::BI__builtin_function_start);
2067}
2068
2070 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2071 // constant expression of pointer type that evaluates to...
2072
2073 // ... a null pointer value, or a prvalue core constant expression of type
2074 // std::nullptr_t.
2075 if (!B)
2076 return true;
2077
2078 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2079 // ... the address of an object with static storage duration,
2080 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2081 return VD->hasGlobalStorage();
2082 if (isa<TemplateParamObjectDecl>(D))
2083 return true;
2084 // ... the address of a function,
2085 // ... the address of a GUID [MS extension],
2086 // ... the address of an unnamed global constant
2087 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
2088 }
2089
2090 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2091 return true;
2092
2093 const Expr *E = B.get<const Expr*>();
2094 switch (E->getStmtClass()) {
2095 default:
2096 return false;
2097 case Expr::CompoundLiteralExprClass: {
2098 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2099 return CLE->isFileScope() && CLE->isLValue();
2100 }
2101 case Expr::MaterializeTemporaryExprClass:
2102 // A materialized temporary might have been lifetime-extended to static
2103 // storage duration.
2104 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2105 // A string literal has static storage duration.
2106 case Expr::StringLiteralClass:
2107 case Expr::PredefinedExprClass:
2108 case Expr::ObjCStringLiteralClass:
2109 case Expr::ObjCEncodeExprClass:
2110 return true;
2111 case Expr::ObjCBoxedExprClass:
2112 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2113 case Expr::CallExprClass:
2114 return IsNoOpCall(cast<CallExpr>(E));
2115 // For GCC compatibility, &&label has static storage duration.
2116 case Expr::AddrLabelExprClass:
2117 return true;
2118 // A Block literal expression may be used as the initialization value for
2119 // Block variables at global or local static scope.
2120 case Expr::BlockExprClass:
2121 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2122 // The APValue generated from a __builtin_source_location will be emitted as a
2123 // literal.
2124 case Expr::SourceLocExprClass:
2125 return true;
2126 case Expr::ImplicitValueInitExprClass:
2127 // FIXME:
2128 // We can never form an lvalue with an implicit value initialization as its
2129 // base through expression evaluation, so these only appear in one case: the
2130 // implicit variable declaration we invent when checking whether a constexpr
2131 // constructor can produce a constant expression. We must assume that such
2132 // an expression might be a global lvalue.
2133 return true;
2134 }
2135}
2136
2137static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2138 return LVal.Base.dyn_cast<const ValueDecl*>();
2139}
2140
2141static bool IsLiteralLValue(const LValue &Value) {
2142 if (Value.getLValueCallIndex())
2143 return false;
2144 const Expr *E = Value.Base.dyn_cast<const Expr*>();
2145 return E && !isa<MaterializeTemporaryExpr>(E);
2146}
2147
2148static bool IsWeakLValue(const LValue &Value) {
2150 return Decl && Decl->isWeak();
2151}
2152
2153static bool isZeroSized(const LValue &Value) {
2155 if (isa_and_nonnull<VarDecl>(Decl)) {
2156 QualType Ty = Decl->getType();
2157 if (Ty->isArrayType())
2158 return Ty->isIncompleteType() ||
2159 Decl->getASTContext().getTypeSize(Ty) == 0;
2160 }
2161 return false;
2162}
2163
2164static bool HasSameBase(const LValue &A, const LValue &B) {
2165 if (!A.getLValueBase())
2166 return !B.getLValueBase();
2167 if (!B.getLValueBase())
2168 return false;
2169
2170 if (A.getLValueBase().getOpaqueValue() !=
2171 B.getLValueBase().getOpaqueValue())
2172 return false;
2173
2174 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2175 A.getLValueVersion() == B.getLValueVersion();
2176}
2177
2178static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2179 assert(Base && "no location for a null lvalue");
2180 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2181
2182 // For a parameter, find the corresponding call stack frame (if it still
2183 // exists), and point at the parameter of the function definition we actually
2184 // invoked.
2185 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2186 unsigned Idx = PVD->getFunctionScopeIndex();
2187 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2188 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2189 F->Arguments.Version == Base.getVersion() && F->Callee &&
2190 Idx < F->Callee->getNumParams()) {
2191 VD = F->Callee->getParamDecl(Idx);
2192 break;
2193 }
2194 }
2195 }
2196
2197 if (VD)
2198 Info.Note(VD->getLocation(), diag::note_declared_at);
2199 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2200 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2201 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2202 // FIXME: Produce a note for dangling pointers too.
2203 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2204 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2205 diag::note_constexpr_dynamic_alloc_here);
2206 }
2207
2208 // We have no information to show for a typeid(T) object.
2209}
2210
2214};
2215
2216/// Materialized temporaries that we've already checked to determine if they're
2217/// initializsed by a constant expression.
2220
2222 EvalInfo &Info, SourceLocation DiagLoc,
2223 QualType Type, const APValue &Value,
2224 ConstantExprKind Kind,
2225 const FieldDecl *SubobjectDecl,
2226 CheckedTemporaries &CheckedTemps);
2227
2228/// Check that this reference or pointer core constant expression is a valid
2229/// value for an address or reference constant expression. Return true if we
2230/// can fold this expression, whether or not it's a constant expression.
2232 QualType Type, const LValue &LVal,
2233 ConstantExprKind Kind,
2234 CheckedTemporaries &CheckedTemps) {
2235 bool IsReferenceType = Type->isReferenceType();
2236
2237 APValue::LValueBase Base = LVal.getLValueBase();
2238 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2239
2240 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2241 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2242
2243 // Additional restrictions apply in a template argument. We only enforce the
2244 // C++20 restrictions here; additional syntactic and semantic restrictions
2245 // are applied elsewhere.
2246 if (isTemplateArgument(Kind)) {
2247 int InvalidBaseKind = -1;
2248 StringRef Ident;
2249 if (Base.is<TypeInfoLValue>())
2250 InvalidBaseKind = 0;
2251 else if (isa_and_nonnull<StringLiteral>(BaseE))
2252 InvalidBaseKind = 1;
2253 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2254 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2255 InvalidBaseKind = 2;
2256 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2257 InvalidBaseKind = 3;
2258 Ident = PE->getIdentKindName();
2259 }
2260
2261 if (InvalidBaseKind != -1) {
2262 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2263 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2264 << Ident;
2265 return false;
2266 }
2267 }
2268
2269 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2270 FD && FD->isImmediateFunction()) {
2271 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2272 << !Type->isAnyPointerType();
2273 Info.Note(FD->getLocation(), diag::note_declared_at);
2274 return false;
2275 }
2276
2277 // Check that the object is a global. Note that the fake 'this' object we
2278 // manufacture when checking potential constant expressions is conservatively
2279 // assumed to be global here.
2280 if (!IsGlobalLValue(Base)) {
2281 if (Info.getLangOpts().CPlusPlus11) {
2282 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2283 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2284 << BaseVD;
2285 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2286 if (VarD && VarD->isConstexpr()) {
2287 // Non-static local constexpr variables have unintuitive semantics:
2288 // constexpr int a = 1;
2289 // constexpr const int *p = &a;
2290 // ... is invalid because the address of 'a' is not constant. Suggest
2291 // adding a 'static' in this case.
2292 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2293 << VarD
2294 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2295 } else {
2296 NoteLValueLocation(Info, Base);
2297 }
2298 } else {
2299 Info.FFDiag(Loc);
2300 }
2301 // Don't allow references to temporaries to escape.
2302 return false;
2303 }
2304 assert((Info.checkingPotentialConstantExpression() ||
2305 LVal.getLValueCallIndex() == 0) &&
2306 "have call index for global lvalue");
2307
2308 if (Base.is<DynamicAllocLValue>()) {
2309 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2310 << IsReferenceType << !Designator.Entries.empty();
2311 NoteLValueLocation(Info, Base);
2312 return false;
2313 }
2314
2315 if (BaseVD) {
2316 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2317 // Check if this is a thread-local variable.
2318 if (Var->getTLSKind())
2319 // FIXME: Diagnostic!
2320 return false;
2321
2322 // A dllimport variable never acts like a constant, unless we're
2323 // evaluating a value for use only in name mangling.
2324 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2325 // FIXME: Diagnostic!
2326 return false;
2327
2328 // In CUDA/HIP device compilation, only device side variables have
2329 // constant addresses.
2330 if (Info.getCtx().getLangOpts().CUDA &&
2331 Info.getCtx().getLangOpts().CUDAIsDevice &&
2332 Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2333 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2334 !Var->hasAttr<CUDAConstantAttr>() &&
2335 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2336 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2337 Var->hasAttr<HIPManagedAttr>())
2338 return false;
2339 }
2340 }
2341 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2342 // __declspec(dllimport) must be handled very carefully:
2343 // We must never initialize an expression with the thunk in C++.
2344 // Doing otherwise would allow the same id-expression to yield
2345 // different addresses for the same function in different translation
2346 // units. However, this means that we must dynamically initialize the
2347 // expression with the contents of the import address table at runtime.
2348 //
2349 // The C language has no notion of ODR; furthermore, it has no notion of
2350 // dynamic initialization. This means that we are permitted to
2351 // perform initialization with the address of the thunk.
2352 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2353 FD->hasAttr<DLLImportAttr>())
2354 // FIXME: Diagnostic!
2355 return false;
2356 }
2357 } else if (const auto *MTE =
2358 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2359 if (CheckedTemps.insert(MTE).second) {
2360 QualType TempType = getType(Base);
2361 if (TempType.isDestructedType()) {
2362 Info.FFDiag(MTE->getExprLoc(),
2363 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2364 << TempType;
2365 return false;
2366 }
2367
2368 APValue *V = MTE->getOrCreateValue(false);
2369 assert(V && "evasluation result refers to uninitialised temporary");
2370 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2371 Info, MTE->getExprLoc(), TempType, *V, Kind,
2372 /*SubobjectDecl=*/nullptr, CheckedTemps))
2373 return false;
2374 }
2375 }
2376
2377 // Allow address constant expressions to be past-the-end pointers. This is
2378 // an extension: the standard requires them to point to an object.
2379 if (!IsReferenceType)
2380 return true;
2381
2382 // A reference constant expression must refer to an object.
2383 if (!Base) {
2384 // FIXME: diagnostic
2385 Info.CCEDiag(Loc);
2386 return true;
2387 }
2388
2389 // Does this refer one past the end of some object?
2390 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2391 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2392 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2393 NoteLValueLocation(Info, Base);
2394 }
2395
2396 return true;
2397}
2398
2399/// Member pointers are constant expressions unless they point to a
2400/// non-virtual dllimport member function.
2401static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2403 QualType Type,
2404 const APValue &Value,
2405 ConstantExprKind Kind) {
2406 const ValueDecl *Member = Value.getMemberPointerDecl();
2407 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2408 if (!FD)
2409 return true;
2410 if (FD->isImmediateFunction()) {
2411 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2412 Info.Note(FD->getLocation(), diag::note_declared_at);
2413 return false;
2414 }
2415 return isForManglingOnly(Kind) || FD->isVirtual() ||
2416 !FD->hasAttr<DLLImportAttr>();
2417}
2418
2419/// Check that this core constant expression is of literal type, and if not,
2420/// produce an appropriate diagnostic.
2421static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2422 const LValue *This = nullptr) {
2423 // The restriction to literal types does not exist in C++23 anymore.
2424 if (Info.getLangOpts().CPlusPlus23)
2425 return true;
2426
2427 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2428 return true;
2429
2430 // C++1y: A constant initializer for an object o [...] may also invoke
2431 // constexpr constructors for o and its subobjects even if those objects
2432 // are of non-literal class types.
2433 //
2434 // C++11 missed this detail for aggregates, so classes like this:
2435 // struct foo_t { union { int i; volatile int j; } u; };
2436 // are not (obviously) initializable like so:
2437 // __attribute__((__require_constant_initialization__))
2438 // static const foo_t x = {{0}};
2439 // because "i" is a subobject with non-literal initialization (due to the
2440 // volatile member of the union). See:
2441 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2442 // Therefore, we use the C++1y behavior.
2443 if (This && Info.EvaluatingDecl == This->getLValueBase())
2444 return true;
2445
2446 // Prvalue constant expressions must be of literal types.
2447 if (Info.getLangOpts().CPlusPlus11)
2448 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2449 << E->getType();
2450 else
2451 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2452 return false;
2453}
2454
2456 EvalInfo &Info, SourceLocation DiagLoc,
2457 QualType Type, const APValue &Value,
2458 ConstantExprKind Kind,
2459 const FieldDecl *SubobjectDecl,
2460 CheckedTemporaries &CheckedTemps) {
2461 if (!Value.hasValue()) {
2462 if (SubobjectDecl) {
2463 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2464 << /*(name)*/ 1 << SubobjectDecl;
2465 Info.Note(SubobjectDecl->getLocation(),
2466 diag::note_constexpr_subobject_declared_here);
2467 } else {
2468 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2469 << /*of type*/ 0 << Type;
2470 }
2471 return false;
2472 }
2473
2474 // We allow _Atomic(T) to be initialized from anything that T can be
2475 // initialized from.
2476 if (const AtomicType *AT = Type->getAs<AtomicType>())
2477 Type = AT->getValueType();
2478
2479 // Core issue 1454: For a literal constant expression of array or class type,
2480 // each subobject of its value shall have been initialized by a constant
2481 // expression.
2482 if (Value.isArray()) {
2484 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2485 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2486 Value.getArrayInitializedElt(I), Kind,
2487 SubobjectDecl, CheckedTemps))
2488 return false;
2489 }
2490 if (!Value.hasArrayFiller())
2491 return true;
2492 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2493 Value.getArrayFiller(), Kind, SubobjectDecl,
2494 CheckedTemps);
2495 }
2496 if (Value.isUnion() && Value.getUnionField()) {
2497 return CheckEvaluationResult(
2498 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2499 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2500 }
2501 if (Value.isStruct()) {
2502 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2503 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2504 unsigned BaseIndex = 0;
2505 for (const CXXBaseSpecifier &BS : CD->bases()) {
2506 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2507 if (!BaseValue.hasValue()) {
2508 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2509 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2510 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2511 return false;
2512 }
2513 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2514 Kind, /*SubobjectDecl=*/nullptr,
2515 CheckedTemps))
2516 return false;
2517 ++BaseIndex;
2518 }
2519 }
2520 for (const auto *I : RD->fields()) {
2521 if (I->isUnnamedBitField())
2522 continue;
2523
2524 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2525 Value.getStructField(I->getFieldIndex()), Kind,
2526 I, CheckedTemps))
2527 return false;
2528 }
2529 }
2530
2531 if (Value.isLValue() &&
2532 CERK == CheckEvaluationResultKind::ConstantExpression) {
2533 LValue LVal;
2534 LVal.setFrom(Info.Ctx, Value);
2535 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2536 CheckedTemps);
2537 }
2538
2539 if (Value.isMemberPointer() &&
2540 CERK == CheckEvaluationResultKind::ConstantExpression)
2541 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2542
2543 // Everything else is fine.
2544 return true;
2545}
2546
2547/// Check that this core constant expression value is a valid value for a
2548/// constant expression. If not, report an appropriate diagnostic. Does not
2549/// check that the expression is of literal type.
2550static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2551 QualType Type, const APValue &Value,
2552 ConstantExprKind Kind) {
2553 // Nothing to check for a constant expression of type 'cv void'.
2554 if (Type->isVoidType())
2555 return true;
2556
2557 CheckedTemporaries CheckedTemps;
2558 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2559 Info, DiagLoc, Type, Value, Kind,
2560 /*SubobjectDecl=*/nullptr, CheckedTemps);
2561}
2562
2563/// Check that this evaluated value is fully-initialized and can be loaded by
2564/// an lvalue-to-rvalue conversion.
2565static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2566 QualType Type, const APValue &Value) {
2567 CheckedTemporaries CheckedTemps;
2568 return CheckEvaluationResult(
2569 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2570 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2571}
2572
2573/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2574/// "the allocated storage is deallocated within the evaluation".
2575static bool CheckMemoryLeaks(EvalInfo &Info) {
2576 if (!Info.HeapAllocs.empty()) {
2577 // We can still fold to a constant despite a compile-time memory leak,
2578 // so long as the heap allocation isn't referenced in the result (we check
2579 // that in CheckConstantExpression).
2580 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2581 diag::note_constexpr_memory_leak)
2582 << unsigned(Info.HeapAllocs.size() - 1);
2583 }
2584 return true;
2585}
2586
2587static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2588 // A null base expression indicates a null pointer. These are always
2589 // evaluatable, and they are false unless the offset is zero.
2590 if (!Value.getLValueBase()) {
2591 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2592 Result = !Value.getLValueOffset().isZero();
2593 return true;
2594 }
2595
2596 // We have a non-null base. These are generally known to be true, but if it's
2597 // a weak declaration it can be null at runtime.
2598 Result = true;
2599 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2600 return !Decl || !Decl->isWeak();
2601}
2602
2603static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2604 // TODO: This function should produce notes if it fails.
2605 switch (Val.getKind()) {
2606 case APValue::None:
2608 return false;
2609 case APValue::Int:
2610 Result = Val.getInt().getBoolValue();
2611 return true;
2613 Result = Val.getFixedPoint().getBoolValue();
2614 return true;
2615 case APValue::Float:
2616 Result = !Val.getFloat().isZero();
2617 return true;
2619 Result = Val.getComplexIntReal().getBoolValue() ||
2620 Val.getComplexIntImag().getBoolValue();
2621 return true;
2623 Result = !Val.getComplexFloatReal().isZero() ||
2624 !Val.getComplexFloatImag().isZero();
2625 return true;
2626 case APValue::LValue:
2627 return EvalPointerValueAsBool(Val, Result);
2629 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2630 return false;
2631 }
2632 Result = Val.getMemberPointerDecl();
2633 return true;
2634 case APValue::Vector:
2635 case APValue::Array:
2636 case APValue::Struct:
2637 case APValue::Union:
2639 return false;
2640 }
2641
2642 llvm_unreachable("unknown APValue kind");
2643}
2644
2645static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2646 EvalInfo &Info) {
2647 assert(!E->isValueDependent());
2648 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2649 APValue Val;
2650 if (!Evaluate(Val, Info, E))
2651 return false;
2652 return HandleConversionToBool(Val, Result);
2653}
2654
2655template<typename T>
2656static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2657 const T &SrcValue, QualType DestType) {
2658 Info.CCEDiag(E, diag::note_constexpr_overflow)
2659 << SrcValue << DestType;
2660 return Info.noteUndefinedBehavior();
2661}
2662
2663static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2664 QualType SrcType, const APFloat &Value,
2665 QualType DestType, APSInt &Result) {
2666 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2667 // Determine whether we are converting to unsigned or signed.
2668 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2669
2670 Result = APSInt(DestWidth, !DestSigned);
2671 bool ignored;
2672 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2673 & APFloat::opInvalidOp)
2674 return HandleOverflow(Info, E, Value, DestType);
2675 return true;
2676}
2677
2678/// Get rounding mode to use in evaluation of the specified expression.
2679///
2680/// If rounding mode is unknown at compile time, still try to evaluate the
2681/// expression. If the result is exact, it does not depend on rounding mode.
2682/// So return "tonearest" mode instead of "dynamic".
2683static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2684 llvm::RoundingMode RM =
2685 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2686 if (RM == llvm::RoundingMode::Dynamic)
2687 RM = llvm::RoundingMode::NearestTiesToEven;
2688 return RM;
2689}
2690
2691/// Check if the given evaluation result is allowed for constant evaluation.
2692static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2693 APFloat::opStatus St) {
2694 // In a constant context, assume that any dynamic rounding mode or FP
2695 // exception state matches the default floating-point environment.
2696 if (Info.InConstantContext)
2697 return true;
2698
2699 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2700 if ((St & APFloat::opInexact) &&
2701 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2702 // Inexact result means that it depends on rounding mode. If the requested
2703 // mode is dynamic, the evaluation cannot be made in compile time.
2704 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2705 return false;
2706 }
2707
2708 if ((St != APFloat::opOK) &&
2709 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2710 FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2711 FPO.getAllowFEnvAccess())) {
2712 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2713 return false;
2714 }
2715
2716 if ((St & APFloat::opStatus::opInvalidOp) &&
2717 FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2718 // There is no usefully definable result.
2719 Info.FFDiag(E);
2720 return false;
2721 }
2722
2723 // FIXME: if:
2724 // - evaluation triggered other FP exception, and
2725 // - exception mode is not "ignore", and
2726 // - the expression being evaluated is not a part of global variable
2727 // initializer,
2728 // the evaluation probably need to be rejected.
2729 return true;
2730}
2731
2732static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2733 QualType SrcType, QualType DestType,
2734 APFloat &Result) {
2735 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2736 isa<ConvertVectorExpr>(E)) &&
2737 "HandleFloatToFloatCast has been checked with only CastExpr, "
2738 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2739 "the new expression or address the root cause of this usage.");
2740 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2741 APFloat::opStatus St;
2742 APFloat Value = Result;
2743 bool ignored;
2744 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2745 return checkFloatingPointResult(Info, E, St);
2746}
2747
2748static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2749 QualType DestType, QualType SrcType,
2750 const APSInt &Value) {
2751 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2752 // Figure out if this is a truncate, extend or noop cast.
2753 // If the input is signed, do a sign extend, noop, or truncate.
2754 APSInt Result = Value.extOrTrunc(DestWidth);
2755 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2756 if (DestType->isBooleanType())
2757 Result = Value.getBoolValue();
2758 return Result;
2759}
2760
2761static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2762 const FPOptions FPO,
2763 QualType SrcType, const APSInt &Value,
2764 QualType DestType, APFloat &Result) {
2765 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2766 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2767 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2768 return checkFloatingPointResult(Info, E, St);
2769}
2770
2771static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2772 APValue &Value, const FieldDecl *FD) {
2773 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2774
2775 if (!Value.isInt()) {
2776 // Trying to store a pointer-cast-to-integer into a bitfield.
2777 // FIXME: In this case, we should provide the diagnostic for casting
2778 // a pointer to an integer.
2779 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2780 Info.FFDiag(E);
2781 return false;
2782 }
2783
2784 APSInt &Int = Value.getInt();
2785 unsigned OldBitWidth = Int.getBitWidth();
2786 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2787 if (NewBitWidth < OldBitWidth)
2788 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2789 return true;
2790}
2791
2792/// Perform the given integer operation, which is known to need at most BitWidth
2793/// bits, and check for overflow in the original type (if that type was not an
2794/// unsigned type).
2795template<typename Operation>
2796static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2797 const APSInt &LHS, const APSInt &RHS,
2798 unsigned BitWidth, Operation Op,
2799 APSInt &Result) {
2800 if (LHS.isUnsigned()) {
2801 Result = Op(LHS, RHS);
2802 return true;
2803 }
2804
2805 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2806 Result = Value.trunc(LHS.getBitWidth());
2807 if (Result.extend(BitWidth) != Value) {
2808 if (Info.checkingForUndefinedBehavior())
2809 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2810 diag::warn_integer_constant_overflow)
2811 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2812 /*UpperCase=*/true, /*InsertSeparators=*/true)
2813 << E->getType() << E->getSourceRange();
2814 return HandleOverflow(Info, E, Value, E->getType());
2815 }
2816 return true;
2817}
2818
2819/// Perform the given binary integer operation.
2820static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2821 const APSInt &LHS, BinaryOperatorKind Opcode,
2822 APSInt RHS, APSInt &Result) {
2823 bool HandleOverflowResult = true;
2824 switch (Opcode) {
2825 default:
2826 Info.FFDiag(E);
2827 return false;
2828 case BO_Mul:
2829 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2830 std::multiplies<APSInt>(), Result);
2831 case BO_Add:
2832 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2833 std::plus<APSInt>(), Result);
2834 case BO_Sub:
2835 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2836 std::minus<APSInt>(), Result);
2837 case BO_And: Result = LHS & RHS; return true;
2838 case BO_Xor: Result = LHS ^ RHS; return true;
2839 case BO_Or: Result = LHS | RHS; return true;
2840 case BO_Div:
2841 case BO_Rem:
2842 if (RHS == 0) {
2843 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2844 << E->getRHS()->getSourceRange();
2845 return false;
2846 }
2847 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2848 // this operation and gives the two's complement result.
2849 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2850 LHS.isMinSignedValue())
2851 HandleOverflowResult = HandleOverflow(
2852 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2853 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2854 return HandleOverflowResult;
2855 case BO_Shl: {
2856 if (Info.getLangOpts().OpenCL)
2857 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2858 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2859 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2860 RHS.isUnsigned());
2861 else if (RHS.isSigned() && RHS.isNegative()) {
2862 // During constant-folding, a negative shift is an opposite shift. Such
2863 // a shift is not a constant expression.
2864 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2865 if (!Info.noteUndefinedBehavior())
2866 return false;
2867 RHS = -RHS;
2868 goto shift_right;
2869 }
2870 shift_left:
2871 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2872 // the shifted type.
2873 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2874 if (SA != RHS) {
2875 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2876 << RHS << E->getType() << LHS.getBitWidth();
2877 if (!Info.noteUndefinedBehavior())
2878 return false;
2879 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2880 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2881 // operand, and must not overflow the corresponding unsigned type.
2882 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2883 // E1 x 2^E2 module 2^N.
2884 if (LHS.isNegative()) {
2885 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2886 if (!Info.noteUndefinedBehavior())
2887 return false;
2888 } else if (LHS.countl_zero() < SA) {
2889 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2890 if (!Info.noteUndefinedBehavior())
2891 return false;
2892 }
2893 }
2894 Result = LHS << SA;
2895 return true;
2896 }
2897 case BO_Shr: {
2898 if (Info.getLangOpts().OpenCL)
2899 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2900 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2901 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2902 RHS.isUnsigned());
2903 else if (RHS.isSigned() && RHS.isNegative()) {
2904 // During constant-folding, a negative shift is an opposite shift. Such a
2905 // shift is not a constant expression.
2906 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2907 if (!Info.noteUndefinedBehavior())
2908 return false;
2909 RHS = -RHS;
2910 goto shift_left;
2911 }
2912 shift_right:
2913 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2914 // shifted type.
2915 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2916 if (SA != RHS) {
2917 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2918 << RHS << E->getType() << LHS.getBitWidth();
2919 if (!Info.noteUndefinedBehavior())
2920 return false;
2921 }
2922
2923 Result = LHS >> SA;
2924 return true;
2925 }
2926
2927 case BO_LT: Result = LHS < RHS; return true;
2928 case BO_GT: Result = LHS > RHS; return true;
2929 case BO_LE: Result = LHS <= RHS; return true;
2930 case BO_GE: Result = LHS >= RHS; return true;
2931 case BO_EQ: Result = LHS == RHS; return true;
2932 case BO_NE: Result = LHS != RHS; return true;
2933 case BO_Cmp:
2934 llvm_unreachable("BO_Cmp should be handled elsewhere");
2935 }
2936}
2937
2938/// Perform the given binary floating-point operation, in-place, on LHS.
2939static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2940 APFloat &LHS, BinaryOperatorKind Opcode,
2941 const APFloat &RHS) {
2942 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2943 APFloat::opStatus St;
2944 switch (Opcode) {
2945 default:
2946 Info.FFDiag(E);
2947 return false;
2948 case BO_Mul:
2949 St = LHS.multiply(RHS, RM);
2950 break;
2951 case BO_Add:
2952 St = LHS.add(RHS, RM);
2953 break;
2954 case BO_Sub:
2955 St = LHS.subtract(RHS, RM);
2956 break;
2957 case BO_Div:
2958 // [expr.mul]p4:
2959 // If the second operand of / or % is zero the behavior is undefined.
2960 if (RHS.isZero())
2961 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2962 St = LHS.divide(RHS, RM);
2963 break;
2964 }
2965
2966 // [expr.pre]p4:
2967 // If during the evaluation of an expression, the result is not
2968 // mathematically defined [...], the behavior is undefined.
2969 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2970 if (LHS.isNaN()) {
2971 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2972 return Info.noteUndefinedBehavior();
2973 }
2974
2975 return checkFloatingPointResult(Info, E, St);
2976}
2977
2978static bool handleLogicalOpForVector(const APInt &LHSValue,
2979 BinaryOperatorKind Opcode,
2980 const APInt &RHSValue, APInt &Result) {
2981 bool LHS = (LHSValue != 0);
2982 bool RHS = (RHSValue != 0);
2983
2984 if (Opcode == BO_LAnd)
2985 Result = LHS && RHS;
2986 else
2987 Result = LHS || RHS;
2988 return true;
2989}
2990static bool handleLogicalOpForVector(const APFloat &LHSValue,
2991 BinaryOperatorKind Opcode,
2992 const APFloat &RHSValue, APInt &Result) {
2993 bool LHS = !LHSValue.isZero();
2994 bool RHS = !RHSValue.isZero();
2995
2996 if (Opcode == BO_LAnd)
2997 Result = LHS && RHS;
2998 else
2999 Result = LHS || RHS;
3000 return true;
3001}
3002
3003static bool handleLogicalOpForVector(const APValue &LHSValue,
3004 BinaryOperatorKind Opcode,
3005 const APValue &RHSValue, APInt &Result) {
3006 // The result is always an int type, however operands match the first.
3007 if (LHSValue.getKind() == APValue::Int)
3008 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3009 RHSValue.getInt(), Result);
3010 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3011 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3012 RHSValue.getFloat(), Result);
3013}
3014
3015template <typename APTy>
3016static bool
3018 const APTy &RHSValue, APInt &Result) {
3019 switch (Opcode) {
3020 default:
3021 llvm_unreachable("unsupported binary operator");
3022 case BO_EQ:
3023 Result = (LHSValue == RHSValue);
3024 break;
3025 case BO_NE:
3026 Result = (LHSValue != RHSValue);
3027 break;
3028 case BO_LT:
3029 Result = (LHSValue < RHSValue);
3030 break;
3031 case BO_GT:
3032 Result = (LHSValue > RHSValue);
3033 break;
3034 case BO_LE:
3035 Result = (LHSValue <= RHSValue);
3036 break;
3037 case BO_GE:
3038 Result = (LHSValue >= RHSValue);
3039 break;
3040 }
3041
3042 // The boolean operations on these vector types use an instruction that
3043 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3044 // to -1 to make sure that we produce the correct value.
3045 Result.negate();
3046
3047 return true;
3048}
3049
3050static bool handleCompareOpForVector(const APValue &LHSValue,
3051 BinaryOperatorKind Opcode,
3052 const APValue &RHSValue, APInt &Result) {
3053 // The result is always an int type, however operands match the first.
3054 if (LHSValue.getKind() == APValue::Int)
3055 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3056 RHSValue.getInt(), Result);
3057 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3058 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3059 RHSValue.getFloat(), Result);
3060}
3061
3062// Perform binary operations for vector types, in place on the LHS.
3063static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3064 BinaryOperatorKind Opcode,
3065 APValue &LHSValue,
3066 const APValue &RHSValue) {
3067 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3068 "Operation not supported on vector types");
3069
3070 const auto *VT = E->getType()->castAs<VectorType>();
3071 unsigned NumElements = VT->getNumElements();
3072 QualType EltTy = VT->getElementType();
3073
3074 // In the cases (typically C as I've observed) where we aren't evaluating
3075 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3076 // just give up.
3077 if (!LHSValue.isVector()) {
3078 assert(LHSValue.isLValue() &&
3079 "A vector result that isn't a vector OR uncalculated LValue");
3080 Info.FFDiag(E);
3081 return false;
3082 }
3083
3084 assert(LHSValue.getVectorLength() == NumElements &&
3085 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3086
3087 SmallVector<APValue, 4> ResultElements;
3088
3089 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3090 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3091 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3092
3093 if (EltTy->isIntegerType()) {
3094 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3095 EltTy->isUnsignedIntegerType()};
3096 bool Success = true;
3097
3098 if (BinaryOperator::isLogicalOp(Opcode))
3099 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3100 else if (BinaryOperator::isComparisonOp(Opcode))
3101 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3102 else
3103 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3104 RHSElt.getInt(), EltResult);
3105
3106 if (!Success) {
3107 Info.FFDiag(E);
3108 return false;
3109 }
3110 ResultElements.emplace_back(EltResult);
3111
3112 } else if (EltTy->isFloatingType()) {
3113 assert(LHSElt.getKind() == APValue::Float &&
3114 RHSElt.getKind() == APValue::Float &&
3115 "Mismatched LHS/RHS/Result Type");
3116 APFloat LHSFloat = LHSElt.getFloat();
3117
3118 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3119 RHSElt.getFloat())) {
3120 Info.FFDiag(E);
3121 return false;
3122 }
3123
3124 ResultElements.emplace_back(LHSFloat);
3125 }
3126 }
3127
3128 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3129 return true;
3130}
3131
3132/// Cast an lvalue referring to a base subobject to a derived class, by
3133/// truncating the lvalue's path to the given length.
3134static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3135 const RecordDecl *TruncatedType,
3136 unsigned TruncatedElements) {
3137 SubobjectDesignator &D = Result.Designator;
3138
3139 // Check we actually point to a derived class object.
3140 if (TruncatedElements == D.Entries.size())
3141 return true;
3142 assert(TruncatedElements >= D.MostDerivedPathLength &&
3143 "not casting to a derived class");
3144 if (!Result.checkSubobject(Info, E, CSK_Derived))
3145 return false;
3146
3147 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3148 const RecordDecl *RD = TruncatedType;
3149 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3150 if (RD->isInvalidDecl()) return false;
3151 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3152 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3153 if (isVirtualBaseClass(D.Entries[I]))
3154 Result.Offset -= Layout.getVBaseClassOffset(Base);
3155 else
3156 Result.Offset -= Layout.getBaseClassOffset(Base);
3157 RD = Base;
3158 }
3159 D.Entries.resize(TruncatedElements);
3160 return true;
3161}
3162
3163static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3164 const CXXRecordDecl *Derived,
3165 const CXXRecordDecl *Base,
3166 const ASTRecordLayout *RL = nullptr) {
3167 if (!RL) {
3168 if (Derived->isInvalidDecl()) return false;
3169 RL = &Info.Ctx.getASTRecordLayout(Derived);
3170 }
3171
3172 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3173 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3174 return true;
3175}
3176
3177static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3178 const CXXRecordDecl *DerivedDecl,
3179 const CXXBaseSpecifier *Base) {
3180 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3181
3182 if (!Base->isVirtual())
3183 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3184
3185 SubobjectDesignator &D = Obj.Designator;
3186 if (D.Invalid)
3187 return false;
3188
3189 // Extract most-derived object and corresponding type.
3190 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3191 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3192 return false;
3193
3194 // Find the virtual base class.
3195 if (DerivedDecl->isInvalidDecl()) return false;
3196 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3197 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3198 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3199 return true;
3200}
3201
3202static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3203 QualType Type, LValue &Result) {
3204 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3205 PathE = E->path_end();
3206 PathI != PathE; ++PathI) {
3207 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3208 *PathI))
3209 return false;
3210 Type = (*PathI)->getType();
3211 }
3212 return true;
3213}
3214
3215/// Cast an lvalue referring to a derived class to a known base subobject.
3216static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3217 const CXXRecordDecl *DerivedRD,
3218 const CXXRecordDecl *BaseRD) {
3219 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3220 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3221 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3222 llvm_unreachable("Class must be derived from the passed in base class!");
3223
3224 for (CXXBasePathElement &Elem : Paths.front())
3225 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3226 return false;
3227 return true;
3228}
3229
3230/// Update LVal to refer to the given field, which must be a member of the type
3231/// currently described by LVal.
3232static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3233 const FieldDecl *FD,
3234 const ASTRecordLayout *RL = nullptr) {
3235 if (!RL) {
3236 if (FD->getParent()->isInvalidDecl()) return false;
3237 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3238 }
3239
3240 unsigned I = FD->getFieldIndex();
3241 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3242 LVal.addDecl(Info, E, FD);
3243 return true;
3244}
3245
3246/// Update LVal to refer to the given indirect field.
3247static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3248 LValue &LVal,
3249 const IndirectFieldDecl *IFD) {
3250 for (const auto *C : IFD->chain())
3251 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3252 return false;
3253 return true;
3254}
3255
3256enum class SizeOfType {
3257 SizeOf,
3258 DataSizeOf,
3259};
3260
3261/// Get the size of the given type in char units.
3262static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3263 CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) {
3264 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3265 // extension.
3266 if (Type->isVoidType() || Type->isFunctionType()) {
3267 Size = CharUnits::One();
3268 return true;
3269 }
3270
3271 if (Type->isDependentType()) {
3272 Info.FFDiag(Loc);
3273 return false;
3274 }
3275
3276 if (!Type->isConstantSizeType()) {
3277 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3278 // FIXME: Better diagnostic.
3279 Info.FFDiag(Loc);
3280 return false;
3281 }
3282
3283 if (SOT == SizeOfType::SizeOf)
3284 Size = Info.Ctx.getTypeSizeInChars(Type);
3285 else
3286 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3287 return true;
3288}
3289
3290/// Update a pointer value to model pointer arithmetic.
3291/// \param Info - Information about the ongoing evaluation.
3292/// \param E - The expression being evaluated, for diagnostic purposes.
3293/// \param LVal - The pointer value to be updated.
3294/// \param EltTy - The pointee type represented by LVal.
3295/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3296static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3297 LValue &LVal, QualType EltTy,
3298 APSInt Adjustment) {
3299 CharUnits SizeOfPointee;
3300 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3301 return false;
3302
3303 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3304 return true;
3305}
3306
3307static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3308 LValue &LVal, QualType EltTy,
3309 int64_t Adjustment) {
3310 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3311 APSInt::get(Adjustment));
3312}
3313
3314/// Update an lvalue to refer to a component of a complex number.
3315/// \param Info - Information about the ongoing evaluation.
3316/// \param LVal - The lvalue to be updated.
3317/// \param EltTy - The complex number's component type.
3318/// \param Imag - False for the real component, true for the imaginary.
3319static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3320 LValue &LVal, QualType EltTy,
3321 bool Imag) {
3322 if (Imag) {
3323 CharUnits SizeOfComponent;
3324 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3325 return false;
3326 LVal.Offset += SizeOfComponent;
3327 }
3328 LVal.addComplex(Info, E, EltTy, Imag);
3329 return true;
3330}
3331
3332static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3333 LValue &LVal, QualType EltTy,
3334 uint64_t Size, uint64_t Idx) {
3335 if (Idx) {
3336 CharUnits SizeOfElement;
3337 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3338 return false;
3339 LVal.Offset += SizeOfElement * Idx;
3340 }
3341 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3342 return true;
3343}
3344
3345/// Try to evaluate the initializer for a variable declaration.
3346///
3347/// \param Info Information about the ongoing evaluation.
3348/// \param E An expression to be used when printing diagnostics.
3349/// \param VD The variable whose initializer should be obtained.
3350/// \param Version The version of the variable within the frame.
3351/// \param Frame The frame in which the variable was created. Must be null
3352/// if this variable is not local to the evaluation.
3353/// \param Result Filled in with a pointer to the value of the variable.
3354static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3355 const VarDecl *VD, CallStackFrame *Frame,
3356 unsigned Version, APValue *&Result) {
3357 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3358
3359 // If this is a local variable, dig out its value.
3360 if (Frame) {
3361 Result = Frame->getTemporary(VD, Version);
3362 if (Result)
3363 return true;
3364
3365 if (!isa<ParmVarDecl>(VD)) {
3366 // Assume variables referenced within a lambda's call operator that were
3367 // not declared within the call operator are captures and during checking
3368 // of a potential constant expression, assume they are unknown constant
3369 // expressions.
3370 assert(isLambdaCallOperator(Frame->Callee) &&
3371 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3372 "missing value for local variable");
3373 if (Info.checkingPotentialConstantExpression())
3374 return false;
3375 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3376 // still reachable at all?
3377 Info.FFDiag(E->getBeginLoc(),
3378 diag::note_unimplemented_constexpr_lambda_feature_ast)
3379 << "captures not currently allowed";
3380 return false;
3381 }
3382 }
3383
3384 // If we're currently evaluating the initializer of this declaration, use that
3385 // in-flight value.
3386 if (Info.EvaluatingDecl == Base) {
3387 Result = Info.EvaluatingDeclValue;
3388 return true;
3389 }
3390
3391 if (isa<ParmVarDecl>(VD)) {
3392 // Assume parameters of a potential constant expression are usable in
3393 // constant expressions.
3394 if (!Info.checkingPotentialConstantExpression() ||
3395 !Info.CurrentCall->Callee ||
3396 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3397 if (Info.getLangOpts().CPlusPlus11) {
3398 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3399 << VD;
3400 NoteLValueLocation(Info, Base);
3401 } else {
3402 Info.FFDiag(E);
3403 }
3404 }
3405 return false;
3406 }
3407
3408 if (E->isValueDependent())
3409 return false;
3410
3411 // Dig out the initializer, and use the declaration which it's attached to.
3412 // FIXME: We should eventually check whether the variable has a reachable
3413 // initializing declaration.
3414 const Expr *Init = VD->getAnyInitializer(VD);
3415 if (!Init) {
3416 // Don't diagnose during potential constant expression checking; an
3417 // initializer might be added later.
3418 if (!Info.checkingPotentialConstantExpression()) {
3419 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3420 << VD;
3421 NoteLValueLocation(Info, Base);
3422 }
3423 return false;
3424 }
3425
3426 if (Init->isValueDependent()) {
3427 // The DeclRefExpr is not value-dependent, but the variable it refers to
3428 // has a value-dependent initializer. This should only happen in
3429 // constant-folding cases, where the variable is not actually of a suitable
3430 // type for use in a constant expression (otherwise the DeclRefExpr would
3431 // have been value-dependent too), so diagnose that.
3432 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3433 if (!Info.checkingPotentialConstantExpression()) {
3434 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3435 ? diag::note_constexpr_ltor_non_constexpr
3436 : diag::note_constexpr_ltor_non_integral, 1)
3437 << VD << VD->getType();
3438 NoteLValueLocation(Info, Base);
3439 }
3440 return false;
3441 }
3442
3443 // Check that we can fold the initializer. In C++, we will have already done
3444 // this in the cases where it matters for conformance.
3445 if (!VD->evaluateValue()) {
3446 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3447 NoteLValueLocation(Info, Base);
3448 return false;
3449 }
3450
3451 // Check that the variable is actually usable in constant expressions. For a
3452 // const integral variable or a reference, we might have a non-constant
3453 // initializer that we can nonetheless evaluate the initializer for. Such
3454 // variables are not usable in constant expressions. In C++98, the
3455 // initializer also syntactically needs to be an ICE.
3456 //
3457 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3458 // expressions here; doing so would regress diagnostics for things like
3459 // reading from a volatile constexpr variable.
3460 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3461 VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3462 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3463 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3464 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3465 NoteLValueLocation(Info, Base);
3466 }
3467
3468 // Never use the initializer of a weak variable, not even for constant
3469 // folding. We can't be sure that this is the definition that will be used.
3470 if (VD->isWeak()) {
3471 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3472 NoteLValueLocation(Info, Base);
3473 return false;
3474 }
3475
3476 Result = VD->getEvaluatedValue();
3477 return true;
3478}
3479
3480/// Get the base index of the given base class within an APValue representing
3481/// the given derived class.
3482static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3483 const CXXRecordDecl *Base) {
3484 Base = Base->getCanonicalDecl();
3485 unsigned Index = 0;
3487 E = Derived->bases_end(); I != E; ++I, ++Index) {
3488 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3489 return Index;
3490 }
3491
3492 llvm_unreachable("base class missing from derived class's bases list");
3493}
3494
3495/// Extract the value of a character from a string literal.
3496static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3497 uint64_t Index) {
3498 assert(!isa<SourceLocExpr>(Lit) &&
3499 "SourceLocExpr should have already been converted to a StringLiteral");
3500
3501 // FIXME: Support MakeStringConstant
3502 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3503 std::string Str;
3504 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3505 assert(Index <= Str.size() && "Index too large");
3506 return APSInt::getUnsigned(Str.c_str()[Index]);
3507 }
3508
3509 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3510 Lit = PE->getFunctionName();
3511 const StringLiteral *S = cast<StringLiteral>(Lit);
3512 const ConstantArrayType *CAT =
3513 Info.Ctx.getAsConstantArrayType(S->getType());
3514 assert(CAT && "string literal isn't an array");
3515 QualType CharType = CAT->getElementType();
3516 assert(CharType->isIntegerType() && "unexpected character type");
3517 APSInt Value(Info.Ctx.getTypeSize(CharType),
3518 CharType->isUnsignedIntegerType());
3519 if (Index < S->getLength())
3520 Value = S->getCodeUnit(Index);
3521 return Value;
3522}
3523
3524// Expand a string literal into an array of characters.
3525//
3526// FIXME: This is inefficient; we should probably introduce something similar
3527// to the LLVM ConstantDataArray to make this cheaper.
3528static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3529 APValue &Result,
3530 QualType AllocType = QualType()) {
3531 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3532 AllocType.isNull() ? S->getType() : AllocType);
3533 assert(CAT && "string literal isn't an array");
3534 QualType CharType = CAT->getElementType();
3535 assert(CharType->isIntegerType() && "unexpected character type");
3536
3537 unsigned Elts = CAT->getZExtSize();
3538 Result = APValue(APValue::UninitArray(),
3539 std::min(S->getLength(), Elts), Elts);
3540 APSInt Value(Info.Ctx.getTypeSize(CharType),
3541 CharType->isUnsignedIntegerType());
3542 if (Result.hasArrayFiller())
3543 Result.getArrayFiller() = APValue(Value);
3544 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3545 Value = S->getCodeUnit(I);
3546 Result.getArrayInitializedElt(I) = APValue(Value);
3547 }
3548}
3549
3550// Expand an array so that it has more than Index filled elements.
3551static void expandArray(APValue &Array, unsigned Index) {
3552 unsigned Size = Array.getArraySize();
3553 assert(Index < Size);
3554
3555 // Always at least double the number of elements for which we store a value.
3556 unsigned OldElts = Array.getArrayInitializedElts();
3557 unsigned NewElts = std::max(Index+1, OldElts * 2);
3558 NewElts = std::min(Size, std::max(NewElts, 8u));
3559
3560 // Copy the data across.
3561 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3562 for (unsigned I = 0; I != OldElts; ++I)
3563 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3564 for (unsigned I = OldElts; I != NewElts; ++I)
3565 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3566 if (NewValue.hasArrayFiller())
3567 NewValue.getArrayFiller() = Array.getArrayFiller();
3568 Array.swap(NewValue);
3569}
3570
3571/// Determine whether a type would actually be read by an lvalue-to-rvalue
3572/// conversion. If it's of class type, we may assume that the copy operation
3573/// is trivial. Note that this is never true for a union type with fields
3574/// (because the copy always "reads" the active member) and always true for
3575/// a non-class type.
3576static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3579 return !RD || isReadByLvalueToRvalueConversion(RD);
3580}
3582 // FIXME: A trivial copy of a union copies the object representation, even if
3583 // the union is empty.
3584 if (RD->isUnion())
3585 return !RD->field_empty();
3586 if (RD->isEmpty())
3587 return false;
3588
3589 for (auto *Field : RD->fields())
3590 if (!Field->isUnnamedBitField() &&
3591 isReadByLvalueToRvalueConversion(Field->getType()))
3592 return true;
3593
3594 for (auto &BaseSpec : RD->bases())
3595 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3596 return true;
3597
3598 return false;
3599}
3600
3601/// Diagnose an attempt to read from any unreadable field within the specified
3602/// type, which might be a class type.
3603static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3604 QualType T) {
3606 if (!RD)
3607 return false;
3608
3609 if (!RD->hasMutableFields())
3610 return false;
3611
3612 for (auto *Field : RD->fields()) {
3613 // If we're actually going to read this field in some way, then it can't
3614 // be mutable. If we're in a union, then assigning to a mutable field
3615 // (even an empty one) can change the active member, so that's not OK.
3616 // FIXME: Add core issue number for the union case.
3617 if (Field->isMutable() &&
3618 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3619 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3620 Info.Note(Field->getLocation(), diag::note_declared_at);
3621 return true;
3622 }
3623
3624 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3625 return true;
3626 }
3627
3628 for (auto &BaseSpec : RD->bases())
3629 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3630 return true;
3631
3632 // All mutable fields were empty, and thus not actually read.
3633 return false;
3634}
3635
3636static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3638 bool MutableSubobject = false) {
3639 // A temporary or transient heap allocation we created.
3640 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3641 return true;
3642
3643 switch (Info.IsEvaluatingDecl) {
3644 case EvalInfo::EvaluatingDeclKind::None:
3645 return false;
3646
3647 case EvalInfo::EvaluatingDeclKind::Ctor:
3648 // The variable whose initializer we're evaluating.
3649 if (Info.EvaluatingDecl == Base)
3650 return true;
3651
3652 // A temporary lifetime-extended by the variable whose initializer we're
3653 // evaluating.
3654 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3655 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3656 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3657 return false;
3658
3659 case EvalInfo::EvaluatingDeclKind::Dtor:
3660 // C++2a [expr.const]p6:
3661 // [during constant destruction] the lifetime of a and its non-mutable
3662 // subobjects (but not its mutable subobjects) [are] considered to start
3663 // within e.
3664 if (MutableSubobject || Base != Info.EvaluatingDecl)
3665 return false;
3666 // FIXME: We can meaningfully extend this to cover non-const objects, but
3667 // we will need special handling: we should be able to access only
3668 // subobjects of such objects that are themselves declared const.
3669 QualType T = getType(Base);
3670 return T.isConstQualified() || T->isReferenceType();
3671 }
3672
3673 llvm_unreachable("unknown evaluating decl kind");
3674}
3675
3676static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3677 SourceLocation CallLoc = {}) {
3678 return Info.CheckArraySize(
3679 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3680 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3681 /*Diag=*/true);
3682}
3683
3684namespace {
3685/// A handle to a complete object (an object that is not a subobject of
3686/// another object).
3687struct CompleteObject {
3688 /// The identity of the object.
3690 /// The value of the complete object.
3691 APValue *Value;
3692 /// The type of the complete object.
3693 QualType Type;
3694
3695 CompleteObject() : Value(nullptr) {}
3697 : Base(Base), Value(Value), Type(Type) {}
3698
3699 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3700 // If this isn't a "real" access (eg, if it's just accessing the type
3701 // info), allow it. We assume the type doesn't change dynamically for
3702 // subobjects of constexpr objects (even though we'd hit UB here if it
3703 // did). FIXME: Is this right?
3704 if (!isAnyAccess(AK))
3705 return true;
3706
3707 // In C++14 onwards, it is permitted to read a mutable member whose
3708 // lifetime began within the evaluation.
3709 // FIXME: Should we also allow this in C++11?
3710 if (!Info.getLangOpts().CPlusPlus14)
3711 return false;
3712 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3713 }
3714
3715 explicit operator bool() const { return !Type.isNull(); }
3716};
3717} // end anonymous namespace
3718
3719static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3720 bool IsMutable = false) {
3721 // C++ [basic.type.qualifier]p1:
3722 // - A const object is an object of type const T or a non-mutable subobject
3723 // of a const object.
3724 if (ObjType.isConstQualified() && !IsMutable)
3725 SubobjType.addConst();
3726 // - A volatile object is an object of type const T or a subobject of a
3727 // volatile object.
3728 if (ObjType.isVolatileQualified())
3729 SubobjType.addVolatile();
3730 return SubobjType;
3731}
3732
3733/// Find the designated sub-object of an rvalue.
3734template<typename SubobjectHandler>
3735typename SubobjectHandler::result_type
3736findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3737 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3738 if (Sub.Invalid)
3739 // A diagnostic will have already been produced.
3740 return handler.failed();
3741 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3742 if (Info.getLangOpts().CPlusPlus11)
3743 Info.FFDiag(E, Sub.isOnePastTheEnd()
3744 ? diag::note_constexpr_access_past_end
3745 : diag::note_constexpr_access_unsized_array)
3746 << handler.AccessKind;
3747 else
3748 Info.FFDiag(E);
3749 return handler.failed();
3750 }
3751
3752 APValue *O = Obj.Value;
3753 QualType ObjType = Obj.Type;
3754 const FieldDecl *LastField = nullptr;
3755 const FieldDecl *VolatileField = nullptr;
3756
3757 // Walk the designator's path to find the subobject.
3758 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3759 // Reading an indeterminate value is undefined, but assigning over one is OK.
3760 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3761 (O->isIndeterminate() &&
3762 !isValidIndeterminateAccess(handler.AccessKind))) {
3763 if (!Info.checkingPotentialConstantExpression())
3764 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3765 << handler.AccessKind << O->isIndeterminate()
3766 << E->getSourceRange();
3767 return handler.failed();
3768 }
3769
3770 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3771 // const and volatile semantics are not applied on an object under
3772 // {con,de}struction.
3773 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3774 ObjType->isRecordType() &&
3775 Info.isEvaluatingCtorDtor(
3776 Obj.Base,
3777 llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3778 ConstructionPhase::None) {
3779 ObjType = Info.Ctx.getCanonicalType(ObjType);
3780 ObjType.removeLocalConst();
3781 ObjType.removeLocalVolatile();
3782 }
3783
3784 // If this is our last pass, check that the final object type is OK.
3785 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3786 // Accesses to volatile objects are prohibited.
3787 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3788 if (Info.getLangOpts().CPlusPlus) {
3789 int DiagKind;
3791 const NamedDecl *Decl = nullptr;
3792 if (VolatileField) {
3793 DiagKind = 2;
3794 Loc = VolatileField->getLocation();
3795 Decl = VolatileField;
3796 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3797 DiagKind = 1;
3798 Loc = VD->getLocation();
3799 Decl = VD;
3800 } else {
3801 DiagKind = 0;
3802 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3803 Loc = E->getExprLoc();
3804 }
3805 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3806 << handler.AccessKind << DiagKind << Decl;
3807 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3808 } else {
3809 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3810 }
3811 return handler.failed();
3812 }
3813
3814 // If we are reading an object of class type, there may still be more
3815 // things we need to check: if there are any mutable subobjects, we
3816 // cannot perform this read. (This only happens when performing a trivial
3817 // copy or assignment.)
3818 if (ObjType->isRecordType() &&
3819 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3820 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3821 return handler.failed();
3822 }
3823
3824 if (I == N) {
3825 if (!handler.found(*O, ObjType))
3826 return false;
3827
3828 // If we modified a bit-field, truncate it to the right width.
3829 if (isModification(handler.AccessKind) &&
3830 LastField && LastField->isBitField() &&
3831 !truncateBitfieldValue(Info, E, *O, LastField))
3832 return false;
3833
3834 return true;
3835 }
3836
3837 LastField = nullptr;
3838 if (ObjType->isArrayType()) {
3839 // Next subobject is an array element.
3840 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3841 assert(CAT && "vla in literal type?");
3842 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3843 if (CAT->getSize().ule(Index)) {
3844 // Note, it should not be possible to form a pointer with a valid
3845 // designator which points more than one past the end of the array.
3846 if (Info.getLangOpts().CPlusPlus11)
3847 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3848 << handler.AccessKind;
3849 else
3850 Info.FFDiag(E);
3851 return handler.failed();
3852 }
3853
3854 ObjType = CAT->getElementType();
3855
3856 if (O->getArrayInitializedElts() > Index)
3857 O = &O->getArrayInitializedElt(Index);
3858 else if (!isRead(handler.AccessKind)) {
3859 if (!CheckArraySize(Info, CAT, E->getExprLoc()))
3860 return handler.failed();
3861
3862 expandArray(*O, Index);
3863 O = &O->getArrayInitializedElt(Index);
3864 } else
3865 O = &O->getArrayFiller();
3866 } else if (ObjType->isAnyComplexType()) {
3867 // Next subobject is a complex number.
3868 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3869 if (Index > 1) {
3870 if (Info.getLangOpts().CPlusPlus11)
3871 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3872 << handler.AccessKind;
3873 else
3874 Info.FFDiag(E);
3875 return handler.failed();
3876 }
3877
3878 ObjType = getSubobjectType(
3879 ObjType, ObjType->castAs<ComplexType>()->getElementType());
3880
3881 assert(I == N - 1 && "extracting subobject of scalar?");
3882 if (O->isComplexInt()) {
3883 return handler.found(Index ? O->getComplexIntImag()
3884 : O->getComplexIntReal(), ObjType);
3885 } else {
3886 assert(O->isComplexFloat());
3887 return handler.found(Index ? O->getComplexFloatImag()
3888 : O->getComplexFloatReal(), ObjType);
3889 }
3890 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
3891 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3892 unsigned NumElements = VT->getNumElements();
3893 if (Index == NumElements) {
3894 if (Info.getLangOpts().CPlusPlus11)
3895 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3896 << handler.AccessKind;
3897 else
3898 Info.FFDiag(E);
3899 return handler.failed();
3900 }
3901
3902 if (Index > NumElements) {
3903 Info.CCEDiag(E, diag::note_constexpr_array_index)
3904 << Index << /*array*/ 0 << NumElements;
3905 return handler.failed();
3906 }
3907
3908 ObjType = VT->getElementType();
3909 assert(I == N - 1 && "extracting subobject of scalar?");
3910 return handler.found(O->getVectorElt(Index), ObjType);
3911 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3912 if (Field->isMutable() &&
3913 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3914 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3915 << handler.AccessKind << Field;
3916 Info.Note(Field->getLocation(), diag::note_declared_at);
3917 return handler.failed();
3918 }
3919
3920 // Next subobject is a class, struct or union field.
3921 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3922 if (RD->isUnion()) {
3923 const FieldDecl *UnionField = O->getUnionField();
3924 if (!UnionField ||
3925 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3926 if (I == N - 1 && handler.AccessKind == AK_Construct) {
3927 // Placement new onto an inactive union member makes it active.
3928 O->setUnion(Field, APValue());
3929 } else {
3930 // FIXME: If O->getUnionValue() is absent, report that there's no
3931 // active union member rather than reporting the prior active union
3932 // member. We'll need to fix nullptr_t to not use APValue() as its
3933 // representation first.
3934 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3935 << handler.AccessKind << Field << !UnionField << UnionField;
3936 return handler.failed();
3937 }
3938 }
3939 O = &O->getUnionValue();
3940 } else
3941 O = &O->getStructField(Field->getFieldIndex());
3942
3943 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3944 LastField = Field;
3945 if (Field->getType().isVolatileQualified())
3946 VolatileField = Field;
3947 } else {
3948 // Next subobject is a base class.
3949 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3950 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3951 O = &O->getStructBase(getBaseIndex(Derived, Base));
3952
3953 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3954 }
3955 }
3956}
3957
3958namespace {
3959struct ExtractSubobjectHandler {
3960 EvalInfo &Info;
3961 const Expr *E;
3962 APValue &Result;
3963 const AccessKinds AccessKind;
3964
3965 typedef bool result_type;
3966 bool failed() { return false; }
3967 bool found(APValue &Subobj, QualType SubobjType) {
3968 Result = Subobj;
3969 if (AccessKind == AK_ReadObjectRepresentation)
3970 return true;
3971 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3972 }
3973 bool found(APSInt &Value, QualType SubobjType) {
3974 Result = APValue(Value);
3975 return true;
3976 }
3977 bool found(APFloat &Value, QualType SubobjType) {
3978 Result = APValue(Value);
3979 return true;
3980 }
3981};
3982} // end anonymous namespace
3983
3984/// Extract the designated sub-object of an rvalue.
3985static bool extractSubobject(EvalInfo &Info, const Expr *E,
3986 const CompleteObject &Obj,
3987 const SubobjectDesignator &Sub, APValue &Result,
3988 AccessKinds AK = AK_Read) {
3989 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3990 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3991 return findSubobject(Info, E, Obj, Sub, Handler);
3992}
3993
3994namespace {
3995struct ModifySubobjectHandler {
3996 EvalInfo &Info;
3997 APValue &NewVal;
3998 const Expr *E;
3999
4000 typedef bool result_type;
4001 static const AccessKinds AccessKind = AK_Assign;
4002
4003 bool checkConst(QualType QT) {
4004 // Assigning to a const object has undefined behavior.
4005 if (QT.isConstQualified()) {
4006 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4007 return false;
4008 }
4009 return true;
4010 }
4011
4012 bool failed() { return false; }
4013 bool found(APValue &Subobj, QualType SubobjType) {
4014 if (!checkConst(SubobjType))
4015 return false;
4016 // We've been given ownership of NewVal, so just swap it in.
4017 Subobj.swap(NewVal);
4018 return true;
4019 }
4020 bool found(APSInt &Value, QualType SubobjType) {
4021 if (!checkConst(SubobjType))
4022 return false;
4023 if (!NewVal.isInt()) {
4024 // Maybe trying to write a cast pointer value into a complex?
4025 Info.FFDiag(E);
4026 return false;
4027 }
4028 Value = NewVal.getInt();
4029 return true;
4030 }
4031 bool found(APFloat &Value, QualType SubobjType) {
4032 if (!checkConst(SubobjType))
4033 return false;
4034 Value = NewVal.getFloat();
4035 return true;
4036 }
4037};
4038} // end anonymous namespace
4039
4040const AccessKinds ModifySubobjectHandler::AccessKind;
4041
4042/// Update the designated sub-object of an rvalue to the given value.
4043static bool modifySubobject(EvalInfo &Info, const Expr *E,
4044 const CompleteObject &Obj,
4045 const SubobjectDesignator &Sub,
4046 APValue &NewVal) {
4047 ModifySubobjectHandler Handler = { Info, NewVal, E };
4048 return findSubobject(Info, E, Obj, Sub, Handler);
4049}
4050
4051/// Find the position where two subobject designators diverge, or equivalently
4052/// the length of the common initial subsequence.
4053static unsigned FindDesignatorMismatch(QualType ObjType,
4054 const SubobjectDesignator &A,
4055 const SubobjectDesignator &B,
4056 bool &WasArrayIndex) {
4057 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4058 for (/**/; I != N; ++I) {
4059 if (!ObjType.isNull() &&
4060 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4061 // Next subobject is an array element.
4062 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4063 WasArrayIndex = true;
4064 return I;
4065 }
4066 if (ObjType->isAnyComplexType())
4067 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4068 else
4069 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4070 } else {
4071 if (A.Entries[I].getAsBaseOrMember() !=
4072 B.Entries[I].getAsBaseOrMember()) {
4073 WasArrayIndex = false;
4074 return I;
4075 }
4076 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4077 // Next subobject is a field.
4078 ObjType = FD->getType();
4079 else
4080 // Next subobject is a base class.
4081 ObjType = QualType();
4082 }
4083 }
4084 WasArrayIndex = false;
4085 return I;
4086}
4087
4088/// Determine whether the given subobject designators refer to elements of the
4089/// same array object.
4091 const SubobjectDesignator &A,
4092 const SubobjectDesignator &B) {
4093 if (A.Entries.size() != B.Entries.size())
4094 return false;
4095
4096 bool IsArray = A.MostDerivedIsArrayElement;
4097 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4098 // A is a subobject of the array element.
4099 return false;
4100
4101 // If A (and B) designates an array element, the last entry will be the array
4102 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4103 // of length 1' case, and the entire path must match.
4104 bool WasArrayIndex;
4105 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4106 return CommonLength >= A.Entries.size() - IsArray;
4107}
4108
4109/// Find the complete object to which an LValue refers.
4110static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4111 AccessKinds AK, const LValue &LVal,
4112 QualType LValType) {
4113 if (LVal.InvalidBase) {
4114 Info.FFDiag(E);
4115 return CompleteObject();
4116 }
4117
4118 if (!LVal.Base) {
4119 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4120 return CompleteObject();
4121 }
4122
4123 CallStackFrame *Frame = nullptr;
4124 unsigned Depth = 0;
4125 if (LVal.getLValueCallIndex()) {
4126 std::tie(Frame, Depth) =
4127 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4128 if (!Frame) {
4129 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4130 << AK << LVal.Base.is<const ValueDecl*>();
4131 NoteLValueLocation(Info, LVal.Base);
4132 return CompleteObject();
4133 }
4134 }
4135
4136 bool IsAccess = isAnyAccess(AK);
4137
4138 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4139 // is not a constant expression (even if the object is non-volatile). We also
4140 // apply this rule to C++98, in order to conform to the expected 'volatile'
4141 // semantics.
4142 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4143 if (Info.getLangOpts().CPlusPlus)
4144 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4145 << AK << LValType;
4146 else
4147 Info.FFDiag(E);
4148 return CompleteObject();
4149 }
4150
4151 // Compute value storage location and type of base object.
4152 APValue *BaseVal = nullptr;
4153 QualType BaseType = getType(LVal.Base);
4154
4155 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4156 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4157 // This is the object whose initializer we're evaluating, so its lifetime
4158 // started in the current evaluation.
4159 BaseVal = Info.EvaluatingDeclValue;
4160 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4161 // Allow reading from a GUID declaration.
4162 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4163 if (isModification(AK)) {
4164 // All the remaining cases do not permit modification of the object.
4165 Info.FFDiag(E, diag::note_constexpr_modify_global);
4166 return CompleteObject();
4167 }
4168 APValue &V = GD->getAsAPValue();
4169 if (V.isAbsent()) {
4170 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4171 << GD->getType();
4172 return CompleteObject();
4173 }
4174 return CompleteObject(LVal.Base, &V, GD->getType());
4175 }
4176
4177 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4178 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4179 if (isModification(AK)) {
4180 Info.FFDiag(E, diag::note_constexpr_modify_global);
4181 return CompleteObject();
4182 }
4183 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4184 GCD->getType());
4185 }
4186
4187 // Allow reading from template parameter objects.
4188 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4189 if (isModification(AK)) {
4190 Info.FFDiag(E, diag::note_constexpr_modify_global);
4191 return CompleteObject();
4192 }
4193 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4194 TPO->getType());
4195 }
4196
4197 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4198 // In C++11, constexpr, non-volatile variables initialized with constant
4199 // expressions are constant expressions too. Inside constexpr functions,
4200 // parameters are constant expressions even if they're non-const.
4201 // In C++1y, objects local to a constant expression (those with a Frame) are
4202 // both readable and writable inside constant expressions.
4203 // In C, such things can also be folded, although they are not ICEs.
4204 const VarDecl *VD = dyn_cast<VarDecl>(D);
4205 if (VD) {
4206 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4207 VD = VDef;
4208 }
4209 if (!VD || VD->isInvalidDecl()) {
4210 Info.FFDiag(E);
4211 return CompleteObject();
4212 }
4213
4214 bool IsConstant = BaseType.isConstant(Info.Ctx);
4215 bool ConstexprVar = false;
4216 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4217 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4218 ConstexprVar = VD->isConstexpr();
4219
4220 // Unless we're looking at a local variable or argument in a constexpr call,
4221 // the variable we're reading must be const.
4222 if (!Frame) {
4223 if (IsAccess && isa<ParmVarDecl>(VD)) {
4224 // Access of a parameter that's not associated with a frame isn't going
4225 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4226 // suitable diagnostic.
4227 } else if (Info.getLangOpts().CPlusPlus14 &&
4228 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4229 // OK, we can read and modify an object if we're in the process of
4230 // evaluating its initializer, because its lifetime began in this
4231 // evaluation.
4232 } else if (isModification(AK)) {
4233 // All the remaining cases do not permit modification of the object.
4234 Info.FFDiag(E, diag::note_constexpr_modify_global);
4235 return CompleteObject();
4236 } else if (VD->isConstexpr()) {
4237 // OK, we can read this variable.
4238 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4239 Info.FFDiag(E);
4240 return CompleteObject();
4241 } else if (BaseType->isIntegralOrEnumerationType()) {
4242 if (!IsConstant) {
4243 if (!IsAccess)
4244 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4245 if (Info.getLangOpts().CPlusPlus) {
4246 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4247 Info.Note(VD->getLocation(), diag::note_declared_at);
4248 } else {
4249 Info.FFDiag(E);
4250 }
4251 return CompleteObject();
4252 }
4253 } else if (!IsAccess) {
4254 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4255 } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4256 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4257 // This variable might end up being constexpr. Don't diagnose it yet.
4258 } else if (IsConstant) {
4259 // Keep evaluating to see what we can do. In particular, we support
4260 // folding of const floating-point types, in order to make static const
4261 // data members of such types (supported as an extension) more useful.
4262 if (Info.getLangOpts().CPlusPlus) {
4263 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4264 ? diag::note_constexpr_ltor_non_constexpr
4265 : diag::note_constexpr_ltor_non_integral, 1)
4266 << VD << BaseType;
4267 Info.Note(VD->getLocation(), diag::note_declared_at);
4268 } else {
4269 Info.CCEDiag(E);
4270 }
4271 } else {
4272 // Never allow reading a non-const value.
4273 if (Info.getLangOpts().CPlusPlus) {
4274 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4275 ? diag::note_constexpr_ltor_non_constexpr
4276 : diag::note_constexpr_ltor_non_integral, 1)
4277 << VD << BaseType;
4278 Info.Note(VD->getLocation(), diag::note_declared_at);
4279 } else {
4280 Info.FFDiag(E);
4281 }
4282 return CompleteObject();
4283 }
4284 }
4285
4286 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4287 return CompleteObject();
4288 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4289 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4290 if (!Alloc) {
4291 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4292 return CompleteObject();
4293 }
4294 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4295 LVal.Base.getDynamicAllocType());
4296 } else {
4297 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4298
4299 if (!Frame) {
4300 if (const MaterializeTemporaryExpr *MTE =
4301 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4302 assert(MTE->getStorageDuration() == SD_Static &&
4303 "should have a frame for a non-global materialized temporary");
4304
4305 // C++20 [expr.const]p4: [DR2126]
4306 // An object or reference is usable in constant expressions if it is
4307 // - a temporary object of non-volatile const-qualified literal type
4308 // whose lifetime is extended to that of a variable that is usable
4309 // in constant expressions
4310 //
4311 // C++20 [expr.const]p5:
4312 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4313 // - a non-volatile glvalue that refers to an object that is usable
4314 // in constant expressions, or
4315 // - a non-volatile glvalue of literal type that refers to a
4316 // non-volatile object whose lifetime began within the evaluation
4317 // of E;
4318 //
4319 // C++11 misses the 'began within the evaluation of e' check and
4320 // instead allows all temporaries, including things like:
4321 // int &&r = 1;
4322 // int x = ++r;
4323 // constexpr int k = r;
4324 // Therefore we use the C++14-onwards rules in C++11 too.
4325 //
4326 // Note that temporaries whose lifetimes began while evaluating a
4327 // variable's constructor are not usable while evaluating the
4328 // corresponding destructor, not even if they're of const-qualified
4329 // types.
4330 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4331 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4332 if (!IsAccess)
4333 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4334 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4335 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4336 return CompleteObject();
4337 }
4338
4339 BaseVal = MTE->getOrCreateValue(false);
4340 assert(BaseVal && "got reference to unevaluated temporary");
4341 } else {
4342 if (!IsAccess)
4343 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4344 APValue Val;
4345 LVal.moveInto(Val);
4346 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4347 << AK
4348 << Val.getAsString(Info.Ctx,
4349 Info.Ctx.getLValueReferenceType(LValType));
4350 NoteLValueLocation(Info, LVal.Base);
4351 return CompleteObject();
4352 }
4353 } else {
4354 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4355 assert(BaseVal && "missing value for temporary");
4356 }
4357 }
4358
4359 // In C++14, we can't safely access any mutable state when we might be
4360 // evaluating after an unmodeled side effect. Parameters are modeled as state
4361 // in the caller, but aren't visible once the call returns, so they can be
4362 // modified in a speculatively-evaluated call.
4363 //
4364 // FIXME: Not all local state is mutable. Allow local constant subobjects
4365 // to be read here (but take care with 'mutable' fields).
4366 unsigned VisibleDepth = Depth;
4367 if (llvm::isa_and_nonnull<ParmVarDecl>(
4368 LVal.Base.dyn_cast<const ValueDecl *>()))
4369 ++VisibleDepth;
4370 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4371 Info.EvalStatus.HasSideEffects) ||
4372 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4373 return CompleteObject();
4374
4375 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4376}
4377
4378/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4379/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4380/// glvalue referred to by an entity of reference type.
4381///
4382/// \param Info - Information about the ongoing evaluation.
4383/// \param Conv - The expression for which we are performing the conversion.
4384/// Used for diagnostics.
4385/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4386/// case of a non-class type).
4387/// \param LVal - The glvalue on which we are attempting to perform this action.
4388/// \param RVal - The produced value will be placed here.
4389/// \param WantObjectRepresentation - If true, we're looking for the object
4390/// representation rather than the value, and in particular,
4391/// there is no requirement that the result be fully initialized.
4392static bool
4394 const LValue &LVal, APValue &RVal,
4395 bool WantObjectRepresentation = false) {
4396 if (LVal.Designator.Invalid)
4397 return false;
4398
4399 // Check for special cases where there is no existing APValue to look at.
4400 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4401
4402 AccessKinds AK =
4403 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4404
4405 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4406 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4407 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4408 // initializer until now for such expressions. Such an expression can't be
4409 // an ICE in C, so this only matters for fold.
4410 if (Type.isVolatileQualified()) {
4411 Info.FFDiag(Conv);
4412 return false;
4413 }
4414
4415 APValue Lit;
4416 if (!Evaluate(Lit, Info, CLE->getInitializer()))
4417 return false;
4418
4419 // According to GCC info page:
4420 //
4421 // 6.28 Compound Literals
4422 //
4423 // As an optimization, G++ sometimes gives array compound literals longer
4424 // lifetimes: when the array either appears outside a function or has a
4425 // const-qualified type. If foo and its initializer had elements of type
4426 // char *const rather than char *, or if foo were a global variable, the
4427 // array would have static storage duration. But it is probably safest
4428 // just to avoid the use of array compound literals in C++ code.
4429 //
4430 // Obey that rule by checking constness for converted array types.
4431
4432 QualType CLETy = CLE->getType();
4433 if (CLETy->isArrayType() && !Type->isArrayType()) {
4434 if (!CLETy.isConstant(Info.Ctx)) {
4435 Info.FFDiag(Conv);
4436 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4437 return false;
4438 }
4439 }
4440
4441 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4442 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4443 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4444 // Special-case character extraction so we don't have to construct an
4445 // APValue for the whole string.
4446 assert(LVal.Designator.Entries.size() <= 1 &&
4447 "Can only read characters from string literals");
4448 if (LVal.Designator.Entries.empty()) {
4449 // Fail for now for LValue to RValue conversion of an array.
4450 // (This shouldn't show up in C/C++, but it could be triggered by a
4451 // weird EvaluateAsRValue call from a tool.)
4452 Info.FFDiag(Conv);
4453 return false;
4454 }
4455 if (LVal.Designator.isOnePastTheEnd()) {
4456 if (Info.getLangOpts().CPlusPlus11)
4457 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4458 else
4459 Info.FFDiag(Conv);
4460 return false;
4461 }
4462 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4463 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4464 return true;
4465 }
4466 }
4467
4468 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4469 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4470}
4471
4472/// Perform an assignment of Val to LVal. Takes ownership of Val.
4473static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4474 QualType LValType, APValue &Val) {
4475 if (LVal.Designator.Invalid)
4476 return false;
4477
4478 if (!Info.getLangOpts().CPlusPlus14) {
4479 Info.FFDiag(E);
4480 return false;
4481 }
4482
4483 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4484 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4485}
4486
4487namespace {
4488struct CompoundAssignSubobjectHandler {
4489 EvalInfo &Info;
4491 QualType PromotedLHSType;
4493 const APValue &RHS;
4494
4495 static const AccessKinds AccessKind = AK_Assign;
4496
4497 typedef bool result_type;
4498
4499 bool checkConst(QualType QT) {
4500 // Assigning to a const object has undefined behavior.
4501 if (QT.isConstQualified()) {
4502 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4503 return false;
4504 }
4505 return true;
4506 }
4507
4508 bool failed() { return false; }
4509 bool found(APValue &Subobj, QualType SubobjType) {
4510 switch (Subobj.getKind()) {
4511 case APValue::Int:
4512 return found(Subobj.getInt(), SubobjType);
4513 case APValue::Float:
4514 return found(Subobj.getFloat(), SubobjType);
4517 // FIXME: Implement complex compound assignment.
4518 Info.FFDiag(E);
4519 return false;
4520 case APValue::LValue:
4521 return foundPointer(Subobj, SubobjType);
4522 case APValue::Vector:
4523 return foundVector(Subobj, SubobjType);
4525 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4526 << /*read of=*/0 << /*uninitialized object=*/1
4527 << E->getLHS()->getSourceRange();
4528 return false;
4529 default:
4530 // FIXME: can this happen?
4531 Info.FFDiag(E);
4532 return false;
4533 }
4534 }
4535
4536 bool foundVector(APValue &Value, QualType SubobjType) {
4537 if (!checkConst(SubobjType))
4538 return false;
4539
4540 if (!SubobjType->isVectorType()) {
4541 Info.FFDiag(E);
4542 return false;
4543 }
4544 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4545 }
4546
4547 bool found(APSInt &Value, QualType SubobjType) {
4548 if (!checkConst(SubobjType))
4549 return false;
4550
4551 if (!SubobjType->isIntegerType()) {
4552 // We don't support compound assignment on integer-cast-to-pointer
4553 // values.
4554 Info.FFDiag(E);
4555 return false;
4556 }
4557
4558 if (RHS.isInt()) {
4559 APSInt LHS =
4560 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4561 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4562 return false;
4563 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4564 return true;
4565 } else if (RHS.isFloat()) {
4566 const FPOptions FPO = E->getFPFeaturesInEffect(
4567 Info.Ctx.getLangOpts());
4568 APFloat FValue(0.0);
4569 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4570 PromotedLHSType, FValue) &&
4571 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4572 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4573 Value);
4574 }
4575
4576 Info.FFDiag(E);
4577 return false;
4578 }
4579 bool found(APFloat &Value, QualType SubobjType) {
4580 return checkConst(SubobjType) &&
4581 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4582 Value) &&
4583 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4584 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4585 }
4586 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4587 if (!checkConst(SubobjType))
4588 return false;
4589
4590 QualType PointeeType;
4591 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4592 PointeeType = PT->getPointeeType();
4593
4594 if (PointeeType.isNull() || !RHS.isInt() ||
4595 (Opcode != BO_Add && Opcode != BO_Sub)) {
4596 Info.FFDiag(E);
4597 return false;
4598 }
4599
4600 APSInt Offset = RHS.getInt();
4601 if (Opcode == BO_Sub)
4602 negateAsSigned(Offset);
4603
4604 LValue LVal;
4605 LVal.setFrom(Info.Ctx, Subobj);
4606 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4607 return false;
4608 LVal.moveInto(Subobj);
4609 return true;
4610 }
4611};
4612} // end anonymous namespace
4613
4614const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4615
4616/// Perform a compound assignment of LVal <op>= RVal.
4617static bool handleCompoundAssignment(EvalInfo &Info,
4619 const LValue &LVal, QualType LValType,
4620 QualType PromotedLValType,
4621 BinaryOperatorKind Opcode,
4622 const APValue &RVal) {
4623 if (LVal.Designator.Invalid)
4624 return false;
4625
4626 if (!Info.getLangOpts().CPlusPlus14) {
4627 Info.FFDiag(E);
4628 return false;
4629 }
4630
4631 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4632 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4633 RVal };
4634 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4635}
4636
4637namespace {
4638struct IncDecSubobjectHandler {
4639 EvalInfo &Info;
4640 const UnaryOperator *E;
4641 AccessKinds AccessKind;
4642 APValue *Old;
4643
4644 typedef bool result_type;
4645
4646 bool checkConst(QualType QT) {
4647 // Assigning to a const object has undefined behavior.
4648 if (QT.isConstQualified()) {
4649 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4650 return false;
4651 }
4652 return true;
4653 }
4654
4655 bool failed() { return false; }
4656 bool found(APValue &Subobj, QualType SubobjType) {
4657 // Stash the old value. Also clear Old, so we don't clobber it later
4658 // if we're post-incrementing a complex.
4659 if (Old) {
4660 *Old = Subobj;
4661 Old = nullptr;
4662 }
4663
4664 switch (Subobj.getKind()) {
4665 case APValue::Int:
4666 return found(Subobj.getInt(), SubobjType);
4667 case APValue::Float:
4668 return found(Subobj.getFloat(), SubobjType);
4670 return found(Subobj.getComplexIntReal(),
4671 SubobjType->castAs<ComplexType>()->getElementType()
4672 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4674 return found(Subobj.getComplexFloatReal(),
4675 SubobjType->castAs<ComplexType>()->getElementType()
4676 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4677 case APValue::LValue:
4678 return foundPointer(Subobj, SubobjType);
4679 default:
4680 // FIXME: can this happen?
4681 Info.FFDiag(E);
4682 return false;
4683 }
4684 }
4685 bool found(APSInt &Value, QualType SubobjType) {
4686 if (!checkConst(SubobjType))
4687 return false;
4688
4689 if (!SubobjType->isIntegerType()) {
4690 // We don't support increment / decrement on integer-cast-to-pointer
4691 // values.
4692 Info.FFDiag(E);
4693 return false;
4694 }
4695
4696 if (Old) *Old = APValue(Value);
4697
4698 // bool arithmetic promotes to int, and the conversion back to bool
4699 // doesn't reduce mod 2^n, so special-case it.
4700 if (SubobjType->isBooleanType()) {
4701 if (AccessKind == AK_Increment)
4702 Value = 1;
4703 else
4704 Value = !Value;
4705 return true;
4706 }
4707
4708 bool WasNegative = Value.isNegative();
4709 if (AccessKind == AK_Increment) {
4710 ++Value;
4711
4712 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4713 APSInt ActualValue(Value, /*IsUnsigned*/true);
4714 return HandleOverflow(Info, E, ActualValue, SubobjType);
4715 }
4716 } else {
4717 --Value;
4718
4719 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4720 unsigned BitWidth = Value.getBitWidth();
4721 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4722 ActualValue.setBit(BitWidth);
4723 return HandleOverflow(Info, E, ActualValue, SubobjType);
4724 }
4725 }
4726 return true;
4727 }
4728 bool found(APFloat &Value, QualType SubobjType) {
4729 if (!checkConst(SubobjType))
4730 return false;
4731
4732 if (Old) *Old = APValue(Value);
4733
4734 APFloat One(Value.getSemantics(), 1);
4735 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4736 APFloat::opStatus St;
4737 if (AccessKind == AK_Increment)
4738 St = Value.add(One, RM);
4739 else
4740 St = Value.subtract(One, RM);
4741 return checkFloatingPointResult(Info, E, St);
4742 }
4743 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4744 if (!checkConst(SubobjType))
4745 return false;
4746
4747 QualType PointeeType;
4748 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4749 PointeeType = PT->getPointeeType();
4750 else {
4751 Info.FFDiag(E);
4752 return false;
4753 }
4754
4755 LValue LVal;
4756 LVal.setFrom(Info.Ctx, Subobj);
4757 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4758 AccessKind == AK_Increment ? 1 : -1))
4759 return false;
4760 LVal.moveInto(Subobj);
4761 return true;
4762 }
4763};
4764} // end anonymous namespace
4765
4766/// Perform an increment or decrement on LVal.
4767static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4768 QualType LValType, bool IsIncrement, APValue *Old) {
4769 if (LVal.Designator.Invalid)
4770 return false;
4771
4772 if (!Info.getLangOpts().CPlusPlus14) {
4773 Info.FFDiag(E);
4774 return false;
4775 }
4776
4777 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4778 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4779 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4780 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4781}
4782
4783/// Build an lvalue for the object argument of a member function call.
4784static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4785 LValue &This) {
4786 if (Object->getType()->isPointerType() && Object->isPRValue())
4787 return EvaluatePointer(Object, This, Info);
4788
4789 if (Object->isGLValue())
4790 return EvaluateLValue(Object, This, Info);
4791
4792 if (Object->getType()->isLiteralType(Info.Ctx))
4793 return EvaluateTemporary(Object, This, Info);
4794
4795 if (Object->getType()->isRecordType() && Object->isPRValue())
4796 return EvaluateTemporary(Object, This, Info);
4797
4798 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4799 return false;
4800}
4801
4802/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4803/// lvalue referring to the result.
4804///
4805/// \param Info - Information about the ongoing evaluation.
4806/// \param LV - An lvalue referring to the base of the member pointer.
4807/// \param RHS - The member pointer expression.
4808/// \param IncludeMember - Specifies whether the member itself is included in
4809/// the resulting LValue subobject designator. This is not possible when
4810/// creating a bound member function.
4811/// \return The field or method declaration to which the member pointer refers,
4812/// or 0 if evaluation fails.
4813static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4814 QualType LVType,
4815 LValue &LV,
4816 const Expr *RHS,
4817 bool IncludeMember = true) {
4818 MemberPtr MemPtr;
4819 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4820 return nullptr;
4821
4822 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4823 // member value, the behavior is undefined.
4824 if (!MemPtr.getDecl()) {
4825 // FIXME: Specific diagnostic.
4826 Info.FFDiag(RHS);
4827 return nullptr;
4828 }
4829
4830 if (MemPtr.isDerivedMember()) {
4831 // This is a member of some derived class. Truncate LV appropriately.
4832 // The end of the derived-to-base path for the base object must match the
4833 // derived-to-base path for the member pointer.
4834 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4835 LV.Designator.Entries.size()) {
4836 Info.FFDiag(RHS);
4837 return nullptr;
4838 }
4839 unsigned PathLengthToMember =
4840 LV.Designator.Entries.size() - MemPtr.Path.size();
4841 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4842 const CXXRecordDecl *LVDecl = getAsBaseClass(
4843 LV.Designator.Entries[PathLengthToMember + I]);
4844 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4845 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4846 Info.FFDiag(RHS);
4847 return nullptr;
4848 }
4849 }
4850
4851 // Truncate the lvalue to the appropriate derived class.
4852 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4853 PathLengthToMember))
4854 return nullptr;
4855 } else if (!MemPtr.Path.empty()) {
4856 // Extend the LValue path with the member pointer's path.
4857 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4858 MemPtr.Path.size() + IncludeMember);
4859
4860 // Walk down to the appropriate base class.
4861 if (const PointerType *PT = LVType->getAs<PointerType>())
4862 LVType = PT->getPointeeType();
4863 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4864 assert(RD && "member pointer access on non-class-type expression");
4865 // The first class in the path is that of the lvalue.
4866 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4867 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4868 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4869 return nullptr;
4870 RD = Base;
4871 }
4872 // Finally cast to the class containing the member.
4873 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4874 MemPtr.getContainingRecord()))
4875 return nullptr;
4876 }
4877
4878 // Add the member. Note that we cannot build bound member functions here.
4879 if (IncludeMember) {
4880 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4881 if (!HandleLValueMember(Info, RHS, LV, FD))
4882 return nullptr;
4883 } else if (const IndirectFieldDecl *IFD =
4884 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4885 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4886 return nullptr;
4887 } else {
4888 llvm_unreachable("can't construct reference to bound member function");
4889 }
4890 }
4891
4892 return MemPtr.getDecl();
4893}
4894
4895static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4896 const BinaryOperator *BO,
4897 LValue &LV,
4898 bool IncludeMember = true) {
4899 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4900
4901 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4902 if (Info.noteFailure()) {
4903 MemberPtr MemPtr;
4904 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4905 }
4906 return nullptr;
4907 }
4908
4909 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4910 BO->getRHS(), IncludeMember);
4911}
4912
4913/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4914/// the provided lvalue, which currently refers to the base object.
4915static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4916 LValue &Result) {
4917 SubobjectDesignator &D = Result.Designator;
4918 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4919 return false;
4920
4921 QualType TargetQT = E->getType();
4922 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4923 TargetQT = PT->getPointeeType();
4924
4925 // Check this cast lands within the final derived-to-base subobject path.
4926 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4927 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4928 << D.MostDerivedType << TargetQT;
4929 return false;
4930 }
4931
4932 // Check the type of the final cast. We don't need to check the path,
4933 // since a cast can only be formed if the path is unique.
4934 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4935 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4936 const CXXRecordDecl *FinalType;
4937 if (NewEntriesSize == D.MostDerivedPathLength)
4938 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4939 else
4940 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4941 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4942 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4943 << D.MostDerivedType << TargetQT;
4944 return false;
4945 }
4946
4947 // Truncate the lvalue to the appropriate derived class.
4948 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4949}
4950
4951/// Get the value to use for a default-initialized object of type T.
4952/// Return false if it encounters something invalid.
4954 bool Success = true;
4955
4956 // If there is already a value present don't overwrite it.
4957 if (!Result.isAbsent())
4958 return true;
4959
4960 if (auto *RD = T->getAsCXXRecordDecl()) {
4961 if (RD->isInvalidDecl()) {
4962 Result = APValue();
4963 return false;
4964 }
4965 if (RD->isUnion()) {
4966 Result = APValue((const FieldDecl *)nullptr);
4967 return true;
4968 }
4969 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4970 std::distance(RD->field_begin(), RD->field_end()));
4971
4972 unsigned Index = 0;
4973 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4974 End = RD->bases_end();
4975 I != End; ++I, ++Index)
4976 Success &=
4977 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
4978
4979 for (const auto *I : RD->fields()) {
4980 if (I->isUnnamedBitField())
4981 continue;
4983 I->getType(), Result.getStructField(I->getFieldIndex()));
4984 }
4985 return Success;
4986 }
4987
4988 if (auto *AT =
4989 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4990 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
4991 if (Result.hasArrayFiller())
4992 Success &=
4993 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4994
4995 return Success;
4996 }
4997
4998 Result = APValue::IndeterminateValue();
4999 return true;
5000}
5001
5002namespace {
5003enum EvalStmtResult {
5004 /// Evaluation failed.
5005 ESR_Failed,
5006 /// Hit a 'return' statement.
5007 ESR_Returned,
5008 /// Evaluation succeeded.
5009 ESR_Succeeded,
5010 /// Hit a 'continue' statement.
5011 ESR_Continue,
5012 /// Hit a 'break' statement.
5013 ESR_Break,
5014 /// Still scanning for 'case' or 'default' statement.
5015 ESR_CaseNotFound
5016};
5017}
5018
5019static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5020 if (VD->isInvalidDecl())
5021 return false;
5022 // We don't need to evaluate the initializer for a static local.
5023 if (!VD->hasLocalStorage())
5024 return true;
5025
5026 LValue Result;
5027 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5028 ScopeKind::Block, Result);
5029
5030 const Expr *InitE = VD->getInit();
5031 if (!InitE) {
5032 if (VD->getType()->isDependentType())
5033 return Info.noteSideEffect();
5034 return handleDefaultInitValue(VD->getType(), Val);
5035 }
5036 if (InitE->isValueDependent())
5037 return false;
5038
5039 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5040 // Wipe out any partially-computed value, to allow tracking that this
5041 // evaluation failed.
5042 Val = APValue();
5043 return false;
5044 }
5045
5046 return true;
5047}
5048
5049static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
5050 bool OK = true;
5051
5052 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5053 OK &= EvaluateVarDecl(Info, VD);
5054
5055 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
5056 for (auto *BD : DD->bindings())
5057 if (auto *VD = BD->getHoldingVar())
5058 OK &= EvaluateDecl(Info, VD);
5059
5060 return OK;
5061}
5062
5063static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5064 assert(E->isValueDependent());
5065 if (Info.noteSideEffect())
5066 return true;
5067 assert(E->containsErrors() && "valid value-dependent expression should never "
5068 "reach invalid code path.");
5069 return false;
5070}
5071
5072/// Evaluate a condition (either a variable declaration or an expression).
5073static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5074 const Expr *Cond, bool &Result) {
5075 if (Cond->isValueDependent())
5076 return false;
5077 FullExpressionRAII Scope(Info);
5078 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5079 return false;
5080 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5081 return false;
5082 return Scope.destroy();
5083}
5084
5085namespace {
5086/// A location where the result (returned value) of evaluating a
5087/// statement should be stored.
5088struct StmtResult {
5089 /// The APValue that should be filled in with the returned value.
5090 APValue &Value;
5091 /// The location containing the result, if any (used to support RVO).
5092 const LValue *Slot;
5093};
5094
5095struct TempVersionRAII {
5096 CallStackFrame &Frame;
5097
5098 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5099 Frame.pushTempVersion();
5100 }
5101
5102 ~TempVersionRAII() {
5103 Frame.popTempVersion();
5104 }
5105};
5106
5107}
5108
5109static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5110 const Stmt *S,
5111 const SwitchCase *SC = nullptr);
5112
5113/// Evaluate the body of a loop, and translate the result as appropriate.
5114static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5115 const Stmt *Body,
5116 const SwitchCase *Case = nullptr) {
5117 BlockScopeRAII Scope(Info);
5118
5119 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5120 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5121 ESR = ESR_Failed;
5122
5123 switch (ESR) {
5124 case ESR_Break:
5125 return ESR_Succeeded;
5126 case ESR_Succeeded:
5127 case ESR_Continue:
5128 return ESR_Continue;
5129 case ESR_Failed:
5130 case ESR_Returned:
5131 case ESR_CaseNotFound:
5132 return ESR;
5133 }
5134 llvm_unreachable("Invalid EvalStmtResult!");
5135}
5136
5137/// Evaluate a switch statement.
5138static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5139 const SwitchStmt *SS) {
5140 BlockScopeRAII Scope(Info);
5141
5142 // Evaluate the switch condition.
5143 APSInt Value;
5144 {
5145 if (const Stmt *Init = SS->getInit()) {
5146 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5147 if (ESR != ESR_Succeeded) {
5148 if (ESR != ESR_Failed && !Scope.destroy())
5149 ESR = ESR_Failed;
5150 return ESR;
5151 }
5152 }
5153
5154 FullExpressionRAII CondScope(Info);
5155 if (SS->getConditionVariable() &&
5156 !EvaluateDecl(Info, SS->getConditionVariable()))
5157 return ESR_Failed;
5158 if (SS->getCond()->isValueDependent()) {
5159 // We don't know what the value is, and which branch should jump to.
5160 EvaluateDependentExpr(SS->getCond(), Info);
5161 return ESR_Failed;
5162 }
5163 if (!EvaluateInteger(SS->getCond(), Value, Info))
5164 return ESR_Failed;
5165
5166 if (!CondScope.destroy())
5167 return ESR_Failed;
5168 }
5169
5170 // Find the switch case corresponding to the value of the condition.
5171 // FIXME: Cache this lookup.
5172 const SwitchCase *Found = nullptr;
5173 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5174 SC = SC->getNextSwitchCase()) {
5175 if (isa<DefaultStmt>(SC)) {
5176 Found = SC;
5177 continue;
5178 }
5179
5180 const CaseStmt *CS = cast<CaseStmt>(SC);
5181 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5182 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5183 : LHS;
5184 if (LHS <= Value && Value <= RHS) {
5185 Found = SC;
5186 break;
5187 }
5188 }
5189
5190 if (!Found)
5191 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5192
5193 // Search the switch body for the switch case and evaluate it from there.
5194 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5195 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5196 return ESR_Failed;
5197
5198 switch (ESR) {
5199 case ESR_Break:
5200 return ESR_Succeeded;
5201 case ESR_Succeeded:
5202 case ESR_Continue:
5203 case ESR_Failed:
5204 case ESR_Returned:
5205 return ESR;
5206 case ESR_CaseNotFound:
5207 // This can only happen if the switch case is nested within a statement
5208 // expression. We have no intention of supporting that.
5209 Info.FFDiag(Found->getBeginLoc(),
5210 diag::note_constexpr_stmt_expr_unsupported);
5211 return ESR_Failed;
5212 }
5213 llvm_unreachable("Invalid EvalStmtResult!");
5214}
5215
5216static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5217 // An expression E is a core constant expression unless the evaluation of E
5218 // would evaluate one of the following: [C++23] - a control flow that passes
5219 // through a declaration of a variable with static or thread storage duration
5220 // unless that variable is usable in constant expressions.
5221 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5222 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5223 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5224 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5225 return false;
5226 }
5227 return true;
5228}
5229
5230// Evaluate a statement.
5231static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5232 const Stmt *S, const SwitchCase *Case) {
5233 if (!Info.nextStep(S))
5234 return ESR_Failed;
5235
5236 // If we're hunting down a 'case' or 'default' label, recurse through
5237 // substatements until we hit the label.
5238 if (Case) {
5239 switch (S->getStmtClass()) {
5240 case Stmt::CompoundStmtClass:
5241 // FIXME: Precompute which substatement of a compound statement we
5242 // would jump to, and go straight there rather than performing a
5243 // linear scan each time.
5244 case Stmt::LabelStmtClass:
5245 case Stmt::AttributedStmtClass:
5246 case Stmt::DoStmtClass:
5247 break;
5248
5249 case Stmt::CaseStmtClass:
5250 case Stmt::DefaultStmtClass:
5251 if (Case == S)
5252 Case = nullptr;
5253 break;
5254
5255 case Stmt::IfStmtClass: {
5256 // FIXME: Precompute which side of an 'if' we would jump to, and go
5257 // straight there rather than scanning both sides.
5258 const IfStmt *IS = cast<IfStmt>(S);
5259
5260 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5261 // preceded by our switch label.
5262 BlockScopeRAII Scope(Info);
5263
5264 // Step into the init statement in case it brings an (uninitialized)
5265 // variable into scope.
5266 if (const Stmt *Init = IS->getInit()) {
5267 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5268 if (ESR != ESR_CaseNotFound) {
5269 assert(ESR != ESR_Succeeded);
5270 return ESR;
5271 }
5272 }
5273
5274 // Condition variable must be initialized if it exists.
5275 // FIXME: We can skip evaluating the body if there's a condition
5276 // variable, as there can't be any case labels within it.
5277 // (The same is true for 'for' statements.)
5278
5279 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5280 if (ESR == ESR_Failed)
5281 return ESR;
5282 if (ESR != ESR_CaseNotFound)
5283 return Scope.destroy() ? ESR : ESR_Failed;
5284 if (!IS->getElse())
5285 return ESR_CaseNotFound;
5286
5287 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5288 if (ESR == ESR_Failed)
5289 return ESR;
5290 if (ESR != ESR_CaseNotFound)
5291 return Scope.destroy() ? ESR : ESR_Failed;
5292 return ESR_CaseNotFound;
5293 }
5294
5295 case Stmt::WhileStmtClass: {
5296 EvalStmtResult ESR =
5297 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5298 if (ESR != ESR_Continue)
5299 return ESR;
5300 break;
5301 }
5302
5303 case Stmt::ForStmtClass: {
5304 const ForStmt *FS = cast<ForStmt>(S);
5305 BlockScopeRAII Scope(Info);
5306
5307 // Step into the init statement in case it brings an (uninitialized)
5308 // variable into scope.
5309 if (const Stmt *Init = FS->getInit()) {
5310 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5311 if (ESR != ESR_CaseNotFound) {
5312 assert(ESR != ESR_Succeeded);
5313 return ESR;
5314 }
5315 }
5316
5317 EvalStmtResult ESR =
5318 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5319 if (ESR != ESR_Continue)
5320 return ESR;
5321 if (const auto *Inc = FS->getInc()) {
5322 if (Inc->isValueDependent()) {
5323 if (!EvaluateDependentExpr(Inc, Info))
5324 return ESR_Failed;
5325 } else {
5326 FullExpressionRAII IncScope(Info);
5327 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5328 return ESR_Failed;
5329 }
5330 }
5331 break;
5332 }
5333
5334 case Stmt::DeclStmtClass: {
5335 // Start the lifetime of any uninitialized variables we encounter. They
5336 // might be used by the selected branch of the switch.
5337 const DeclStmt *DS = cast<DeclStmt>(S);
5338 for (const auto *D : DS->decls()) {
5339 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5340 if (!CheckLocalVariableDeclaration(Info, VD))
5341 return ESR_Failed;
5342 if (VD->hasLocalStorage() && !VD->getInit())
5343 if (!EvaluateVarDecl(Info, VD))
5344 return ESR_Failed;
5345 // FIXME: If the variable has initialization that can't be jumped
5346 // over, bail out of any immediately-surrounding compound-statement
5347 // too. There can't be any case labels here.
5348 }
5349 }
5350 return ESR_CaseNotFound;
5351 }
5352
5353 default:
5354 return ESR_CaseNotFound;
5355 }
5356 }
5357
5358 switch (S->getStmtClass()) {
5359 default:
5360 if (const Expr *E = dyn_cast<Expr>(S)) {
5361 if (E->isValueDependent()) {
5362 if (!EvaluateDependentExpr(E, Info))
5363 return ESR_Failed;
5364 } else {
5365 // Don't bother evaluating beyond an expression-statement which couldn't
5366 // be evaluated.
5367 // FIXME: Do we need the FullExpressionRAII object here?
5368 // VisitExprWithCleanups should create one when necessary.
5369 FullExpressionRAII Scope(Info);
5370 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5371 return ESR_Failed;
5372 }
5373 return ESR_Succeeded;
5374 }
5375
5376 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5377 return ESR_Failed;
5378
5379 case Stmt::NullStmtClass:
5380 return ESR_Succeeded;
5381
5382 case Stmt::DeclStmtClass: {
5383 const DeclStmt *DS = cast<DeclStmt>(S);
5384 for (const auto *D : DS->decls()) {
5385 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5386 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5387 return ESR_Failed;
5388 // Each declaration initialization is its own full-expression.
5389 FullExpressionRAII Scope(Info);
5390 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5391 return ESR_Failed;
5392 if (!Scope.destroy())
5393 return ESR_Failed;
5394 }
5395 return ESR_Succeeded;
5396 }
5397
5398 case Stmt::ReturnStmtClass: {
5399 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5400 FullExpressionRAII Scope(Info);
5401 if (RetExpr && RetExpr->isValueDependent()) {
5402 EvaluateDependentExpr(RetExpr, Info);
5403 // We know we returned, but we don't know what the value is.
5404 return ESR_Failed;
5405 }
5406 if (RetExpr &&
5407 !(Result.Slot
5408 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5409 : Evaluate(Result.Value, Info, RetExpr)))
5410 return ESR_Failed;
5411 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5412 }
5413
5414 case Stmt::CompoundStmtClass: {
5415 BlockScopeRAII Scope(Info);
5416
5417 const CompoundStmt *CS = cast<CompoundStmt>(S);
5418 for (const auto *BI : CS->body()) {
5419 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5420 if (ESR == ESR_Succeeded)
5421 Case = nullptr;
5422 else if (ESR != ESR_CaseNotFound) {
5423 if (ESR != ESR_Failed && !Scope.destroy())
5424 return ESR_Failed;
5425 return ESR;
5426 }
5427 }
5428 if (Case)
5429 return ESR_CaseNotFound;
5430 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5431 }
5432
5433 case Stmt::IfStmtClass: {
5434 const IfStmt *IS = cast<IfStmt>(S);
5435
5436 // Evaluate the condition, as either a var decl or as an expression.
5437 BlockScopeRAII Scope(Info);
5438 if (const Stmt *Init = IS->getInit()) {
5439 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5440 if (ESR != ESR_Succeeded) {
5441 if (ESR != ESR_Failed && !Scope.destroy())
5442 return ESR_Failed;
5443 return ESR;
5444 }
5445 }
5446 bool Cond;
5447 if (IS->isConsteval()) {
5448 Cond = IS->isNonNegatedConsteval();
5449 // If we are not in a constant context, if consteval should not evaluate
5450 // to true.
5451 if (!Info.InConstantContext)
5452 Cond = !Cond;
5453 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5454 Cond))
5455 return ESR_Failed;
5456
5457 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5458 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5459 if (ESR != ESR_Succeeded) {
5460 if (ESR != ESR_Failed && !Scope.destroy())
5461 return ESR_Failed;
5462 return ESR;
5463 }
5464 }
5465 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5466 }
5467
5468 case Stmt::WhileStmtClass: {
5469 const WhileStmt *WS = cast<WhileStmt>(S);
5470 while (true) {
5471 BlockScopeRAII Scope(Info);
5472 bool Continue;
5473 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5474 Continue))
5475 return ESR_Failed;
5476 if (!Continue)
5477 break;
5478
5479 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5480 if (ESR != ESR_Continue) {
5481 if (ESR != ESR_Failed && !Scope.destroy())
5482 return ESR_Failed;
5483 return ESR;
5484 }
5485 if (!Scope.destroy())
5486 return ESR_Failed;
5487 }
5488 return ESR_Succeeded;
5489 }
5490
5491 case Stmt::DoStmtClass: {
5492 const DoStmt *DS = cast<DoStmt>(S);
5493 bool Continue;
5494 do {
5495 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5496 if (ESR != ESR_Continue)
5497 return ESR;
5498 Case = nullptr;
5499
5500 if (DS->getCond()->isValueDependent()) {
5501 EvaluateDependentExpr(DS->getCond(), Info);
5502 // Bailout as we don't know whether to keep going or terminate the loop.
5503 return ESR_Failed;
5504 }
5505 FullExpressionRAII CondScope(Info);
5506 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5507 !CondScope.destroy())
5508 return ESR_Failed;
5509 } while (Continue);
5510 return ESR_Succeeded;
5511 }
5512
5513 case Stmt::ForStmtClass: {
5514 const ForStmt *FS = cast<ForStmt>(S);
5515 BlockScopeRAII ForScope(Info);
5516 if (FS->getInit()) {
5517 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5518 if (ESR != ESR_Succeeded) {
5519 if (ESR != ESR_Failed && !ForScope.destroy())
5520 return ESR_Failed;
5521 return ESR;
5522 }
5523 }
5524 while (true) {
5525 BlockScopeRAII IterScope(Info);
5526 bool Continue = true;
5527 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5528 FS->getCond(), Continue))
5529 return ESR_Failed;
5530 if (!Continue)
5531 break;
5532
5533 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5534 if (ESR != ESR_Continue) {
5535 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5536 return ESR_Failed;
5537 return ESR;
5538 }
5539
5540 if (const auto *Inc = FS->getInc()) {
5541 if (Inc->isValueDependent()) {
5542 if (!EvaluateDependentExpr(Inc, Info))
5543 return ESR_Failed;
5544 } else {
5545 FullExpressionRAII IncScope(Info);
5546 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5547 return ESR_Failed;
5548 }
5549 }
5550
5551 if (!IterScope.destroy())
5552 return ESR_Failed;
5553 }
5554 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5555 }
5556
5557 case Stmt::CXXForRangeStmtClass: {
5558 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5559 BlockScopeRAII Scope(Info);
5560
5561 // Evaluate the init-statement if present.
5562 if (FS->getInit()) {
5563 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5564 if (ESR != ESR_Succeeded) {
5565 if (ESR != ESR_Failed && !Scope.destroy())
5566 return ESR_Failed;
5567 return ESR;
5568 }
5569 }
5570
5571 // Initialize the __range variable.
5572 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5573 if (ESR != ESR_Succeeded) {
5574 if (ESR != ESR_Failed && !Scope.destroy())
5575 return ESR_Failed;
5576 return ESR;
5577 }
5578
5579 // In error-recovery cases it's possible to get here even if we failed to
5580 // synthesize the __begin and __end variables.
5581 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5582 return ESR_Failed;
5583
5584 // Create the __begin and __end iterators.
5585 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5586 if (ESR != ESR_Succeeded) {
5587 if (ESR != ESR_Failed && !Scope.destroy())
5588 return ESR_Failed;
5589 return ESR;
5590 }
5591 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5592 if (ESR != ESR_Succeeded) {
5593 if (ESR != ESR_Failed && !Scope.destroy())
5594 return ESR_Failed;
5595 return ESR;
5596 }
5597
5598 while (true) {
5599 // Condition: __begin != __end.
5600 {
5601 if (FS->getCond()->isValueDependent()) {
5602 EvaluateDependentExpr(FS->getCond(), Info);
5603 // We don't know whether to keep going or terminate the loop.
5604 return ESR_Failed;
5605 }
5606 bool Continue = true;
5607 FullExpressionRAII CondExpr(Info);
5608 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5609 return ESR_Failed;
5610 if (!Continue)
5611 break;
5612 }
5613
5614 // User's variable declaration, initialized by *__begin.
5615 BlockScopeRAII InnerScope(Info);
5616 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5617 if (ESR != ESR_Succeeded) {
5618 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5619 return ESR_Failed;
5620 return ESR;
5621 }
5622
5623 // Loop body.
5624 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5625 if (ESR != ESR_Continue) {
5626 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5627 return ESR_Failed;
5628 return ESR;
5629 }
5630 if (FS->getInc()->isValueDependent()) {
5631 if (!EvaluateDependentExpr(FS->getInc(), Info))
5632 return ESR_Failed;
5633 } else {
5634 // Increment: ++__begin
5635 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5636 return ESR_Failed;
5637 }
5638
5639 if (!InnerScope.destroy())
5640 return ESR_Failed;
5641 }
5642
5643 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5644 }
5645
5646 case Stmt::SwitchStmtClass:
5647 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5648
5649 case Stmt::ContinueStmtClass:
5650 return ESR_Continue;
5651
5652 case Stmt::BreakStmtClass:
5653 return ESR_Break;
5654
5655 case Stmt::LabelStmtClass:
5656 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5657
5658 case Stmt::AttributedStmtClass: {
5659 const auto *AS = cast<AttributedStmt>(S);
5660 const auto *SS = AS->getSubStmt();
5661 MSConstexprContextRAII ConstexprContext(
5662 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
5663 isa<ReturnStmt>(SS));
5664
5665 auto LO = Info.getCtx().getLangOpts();
5666 if (LO.CXXAssumptions && !LO.MSVCCompat) {
5667 for (auto *Attr : AS->getAttrs()) {
5668 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
5669 if (!AA)
5670 continue;
5671
5672 auto *Assumption = AA->getAssumption();
5673 if (Assumption->isValueDependent())
5674 return ESR_Failed;
5675
5676 if (Assumption->HasSideEffects(Info.getCtx()))
5677 continue;
5678
5679 bool Value;
5680 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
5681 return ESR_Failed;
5682 if (!Value) {
5683 Info.CCEDiag(Assumption->getExprLoc(),
5684 diag::note_constexpr_assumption_failed);
5685 return ESR_Failed;
5686 }
5687 }
5688 }
5689
5690 return EvaluateStmt(Result, Info, SS, Case);
5691 }
5692
5693 case Stmt::CaseStmtClass:
5694 case Stmt::DefaultStmtClass:
5695 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5696 case Stmt::CXXTryStmtClass:
5697 // Evaluate try blocks by evaluating all sub statements.
5698 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5699 }
5700}
5701
5702/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5703/// default constructor. If so, we'll fold it whether or not it's marked as
5704/// constexpr. If it is marked as constexpr, we will never implicitly define it,
5705/// so we need special handling.
5707 const CXXConstructorDecl *CD,
5708 bool IsValueInitialization) {
5709 if (!CD->isTrivial() || !CD->isDefaultConstructor())
5710 return false;
5711
5712 // Value-initialization does not call a trivial default constructor, so such a
5713 // call is a core constant expression whether or not the constructor is
5714 // constexpr.
5715 if (!CD->isConstexpr() && !IsValueInitialization) {
5716 if (Info.getLangOpts().CPlusPlus11) {
5717 // FIXME: If DiagDecl is an implicitly-declared special member function,
5718 // we should be much more explicit about why it's not constexpr.
5719 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5720 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5721 Info.Note(CD->getLocation(), diag::note_declared_at);
5722 } else {
5723 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5724 }
5725 }
5726 return true;
5727}
5728
5729/// CheckConstexprFunction - Check that a function can be called in a constant
5730/// expression.
5731static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5733 const FunctionDecl *Definition,
5734 const Stmt *Body) {
5735 // Potential constant expressions can contain calls to declared, but not yet
5736 // defined, constexpr functions.
5737 if (Info.checkingPotentialConstantExpression() && !Definition &&
5738 Declaration->isConstexpr())
5739 return false;
5740
5741 // Bail out if the function declaration itself is invalid. We will
5742 // have produced a relevant diagnostic while parsing it, so just
5743 // note the problematic sub-expression.
5744 if (Declaration->isInvalidDecl()) {
5745 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5746 return false;
5747 }
5748
5749 // DR1872: An instantiated virtual constexpr function can't be called in a
5750 // constant expression (prior to C++20). We can still constant-fold such a
5751 // call.
5752 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5753 cast<CXXMethodDecl>(Declaration)->isVirtual())
5754 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5755
5756 if (Definition && Definition->isInvalidDecl()) {
5757 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5758 return false;
5759 }
5760
5761 // Can we evaluate this function call?
5762 if (Definition && Body &&
5763 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
5764 Definition->hasAttr<MSConstexprAttr>())))
5765 return true;
5766
5767 if (Info.getLangOpts().CPlusPlus11) {
5768 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5769
5770 // If this function is not constexpr because it is an inherited
5771 // non-constexpr constructor, diagnose that directly.
5772 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5773 if (CD && CD->isInheritingConstructor()) {
5774 auto *Inherited = CD->getInheritedConstructor().getConstructor();
5775 if (!Inherited->isConstexpr())
5776 DiagDecl = CD = Inherited;
5777 }
5778
5779 // FIXME: If DiagDecl is an implicitly-declared special member function
5780 // or an inheriting constructor, we should be much more explicit about why
5781 // it's not constexpr.
5782 if (CD && CD->isInheritingConstructor())
5783 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5784 << CD->getInheritedConstructor().getConstructor()->getParent();
5785 else
5786 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5787 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5788 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5789 } else {
5790 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5791 }
5792 return false;
5793}
5794
5795namespace {
5796struct CheckDynamicTypeHandler {
5797 AccessKinds AccessKind;
5798 typedef bool result_type;
5799 bool failed() { return false; }
5800 bool found(APValue &Subobj, QualType SubobjType) { return true; }
5801 bool found(APSInt &Value, QualType SubobjType) { return true; }
5802 bool found(APFloat &Value, QualType SubobjType) { return true; }
5803};
5804} // end anonymous namespace
5805
5806/// Check that we can access the notional vptr of an object / determine its
5807/// dynamic type.
5808static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5809 AccessKinds AK, bool Polymorphic) {
5810 if (This.Designator.Invalid)
5811 return false;
5812
5813 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5814
5815 if (!Obj)
5816 return false;
5817
5818 if (!Obj.Value) {
5819 // The object is not usable in constant expressions, so we can't inspect
5820 // its value to see if it's in-lifetime or what the active union members
5821 // are. We can still check for a one-past-the-end lvalue.
5822 if (This.Designator.isOnePastTheEnd() ||
5823 This.Designator.isMostDerivedAnUnsizedArray()) {
5824 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5825 ? diag::note_constexpr_access_past_end
5826 : diag::note_constexpr_access_unsized_array)
5827 << AK;
5828 return false;
5829 } else if (Polymorphic) {
5830 // Conservatively refuse to perform a polymorphic operation if we would
5831 // not be able to read a notional 'vptr' value.
5832 APValue Val;
5833 This.moveInto(Val);
5834 QualType StarThisType =
5835 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5836 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5837 << AK << Val.getAsString(Info.Ctx, StarThisType);
5838 return false;
5839 }
5840 return true;
5841 }
5842
5843 CheckDynamicTypeHandler Handler{AK};
5844 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5845}
5846
5847/// Check that the pointee of the 'this' pointer in a member function call is
5848/// either within its lifetime or in its period of construction or destruction.
5849static bool
5851 const LValue &This,
5852 const CXXMethodDecl *NamedMember) {
5853 return checkDynamicType(
5854 Info, E, This,
5855 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5856}
5857
5859 /// The dynamic class type of the object.
5861 /// The corresponding path length in the lvalue.
5862 unsigned PathLength;
5863};
5864
5865static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5866 unsigned PathLength) {
5867 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5868 Designator.Entries.size() && "invalid path length");
5869 return (PathLength == Designator.MostDerivedPathLength)
5870 ? Designator.MostDerivedType->getAsCXXRecordDecl()
5871 : getAsBaseClass(Designator.Entries[PathLength - 1]);
5872}
5873
5874/// Determine the dynamic type of an object.
5875static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
5876 const Expr *E,
5877 LValue &This,
5878 AccessKinds AK) {
5879 // If we don't have an lvalue denoting an object of class type, there is no
5880 // meaningful dynamic type. (We consider objects of non-class type to have no
5881 // dynamic type.)
5882 if (!checkDynamicType(Info, E, This, AK, true))
5883 return std::nullopt;
5884
5885 // Refuse to compute a dynamic type in the presence of virtual bases. This
5886 // shouldn't happen other than in constant-folding situations, since literal
5887 // types can't have virtual bases.
5888 //
5889 // Note that consumers of DynamicType assume that the type has no virtual
5890 // bases, and will need modifications if this restriction is relaxed.
5891 const CXXRecordDecl *Class =
5892 This.Designator.MostDerivedType->getAsCXXRecordDecl();
5893 if (!Class || Class->getNumVBases()) {
5894 Info.FFDiag(E);
5895 return std::nullopt;
5896 }
5897
5898 // FIXME: For very deep class hierarchies, it might be beneficial to use a
5899 // binary search here instead. But the overwhelmingly common case is that
5900 // we're not in the middle of a constructor, so it probably doesn't matter
5901 // in practice.
5902 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5903 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5904 PathLength <= Path.size(); ++PathLength) {
5905 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5906 Path.slice(0, PathLength))) {
5907 case ConstructionPhase::Bases:
5908 case ConstructionPhase::DestroyingBases:
5909 // We're constructing or destroying a base class. This is not the dynamic
5910 // type.
5911 break;
5912
5913 case ConstructionPhase::None:
5914 case ConstructionPhase::AfterBases:
5915 case ConstructionPhase::AfterFields:
5916 case ConstructionPhase::Destroying:
5917 // We've finished constructing the base classes and not yet started
5918 // destroying them again, so this is the dynamic type.
5919 return DynamicType{getBaseClassType(This.Designator, PathLength),
5920 PathLength};
5921 }
5922 }
5923
5924 // CWG issue 1517: we're constructing a base class of the object described by
5925 // 'This', so that object has not yet begun its period of construction and
5926 // any polymorphic operation on it results in undefined behavior.
5927 Info.FFDiag(E);
5928 return std::nullopt;
5929}
5930
5931/// Perform virtual dispatch.
5933 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5934 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5935 std::optional<DynamicType> DynType = ComputeDynamicType(
5936 Info, E, This,
5937 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5938 if (!DynType)
5939 return nullptr;
5940
5941 // Find the final overrider. It must be declared in one of the classes on the
5942 // path from the dynamic type to the static type.
5943 // FIXME: If we ever allow literal types to have virtual base classes, that
5944 // won't be true.
5945 const CXXMethodDecl *Callee = Found;
5946 unsigned PathLength = DynType->PathLength;
5947 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5948 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5949 const CXXMethodDecl *Overrider =
5950 Found->getCorrespondingMethodDeclaredInClass(Class, false);
5951 if (Overrider) {
5952 Callee = Overrider;
5953 break;
5954 }
5955 }
5956
5957 // C++2a [class.abstract]p6:
5958 // the effect of making a virtual call to a pure virtual function [...] is
5959 // undefined
5960 if (Callee->isPureVirtual()) {
5961 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5962 Info.Note(Callee->getLocation(), diag::note_declared_at);
5963 return nullptr;
5964 }
5965
5966 // If necessary, walk the rest of the path to determine the sequence of
5967 // covariant adjustment steps to apply.
5968 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5969 Found->getReturnType())) {
5970 CovariantAdjustmentPath.push_back(Callee->getReturnType());
5971 for (unsigned CovariantPathLength = PathLength + 1;
5972 CovariantPathLength != This.Designator.Entries.size();
5973 ++CovariantPathLength) {
5974 const CXXRecordDecl *NextClass =
5975 getBaseClassType(This.Designator, CovariantPathLength);
5976 const CXXMethodDecl *Next =
5977 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5978 if (Next && !Info.Ctx.hasSameUnqualifiedType(
5979 Next->getReturnType(), CovariantAdjustmentPath.back()))
5980 CovariantAdjustmentPath.push_back(Next->getReturnType());
5981 }
5982 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5983 CovariantAdjustmentPath.back()))
5984 CovariantAdjustmentPath.push_back(Found->getReturnType());
5985 }
5986
5987 // Perform 'this' adjustment.
5988 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5989 return nullptr;
5990
5991 return Callee;
5992}
5993
5994/// Perform the adjustment from a value returned by a virtual function to
5995/// a value of the statically expected type, which may be a pointer or
5996/// reference to a base class of the returned type.
5997static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5998 APValue &Result,
6000 assert(Result.isLValue() &&
6001 "unexpected kind of APValue for covariant return");
6002 if (Result.isNullPointer())
6003 return true;
6004
6005 LValue LVal;
6006 LVal.setFrom(Info.Ctx, Result);
6007
6008 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6009 for (unsigned I = 1; I != Path.size(); ++I) {
6010 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6011 assert(OldClass && NewClass && "unexpected kind of covariant return");
6012 if (OldClass != NewClass &&
6013 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6014 return false;
6015 OldClass = NewClass;
6016 }
6017
6018 LVal.moveInto(Result);
6019 return true;
6020}
6021
6022/// Determine whether \p Base, which is known to be a direct base class of
6023/// \p Derived, is a public base class.
6024static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6025 const CXXRecordDecl *Base) {
6026 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6027 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6028 if (BaseClass && declaresSameEntity(BaseClass, Base))
6029 return BaseSpec.getAccessSpecifier() == AS_public;
6030 }
6031 llvm_unreachable("Base is not a direct base of Derived");
6032}
6033
6034/// Apply the given dynamic cast operation on the provided lvalue.
6035///
6036/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6037/// to find a suitable target subobject.
6038static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6039 LValue &Ptr) {
6040 // We can't do anything with a non-symbolic pointer value.
6041 SubobjectDesignator &D = Ptr.Designator;
6042 if (D.Invalid)
6043 return false;
6044
6045 // C++ [expr.dynamic.cast]p6:
6046 // If v is a null pointer value, the result is a null pointer value.
6047 if (Ptr.isNullPointer() && !E->isGLValue())
6048 return true;
6049
6050 // For all the other cases, we need the pointer to point to an object within
6051 // its lifetime / period of construction / destruction, and we need to know
6052 // its dynamic type.
6053 std::optional<DynamicType> DynType =
6054 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6055 if (!DynType)
6056 return false;
6057
6058 // C++ [expr.dynamic.cast]p7:
6059 // If T is "pointer to cv void", then the result is a pointer to the most
6060 // derived object
6061 if (E->getType()->isVoidPointerType())
6062 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6063
6064 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
6065 assert(C && "dynamic_cast target is not void pointer nor class");
6066 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
6067
6068 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6069 // C++ [expr.dynamic.cast]p9:
6070 if (!E->isGLValue()) {
6071 // The value of a failed cast to pointer type is the null pointer value
6072 // of the required result type.
6073 Ptr.setNull(Info.Ctx, E->getType());
6074 return true;
6075 }
6076
6077 // A failed cast to reference type throws [...] std::bad_cast.
6078 unsigned DiagKind;
6079 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6080 DynType->Type->isDerivedFrom(C)))
6081 DiagKind = 0;
6082 else if (!Paths || Paths->begin() == Paths->end())
6083 DiagKind = 1;
6084 else if (Paths->isAmbiguous(CQT))
6085 DiagKind = 2;
6086 else {
6087 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6088 DiagKind = 3;
6089 }
6090 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6091 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6092 << Info.Ctx.getRecordType(DynType->Type)
6094 return false;
6095 };
6096
6097 // Runtime check, phase 1:
6098 // Walk from the base subobject towards the derived object looking for the
6099 // target type.
6100 for (int PathLength = Ptr.Designator.Entries.size();
6101 PathLength >= (int)DynType->PathLength; --PathLength) {
6102 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6104 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6105 // We can only walk across public inheritance edges.
6106 if (PathLength > (int)DynType->PathLength &&
6107 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6108 Class))
6109 return RuntimeCheckFailed(nullptr);
6110 }
6111
6112 // Runtime check, phase 2:
6113 // Search the dynamic type for an unambiguous public base of type C.
6114 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6115 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6116 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6117 Paths.front().Access == AS_public) {
6118 // Downcast to the dynamic type...
6119 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6120 return false;
6121 // ... then upcast to the chosen base class subobject.
6122 for (CXXBasePathElement &Elem : Paths.front())
6123 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6124 return false;
6125 return true;
6126 }
6127
6128 // Otherwise, the runtime check fails.
6129 return RuntimeCheckFailed(&Paths);
6130}
6131
6132namespace {
6133struct StartLifetimeOfUnionMemberHandler {
6134 EvalInfo &Info;
6135 const Expr *LHSExpr;
6136 const FieldDecl *Field;
6137 bool DuringInit;
6138 bool Failed = false;
6139 static const AccessKinds AccessKind = AK_Assign;
6140
6141 typedef bool result_type;
6142 bool failed() { return Failed; }
6143 bool found(APValue &Subobj, QualType SubobjType) {
6144 // We are supposed to perform no initialization but begin the lifetime of
6145 // the object. We interpret that as meaning to do what default
6146 // initialization of the object would do if all constructors involved were
6147 // trivial:
6148 // * All base, non-variant member, and array element subobjects' lifetimes
6149 // begin
6150 // * No variant members' lifetimes begin
6151 // * All scalar subobjects whose lifetimes begin have indeterminate values
6152 assert(SubobjType->isUnionType());
6153 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6154 // This union member is already active. If it's also in-lifetime, there's
6155 // nothing to do.
6156 if (Subobj.getUnionValue().hasValue())
6157 return true;
6158 } else if (DuringInit) {
6159 // We're currently in the process of initializing a different union
6160 // member. If we carried on, that initialization would attempt to
6161 // store to an inactive union member, resulting in undefined behavior.
6162 Info.FFDiag(LHSExpr,
6163 diag::note_constexpr_union_member_change_during_init);
6164 return false;
6165 }
6166 APValue Result;
6167 Failed = !handleDefaultInitValue(Field->getType(), Result);
6168 Subobj.setUnion(Field, Result);
6169 return true;
6170 }
6171 bool found(APSInt &Value, QualType SubobjType) {
6172 llvm_unreachable("wrong value kind for union object");
6173 }
6174 bool found(APFloat &Value, QualType SubobjType) {
6175 llvm_unreachable("wrong value kind for union object");
6176 }
6177};
6178} // end anonymous namespace
6179
6180const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6181
6182/// Handle a builtin simple-assignment or a call to a trivial assignment
6183/// operator whose left-hand side might involve a union member access. If it
6184/// does, implicitly start the lifetime of any accessed union elements per
6185/// C++20 [class.union]5.
6186static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6187 const Expr *LHSExpr,
6188 const LValue &LHS) {
6189 if (LHS.InvalidBase || LHS.Designator.Invalid)
6190 return false;
6191
6193 // C++ [class.union]p5:
6194 // define the set S(E) of subexpressions of E as follows:
6195 unsigned PathLength = LHS.Designator.Entries.size();
6196 for (const Expr *E = LHSExpr; E != nullptr;) {
6197 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6198 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6199 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6200 // Note that we can't implicitly start the lifetime of a reference,
6201 // so we don't need to proceed any further if we reach one.
6202 if (!FD || FD->getType()->isReferenceType())
6203 break;
6204
6205 // ... and also contains A.B if B names a union member ...
6206 if (FD->getParent()->isUnion()) {
6207 // ... of a non-class, non-array type, or of a class type with a
6208 // trivial default constructor that is not deleted, or an array of
6209 // such types.
6210 auto *RD =
6211 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6212 if (!RD || RD->hasTrivialDefaultConstructor())
6213 UnionPathLengths.push_back({PathLength - 1, FD});
6214 }
6215
6216 E = ME->getBase();
6217 --PathLength;
6218 assert(declaresSameEntity(FD,
6219 LHS.Designator.Entries[PathLength]
6220 .getAsBaseOrMember().getPointer()));
6221
6222 // -- If E is of the form A[B] and is interpreted as a built-in array
6223 // subscripting operator, S(E) is [S(the array operand, if any)].
6224 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6225 // Step over an ArrayToPointerDecay implicit cast.
6226 auto *Base = ASE->getBase()->IgnoreImplicit();
6227 if (!Base->getType()->isArrayType())
6228 break;
6229
6230 E = Base;
6231 --PathLength;
6232
6233 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6234 // Step over a derived-to-base conversion.
6235 E = ICE->getSubExpr();
6236 if (ICE->getCastKind() == CK_NoOp)
6237 continue;
6238 if (ICE->getCastKind() != CK_DerivedToBase &&
6239 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6240 break;
6241 // Walk path backwards as we walk up from the base to the derived class.
6242 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6243 if (Elt->isVirtual()) {
6244 // A class with virtual base classes never has a trivial default
6245 // constructor, so S(E) is empty in this case.
6246 E = nullptr;
6247 break;
6248 }
6249
6250 --PathLength;
6251 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6252 LHS.Designator.Entries[PathLength]
6253 .getAsBaseOrMember().getPointer()));
6254 }
6255
6256 // -- Otherwise, S(E) is empty.
6257 } else {
6258 break;
6259 }
6260 }
6261
6262 // Common case: no unions' lifetimes are started.
6263 if (UnionPathLengths.empty())
6264 return true;
6265
6266 // if modification of X [would access an inactive union member], an object
6267 // of the type of X is implicitly created
6268 CompleteObject Obj =
6269 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6270 if (!Obj)
6271 return false;
6272 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6273 llvm::reverse(UnionPathLengths)) {
6274 // Form a designator for the union object.
6275 SubobjectDesignator D = LHS.Designator;
6276 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6277
6278 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6279 ConstructionPhase::AfterBases;
6280 StartLifetimeOfUnionMemberHandler StartLifetime{
6281 Info, LHSExpr, LengthAndField.second, DuringInit};
6282 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6283 return false;
6284 }
6285
6286 return true;
6287}
6288
6289static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6290 CallRef Call, EvalInfo &Info,
6291 bool NonNull = false) {
6292 LValue LV;
6293 // Create the parameter slot and register its destruction. For a vararg
6294 // argument, create a temporary.
6295 // FIXME: For calling conventions that destroy parameters in the callee,
6296 // should we consider performing destruction when the function returns
6297 // instead?
6298 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6299 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6300 ScopeKind::Call, LV);
6301 if (!EvaluateInPlace(V, Info, LV, Arg))
6302 return false;
6303
6304 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6305 // undefined behavior, so is non-constant.
6306 if (NonNull && V.isLValue() && V.isNullPointer()) {
6307 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6308 return false;
6309 }
6310
6311 return true;
6312}
6313
6314/// Evaluate the arguments to a function call.
6315static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6316 EvalInfo &Info, const FunctionDecl *Callee,
6317 bool RightToLeft = false) {
6318 bool Success = true;
6319 llvm::SmallBitVector ForbiddenNullArgs;
6320 if (Callee->hasAttr<NonNullAttr>()) {
6321 ForbiddenNullArgs.resize(Args.size());
6322 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6323 if (!Attr->args_size()) {
6324 ForbiddenNullArgs.set();
6325 break;
6326 } else
6327 for (auto Idx : Attr->args()) {
6328 unsigned ASTIdx = Idx.getASTIndex();
6329 if (ASTIdx >= Args.size())
6330 continue;
6331 ForbiddenNullArgs[ASTIdx] = true;
6332 }
6333 }
6334 }
6335 for (unsigned I = 0; I < Args.size(); I++) {
6336 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6337 const ParmVarDecl *PVD =
6338 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6339 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6340 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6341 // If we're checking for a potential constant expression, evaluate all
6342 // initializers even if some of them fail.
6343 if (!Info.noteFailure())
6344 return false;
6345 Success = false;
6346 }
6347 }
6348 return Success;
6349}
6350
6351/// Perform a trivial copy from Param, which is the parameter of a copy or move
6352/// constructor or assignment operator.
6353static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6354 const Expr *E, APValue &Result,
6355 bool CopyObjectRepresentation) {
6356 // Find the reference argument.
6357 CallStackFrame *Frame = Info.CurrentCall;
6358 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6359 if (!RefValue) {
6360 Info.FFDiag(E);
6361 return false;
6362 }
6363
6364 // Copy out the contents of the RHS object.
6365 LValue RefLValue;
6366 RefLValue.setFrom(Info.Ctx, *RefValue);
6368 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6369 CopyObjectRepresentation);
6370}
6371
6372/// Evaluate a function call.
6374 const FunctionDecl *Callee, const LValue *This,
6375 const Expr *E, ArrayRef<const Expr *> Args,
6376 CallRef Call, const Stmt *Body, EvalInfo &Info,
6377 APValue &Result, const LValue *ResultSlot) {
6378 if (!Info.CheckCallLimit(CallLoc))
6379 return false;
6380
6381 CallStackFrame Frame(Info, E->getSourceRange(), Callee, This, E, Call);
6382
6383 // For a trivial copy or move assignment, perform an APValue copy. This is
6384 // essential for unions, where the operations performed by the assignment
6385 // operator cannot be represented as statements.
6386 //
6387 // Skip this for non-union classes with no fields; in that case, the defaulted
6388 // copy/move does not actually read the object.
6389 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6390 if (MD && MD->isDefaulted() &&
6391 (MD->getParent()->isUnion() ||
6392 (MD->isTrivial() &&
6394 assert(This &&
6396 APValue RHSValue;
6397 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6398 MD->getParent()->isUnion()))
6399 return false;
6400 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6401 RHSValue))
6402 return false;
6403 This->moveInto(Result);
6404 return true;
6405 } else if (MD && isLambdaCallOperator(MD)) {
6406 // We're in a lambda; determine the lambda capture field maps unless we're
6407 // just constexpr checking a lambda's call operator. constexpr checking is
6408 // done before the captures have been added to the closure object (unless
6409 // we're inferring constexpr-ness), so we don't have access to them in this
6410 // case. But since we don't need the captures to constexpr check, we can
6411 // just ignore them.
6412 if (!Info.checkingPotentialConstantExpression())
6413 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6414 Frame.LambdaThisCaptureField);
6415 }
6416
6417 StmtResult Ret = {Result, ResultSlot};
6418 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6419 if (ESR == ESR_Succeeded) {
6420 if (Callee->getReturnType()->isVoidType())
6421 return true;
6422 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6423 }
6424 return ESR == ESR_Returned;
6425}
6426
6427/// Evaluate a constructor call.
6428static bool HandleConstructorCall(const Expr *E, const LValue &This,
6429 CallRef Call,
6431 EvalInfo &Info, APValue &Result) {
6432 SourceLocation CallLoc = E->getExprLoc();
6433 if (!Info.CheckCallLimit(CallLoc))
6434 return false;
6435
6436 const CXXRecordDecl *RD = Definition->getParent();
6437 if (RD->getNumVBases()) {
6438 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6439 return false;
6440 }
6441
6442 EvalInfo::EvaluatingConstructorRAII EvalObj(
6443 Info,
6444 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6445 RD->getNumBases());
6446 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
6447
6448 // FIXME: Creating an APValue just to hold a nonexistent return value is
6449 // wasteful.
6450 APValue RetVal;
6451 StmtResult Ret = {RetVal, nullptr};
6452
6453 // If it's a delegating constructor, delegate.
6454 if (Definition->isDelegatingConstructor()) {
6456 if ((*I)->getInit()->isValueDependent()) {
6457 if (!EvaluateDependentExpr((*I)->getInit(), Info))
6458 return false;
6459 } else {
6460 FullExpressionRAII InitScope(Info);
6461 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6462 !InitScope.destroy())
6463 return false;
6464 }
6465 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6466 }
6467
6468 // For a trivial copy or move constructor, perform an APValue copy. This is
6469 // essential for unions (or classes with anonymous union members), where the
6470 // operations performed by the constructor cannot be represented by
6471 // ctor-initializers.
6472 //
6473 // Skip this for empty non-union classes; we should not perform an
6474 // lvalue-to-rvalue conversion on them because their copy constructor does not
6475 // actually read them.
6476 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6477 (Definition->getParent()->isUnion() ||
6478 (Definition->isTrivial() &&
6480 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6481 Definition->getParent()->isUnion());
6482 }
6483
6484 // Reserve space for the struct members.
6485 if (!Result.hasValue()) {
6486 if (!RD->isUnion())
6487 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6488 std::distance(RD->field_begin(), RD->field_end()));
6489 else
6490 // A union starts with no active member.
6491 Result = APValue((const FieldDecl*)nullptr);
6492 }
6493
6494 if (RD->isInvalidDecl()) return false;
6495 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6496
6497 // A scope for temporaries lifetime-extended by reference members.
6498 BlockScopeRAII LifetimeExtendedScope(Info);
6499
6500 bool Success = true;
6501 unsigned BasesSeen = 0;
6502#ifndef NDEBUG
6504#endif
6506 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6507 // We might be initializing the same field again if this is an indirect
6508 // field initialization.
6509 if (FieldIt == RD->field_end() ||
6510 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6511 assert(Indirect && "fields out of order?");
6512 return;
6513 }
6514
6515 // Default-initialize any fields with no explicit initializer.
6516 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6517 assert(FieldIt != RD->field_end() && "missing field?");
6518 if (!FieldIt->isUnnamedBitField())
6520 FieldIt->getType(),
6521 Result.getStructField(FieldIt->getFieldIndex()));
6522 }
6523 ++FieldIt;
6524 };
6525 for (const auto *I : Definition->inits()) {
6526 LValue Subobject = This;
6527 LValue SubobjectParent = This;
6528 APValue *Value = &Result;
6529
6530 // Determine the subobject to initialize.
6531 FieldDecl *FD = nullptr;
6532 if (I->isBaseInitializer()) {
6533 QualType BaseType(I->getBaseClass(), 0);
6534#ifndef NDEBUG
6535 // Non-virtual base classes are initialized in the order in the class
6536 // definition. We have already checked for virtual base classes.
6537 assert(!BaseIt->isVirtual() && "virtual base for literal type");
6538 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
6539 "base class initializers not in expected order");
6540 ++BaseIt;
6541#endif
6542 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6543 BaseType->getAsCXXRecordDecl(), &Layout))
6544 return false;
6545 Value = &Result.getStructBase(BasesSeen++);
6546 } else if ((FD = I->getMember())) {
6547 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6548 return false;
6549 if (RD->isUnion()) {
6550 Result = APValue(FD);
6551 Value = &Result.getUnionValue();
6552 } else {
6553 SkipToField(FD, false);
6554 Value = &Result.getStructField(FD->getFieldIndex());
6555 }
6556 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6557 // Walk the indirect field decl's chain to find the object to initialize,
6558 // and make sure we've initialized every step along it.
6559 auto IndirectFieldChain = IFD->chain();
6560 for (auto *C : IndirectFieldChain) {
6561 FD = cast<FieldDecl>(C);
6562 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6563 // Switch the union field if it differs. This happens if we had
6564 // preceding zero-initialization, and we're now initializing a union
6565 // subobject other than the first.
6566 // FIXME: In this case, the values of the other subobjects are
6567 // specified, since zero-initialization sets all padding bits to zero.
6568 if (!Value->hasValue() ||
6569 (Value->isUnion() && Value->getUnionField() != FD)) {
6570 if (CD->isUnion())
6571 *Value = APValue(FD);
6572 else
6573 // FIXME: This immediately starts the lifetime of all members of
6574 // an anonymous struct. It would be preferable to strictly start
6575 // member lifetime in initialization order.
6576 Success &=
6577 handleDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6578 }
6579 // Store Subobject as its parent before updating it for the last element
6580 // in the chain.
6581 if (C == IndirectFieldChain.back())
6582 SubobjectParent = Subobject;
6583 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6584 return false;
6585 if (CD->isUnion())
6586 Value = &Value->getUnionValue();
6587 else {
6588 if (C == IndirectFieldChain.front() && !RD->isUnion())
6589 SkipToField(FD, true);
6590 Value = &Value->getStructField(FD->getFieldIndex());
6591 }
6592 }
6593 } else {
6594 llvm_unreachable("unknown base initializer kind");
6595 }
6596
6597 // Need to override This for implicit field initializers as in this case
6598 // This refers to innermost anonymous struct/union containing initializer,
6599 // not to currently constructed class.
6600 const Expr *Init = I->getInit();
6601 if (Init->isValueDependent()) {
6602 if (!EvaluateDependentExpr(Init, Info))
6603 return false;
6604 } else {
6605 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6606 isa<CXXDefaultInitExpr>(Init));
6607 FullExpressionRAII InitScope(Info);
6608 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6609 (FD && FD->isBitField() &&
6610 !truncateBitfieldValue(Info, Init, *Value, FD))) {
6611 // If we're checking for a potential constant expression, evaluate all
6612 // initializers even if some of them fail.
6613 if (!Info.noteFailure())
6614 return false;
6615 Success = false;
6616 }
6617 }
6618
6619 // This is the point at which the dynamic type of the object becomes this
6620 // class type.
6621 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6622 EvalObj.finishedConstructingBases();
6623 }
6624
6625 // Default-initialize any remaining fields.
6626 if (!RD->isUnion()) {
6627 for (; FieldIt != RD->field_end(); ++FieldIt) {
6628 if (!FieldIt->isUnnamedBitField())
6630 FieldIt->getType(),
6631 Result.getStructField(FieldIt->getFieldIndex()));
6632 }
6633 }
6634
6635 EvalObj.finishedConstructingFields();
6636
6637 return Success &&
6638 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6639 LifetimeExtendedScope.destroy();
6640}
6641
6642static bool HandleConstructorCall(const Expr *E, const LValue &This,
6645 EvalInfo &Info, APValue &Result) {
6646 CallScopeRAII CallScope(Info);
6647 CallRef Call = Info.CurrentCall->createCall(Definition);
6648 if (!EvaluateArgs(Args, Call, Info, Definition))
6649 return false;
6650
6651 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6652 CallScope.destroy();
6653}
6654
6655static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
6656 const LValue &This, APValue &Value,
6657 QualType T) {
6658 // Objects can only be destroyed while they're within their lifetimes.
6659 // FIXME: We have no representation for whether an object of type nullptr_t
6660 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6661 // as indeterminate instead?
6662 if (Value.isAbsent() && !T->isNullPtrType()) {
6663 APValue Printable;
6664 This.moveInto(Printable);
6665 Info.FFDiag(CallRange.getBegin(),
6666 diag::note_constexpr_destroy_out_of_lifetime)
6667 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6668 return false;
6669 }
6670
6671 // Invent an expression for location purposes.
6672 // FIXME: We shouldn't need to do this.
6673 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
6674
6675 // For arrays, destroy elements right-to-left.
6676 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6677 uint64_t Size = CAT->getZExtSize();
6678 QualType ElemT = CAT->getElementType();
6679
6680 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
6681 return false;
6682
6683 LValue ElemLV = This;
6684 ElemLV.addArray(Info, &LocE, CAT);
6685 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6686 return false;
6687
6688 // Ensure that we have actual array elements available to destroy; the
6689 // destructors might mutate the value, so we can't run them on the array
6690 // filler.
6691 if (Size && Size > Value.getArrayInitializedElts())
6692 expandArray(Value, Value.getArraySize() - 1);
6693
6694 for (; Size != 0; --Size) {
6695 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6696 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6697 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
6698 return false;
6699 }
6700
6701 // End the lifetime of this array now.
6702 Value = APValue();
6703 return true;
6704 }
6705
6706 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6707 if (!RD) {
6708 if (T.isDestructedType()) {
6709 Info.FFDiag(CallRange.getBegin(),
6710 diag::note_constexpr_unsupported_destruction)
6711 << T;
6712 return false;
6713 }
6714
6715 Value = APValue();
6716 return true;
6717 }
6718
6719 if (RD->getNumVBases()) {
6720 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
6721 return false;
6722 }
6723
6724 const CXXDestructorDecl *DD = RD->getDestructor();
6725 if (!DD && !RD->hasTrivialDestructor()) {
6726 Info.FFDiag(CallRange.getBegin());
6727 return false;
6728 }
6729
6730 if (!DD || DD->isTrivial() ||
6731 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6732 // A trivial destructor just ends the lifetime of the object. Check for
6733 // this case before checking for a body, because we might not bother
6734 // building a body for a trivial destructor. Note that it doesn't matter
6735 // whether the destructor is constexpr in this case; all trivial
6736 // destructors are constexpr.
6737 //
6738 // If an anonymous union would be destroyed, some enclosing destructor must
6739 // have been explicitly defined, and the anonymous union destruction should
6740 // have no effect.
6741 Value = APValue();
6742 return true;
6743 }
6744
6745 if (!Info.CheckCallLimit(CallRange.getBegin()))
6746 return false;
6747
6748 const FunctionDecl *Definition = nullptr;
6749 const Stmt *Body = DD->getBody(Definition);
6750
6751 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
6752 return false;
6753
6754 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
6755 CallRef());
6756
6757 // We're now in the period of destruction of this object.
6758 unsigned BasesLeft = RD->getNumBases();
6759 EvalInfo::EvaluatingDestructorRAII EvalObj(
6760 Info,
6761 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6762 if (!EvalObj.DidInsert) {
6763 // C++2a [class.dtor]p19:
6764 // the behavior is undefined if the destructor is invoked for an object
6765 // whose lifetime has ended
6766 // (Note that formally the lifetime ends when the period of destruction
6767 // begins, even though certain uses of the object remain valid until the
6768 // period of destruction ends.)
6769 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
6770 return false;
6771 }
6772
6773 // FIXME: Creating an APValue just to hold a nonexistent return value is
6774 // wasteful.
6775 APValue RetVal;
6776 StmtResult Ret = {RetVal, nullptr};
6777 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6778 return false;
6779
6780 // A union destructor does not implicitly destroy its members.
6781 if (RD->isUnion())
6782 return true;
6783
6784 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6785
6786 // We don't have a good way to iterate fields in reverse, so collect all the
6787 // fields first and then walk them backwards.
6788 SmallVector<FieldDecl*, 16> Fields(RD->fields());
6789 for (const FieldDecl *FD : llvm::reverse(Fields)) {
6790 if (FD->isUnnamedBitField())
6791 continue;
6792
6793 LValue Subobject = This;
6794 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6795 return false;
6796
6797 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6798 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
6799 FD->getType()))
6800 return false;
6801 }
6802
6803 if (BasesLeft != 0)
6804 EvalObj.startedDestroyingBases();
6805
6806 // Destroy base classes in reverse order.
6807 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6808 --BasesLeft;
6809
6810 QualType BaseType = Base.getType();
6811 LValue Subobject = This;
6812 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6813 BaseType->getAsCXXRecordDecl(), &Layout))
6814 return false;
6815
6816 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6817 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
6818 BaseType))
6819 return false;
6820 }
6821 assert(BasesLeft == 0 && "NumBases was wrong?");
6822
6823 // The period of destruction ends now. The object is gone.
6824 Value = APValue();
6825 return true;
6826}
6827
6828namespace {
6829struct DestroyObjectHandler {
6830 EvalInfo &Info;
6831 const Expr *E;
6832 const LValue &This;
6833 const AccessKinds AccessKind;
6834
6835 typedef bool result_type;
6836 bool failed() { return false; }
6837 bool found(APValue &Subobj, QualType SubobjType) {
6838 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
6839 SubobjType);
6840 }
6841 bool found(APSInt &Value, QualType SubobjType) {
6842 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6843 return false;
6844 }
6845 bool found(APFloat &Value, QualType SubobjType) {
6846 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6847 return false;
6848 }
6849};
6850}
6851
6852/// Perform a destructor or pseudo-destructor call on the given object, which
6853/// might in general not be a complete object.
6854static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6855 const LValue &This, QualType ThisType) {
6856 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6857 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6858 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6859}
6860
6861/// Destroy and end the lifetime of the given complete object.
6862static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6864 QualType T) {
6865 // If we've had an unmodeled side-effect, we can't rely on mutable state
6866 // (such as the object we're about to destroy) being correct.
6867 if (Info.EvalStatus.HasSideEffects)
6868 return false;
6869
6870 LValue LV;
6871 LV.set({LVBase});
6872 return HandleDestructionImpl(Info, Loc, LV, Value, T);
6873}
6874
6875/// Perform a call to 'operator new' or to `__builtin_operator_new'.
6876static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6877 LValue &Result) {
6878 if (Info.checkingPotentialConstantExpression() ||
6879 Info.SpeculativeEvaluationDepth)
6880 return false;
6881
6882 // This is permitted only within a call to std::allocator<T>::allocate.
6883 auto Caller = Info.getStdAllocatorCaller("allocate");
6884 if (!Caller) {
6885 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6886 ? diag::note_constexpr_new_untyped
6887 : diag::note_constexpr_new);
6888 return false;
6889 }
6890
6891 QualType ElemType = Caller.ElemType;
6892 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6893 Info.FFDiag(E->getExprLoc(),
6894 diag::note_constexpr_new_not_complete_object_type)
6895 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6896 return false;
6897 }
6898
6899 APSInt ByteSize;
6900 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6901 return false;
6902 bool IsNothrow = false;
6903 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6904 EvaluateIgnoredValue(Info, E->getArg(I));
6905 IsNothrow |= E->getType()->isNothrowT();
6906 }
6907
6908 CharUnits ElemSize;
6909 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6910 return false;
6911 APInt Size, Remainder;
6912 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6913 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6914 if (Remainder != 0) {
6915 // This likely indicates a bug in the implementation of 'std::allocator'.
6916 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6917 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6918 return false;
6919 }
6920
6921 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
6922 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
6923 if (IsNothrow) {
6924 Result.setNull(Info.Ctx, E->getType());
6925 return true;
6926 }
6927 return false;
6928 }
6929
6930 QualType AllocType = Info.Ctx.getConstantArrayType(
6931 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
6932 APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6933 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6934 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6935 return true;
6936}
6937
6939 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6940 if (CXXDestructorDecl *DD = RD->getDestructor())
6941 return DD->isVirtual();
6942 return false;
6943}
6944
6946 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6947 if (CXXDestructorDecl *DD = RD->getDestructor())
6948 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6949 return nullptr;
6950}
6951
6952/// Check that the given object is a suitable pointer to a heap allocation that
6953/// still exists and is of the right kind for the purpose of a deletion.
6954///
6955/// On success, returns the heap allocation to deallocate. On failure, produces
6956/// a diagnostic and returns std::nullopt.
6957static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6958 const LValue &Pointer,
6959 DynAlloc::Kind DeallocKind) {
6960 auto PointerAsString = [&] {
6961 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6962 };
6963
6964 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6965 if (!DA) {
6966 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6967 << PointerAsString();
6968 if (Pointer.Base)
6969 NoteLValueLocation(Info, Pointer.Base);
6970 return std::nullopt;
6971 }
6972
6973 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6974 if (!Alloc) {
6975 Info.FFDiag(E, diag::note_constexpr_double_delete);
6976 return std::nullopt;
6977 }
6978
6979 if (DeallocKind != (*Alloc)->getKind()) {
6980 QualType AllocType = Pointer.Base.getDynamicAllocType();
6981 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6982 << DeallocKind << (*Alloc)->getKind() << AllocType;
6983 NoteLValueLocation(Info, Pointer.Base);
6984 return std::nullopt;
6985 }
6986
6987 bool Subobject = false;
6988 if (DeallocKind == DynAlloc::New) {
6989 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6990 Pointer.Designator.isOnePastTheEnd();
6991 } else {
6992 Subobject = Pointer.Designator.Entries.size() != 1 ||
6993 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6994 }
6995 if (Subobject) {
6996 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6997 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6998 return std::nullopt;
6999 }
7000
7001 return Alloc;
7002}
7003
7004// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7005bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7006 if (Info.checkingPotentialConstantExpression() ||
7007 Info.SpeculativeEvaluationDepth)
7008 return false;
7009
7010 // This is permitted only within a call to std::allocator<T>::deallocate.
7011 if (!Info.getStdAllocatorCaller("deallocate")) {
7012 Info.FFDiag(E->getExprLoc());
7013 return true;
7014 }
7015
7016 LValue Pointer;
7017 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7018 return false;
7019 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7020 EvaluateIgnoredValue(Info, E->getArg(I));
7021
7022 if (Pointer.Designator.Invalid)
7023 return false;
7024
7025 // Deleting a null pointer would have no effect, but it's not permitted by
7026 // std::allocator<T>::deallocate's contract.
7027 if (Pointer.isNullPointer()) {
7028 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7029 return true;
7030 }
7031
7032 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7033 return false;
7034
7035 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7036 return true;
7037}
7038
7039//===----------------------------------------------------------------------===//
7040// Generic Evaluation
7041//===----------------------------------------------------------------------===//
7042namespace {
7043
7044class BitCastBuffer {
7045 // FIXME: We're going to need bit-level granularity when we support
7046 // bit-fields.
7047 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7048 // we don't support a host or target where that is the case. Still, we should
7049 // use a more generic type in case we ever do.
7051
7052 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7053 "Need at least 8 bit unsigned char");
7054
7055 bool TargetIsLittleEndian;
7056
7057public:
7058 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7059 : Bytes(Width.getQuantity()),
7060 TargetIsLittleEndian(TargetIsLittleEndian) {}
7061
7062 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7063 SmallVectorImpl<unsigned char> &Output) const {
7064 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7065 // If a byte of an integer is uninitialized, then the whole integer is
7066 // uninitialized.
7067 if (!Bytes[I.getQuantity()])
7068 return false;
7069 Output.push_back(*Bytes[I.getQuantity()]);
7070 }
7071 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7072 std::reverse(Output.begin(), Output.end());
7073 return true;
7074 }
7075
7076 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7077 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7078 std::reverse(Input.begin(), Input.end());
7079
7080 size_t Index = 0;
7081 for (unsigned char Byte : Input) {
7082 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7083 Bytes[Offset.getQuantity() + Index] = Byte;
7084 ++Index;
7085 }
7086 }
7087
7088 size_t size() { return Bytes.size(); }
7089};
7090
7091/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7092/// target would represent the value at runtime.
7093class APValueToBufferConverter {
7094 EvalInfo &Info;
7095 BitCastBuffer Buffer;
7096 const CastExpr *BCE;
7097
7098 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7099 const CastExpr *BCE)
7100 : Info(Info),
7101 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7102 BCE(BCE) {}
7103
7104 bool visit(const APValue &Val, QualType Ty) {
7105 return visit(Val, Ty, CharUnits::fromQuantity(0));
7106 }
7107
7108 // Write out Val with type Ty into Buffer starting at Offset.
7109 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7110 assert((size_t)Offset.getQuantity() <= Buffer.size());
7111
7112 // As a special case, nullptr_t has an indeterminate value.
7113 if (Ty->isNullPtrType())
7114 return true;
7115
7116 // Dig through Src to find the byte at SrcOffset.
7117 switch (Val.getKind()) {
7119 case APValue::None:
7120 return true;
7121
7122 case APValue::Int:
7123 return visitInt(Val.getInt(), Ty, Offset);
7124 case APValue::Float:
7125 return visitFloat(Val.getFloat(), Ty, Offset);
7126 case APValue::Array:
7127 return visitArray(Val, Ty, Offset);
7128 case APValue::Struct:
7129 return visitRecord(Val, Ty, Offset);
7130 case APValue::Vector:
7131 return visitVector(Val, Ty, Offset);
7132
7136 // FIXME: We should support these.
7137
7138 case APValue::Union:
7141 Info.FFDiag(BCE->getBeginLoc(),
7142 diag::note_constexpr_bit_cast_unsupported_type)
7143 << Ty;
7144 return false;
7145 }
7146
7147 case APValue::LValue:
7148 llvm_unreachable("LValue subobject in bit_cast?");
7149 }
7150 llvm_unreachable("Unhandled APValue::ValueKind");
7151 }
7152
7153 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7154 const RecordDecl *RD = Ty->getAsRecordDecl();
7155 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7156
7157 // Visit the base classes.
7158 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7159 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7160 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7161 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7162
7163 if (!visitRecord(Val.getStructBase(I), BS.getType(),
7164 Layout.getBaseClassOffset(BaseDecl) + Offset))
7165 return false;
7166 }
7167 }
7168
7169 // Visit the fields.
7170 unsigned FieldIdx = 0;
7171 for (FieldDecl *FD : RD->fields()) {
7172 if (FD->isBitField()) {
7173 Info.FFDiag(BCE->getBeginLoc(),
7174 diag::note_constexpr_bit_cast_unsupported_bitfield);
7175 return false;
7176 }
7177
7178 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7179
7180 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7181 "only bit-fields can have sub-char alignment");
7182 CharUnits FieldOffset =
7183 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7184 QualType FieldTy = FD->getType();
7185 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7186 return false;
7187 ++FieldIdx;
7188 }
7189
7190 return true;
7191 }
7192
7193 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7194 const auto *CAT =
7195 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7196 if (!CAT)
7197 return false;
7198
7199 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7200 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7201 unsigned ArraySize = Val.getArraySize();
7202 // First, initialize the initialized elements.
7203 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7204 const APValue &SubObj = Val.getArrayInitializedElt(I);
7205 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7206 return false;
7207 }
7208
7209 // Next, initialize the rest of the array using the filler.
7210 if (Val.hasArrayFiller()) {
7211 const APValue &Filler = Val.getArrayFiller();
7212 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7213 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7214 return false;
7215 }
7216 }
7217
7218 return true;
7219 }
7220
7221 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7222 const VectorType *VTy = Ty->castAs<VectorType>();
7223 QualType EltTy = VTy->getElementType();
7224 unsigned NElts = VTy->getNumElements();
7225 unsigned EltSize =
7226 VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);
7227
7228 if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) {
7229 // The vector's size in bits is not a multiple of the target's byte size,
7230 // so its layout is unspecified. For now, we'll simply treat these cases
7231 // as unsupported (this should only be possible with OpenCL bool vectors
7232 // whose element count isn't a multiple of the byte size).
7233 Info.FFDiag(BCE->getBeginLoc(),
7234 diag::note_constexpr_bit_cast_invalid_vector)
7235 << Ty.getCanonicalType() << EltSize << NElts
7236 << Info.Ctx.getCharWidth();
7237 return false;
7238 }
7239
7240 if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(EltTy) ==
7241 &APFloat::x87DoubleExtended()) {
7242 // The layout for x86_fp80 vectors seems to be handled very inconsistently
7243 // by both clang and LLVM, so for now we won't allow bit_casts involving
7244 // it in a constexpr context.
7245 Info.FFDiag(BCE->getBeginLoc(),
7246 diag::note_constexpr_bit_cast_unsupported_type)
7247 << EltTy;
7248 return false;
7249 }
7250
7251 if (VTy->isExtVectorBoolType()) {
7252 // Special handling for OpenCL bool vectors:
7253 // Since these vectors are stored as packed bits, but we can't write
7254 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7255 // together into an appropriately sized APInt and write them all out at
7256 // once. Because we don't accept vectors where NElts * EltSize isn't a
7257 // multiple of the char size, there will be no padding space, so we don't
7258 // have to worry about writing data which should have been left
7259 // uninitialized.
7260 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7261
7262 llvm::APInt Res = llvm::APInt::getZero(NElts);
7263 for (unsigned I = 0; I < NElts; ++I) {
7264 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7265 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7266 "bool vector element must be 1-bit unsigned integer!");
7267
7268 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7269 }
7270
7271 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7272 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7273 Buffer.writeObject(Offset, Bytes);
7274 } else {
7275 // Iterate over each of the elements and write them out to the buffer at
7276 // the appropriate offset.
7277 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7278 for (unsigned I = 0; I < NElts; ++I) {
7279 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7280 return false;
7281 }
7282 }
7283
7284 return true;
7285 }
7286
7287 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7288 APSInt AdjustedVal = Val;
7289 unsigned Width = AdjustedVal.getBitWidth();
7290 if (Ty->isBooleanType()) {
7291 Width = Info.Ctx.getTypeSize(Ty);
7292 AdjustedVal = AdjustedVal.extend(Width);
7293 }
7294
7295 SmallVector<uint8_t, 8> Bytes(Width / 8);
7296 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7297 Buffer.writeObject(Offset, Bytes);
7298 return true;
7299 }
7300
7301 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7302 APSInt AsInt(Val.bitcastToAPInt());
7303 return visitInt(AsInt, Ty, Offset);
7304 }
7305
7306public:
7307 static std::optional<BitCastBuffer>
7308 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7309 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7310 APValueToBufferConverter Converter(Info, DstSize, BCE);
7311 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7312 return std::nullopt;
7313 return Converter.Buffer;
7314 }
7315};
7316
7317/// Write an BitCastBuffer into an APValue.
7318class BufferToAPValueConverter {
7319 EvalInfo &Info;
7320 const BitCastBuffer &Buffer;
7321 const CastExpr *BCE;
7322
7323 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7324 const CastExpr *BCE)
7325 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7326
7327 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7328 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7329 // Ideally this will be unreachable.
7330 std::nullopt_t unsupportedType(QualType Ty) {
7331 Info.FFDiag(BCE->getBeginLoc(),
7332 diag::note_constexpr_bit_cast_unsupported_type)
7333 << Ty;
7334 return std::nullopt;
7335 }
7336
7337 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7338 Info.FFDiag(BCE->getBeginLoc(),
7339 diag::note_constexpr_bit_cast_unrepresentable_value)
7340 << Ty << toString(Val, /*Radix=*/10);
7341 return std::nullopt;
7342 }
7343
7344 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7345 const EnumType *EnumSugar = nullptr) {
7346 if (T->isNullPtrType()) {
7347 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7348 return APValue((Expr *)nullptr,
7349 /*Offset=*/CharUnits::fromQuantity(NullValue),
7350 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7351 }
7352
7353 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7354
7355 // Work around floating point types that contain unused padding bytes. This
7356 // is really just `long double` on x86, which is the only fundamental type
7357 // with padding bytes.
7358 if (T->isRealFloatingType()) {
7359 const llvm::fltSemantics &Semantics =
7360 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7361 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7362 assert(NumBits % 8 == 0);
7363 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7364 if (NumBytes != SizeOf)
7365 SizeOf = NumBytes;
7366 }
7367
7369 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7370 // If this is std::byte or unsigned char, then its okay to store an
7371 // indeterminate value.
7372 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7373 bool IsUChar =
7374 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7375 T->isSpecificBuiltinType(BuiltinType::Char_U));
7376 if (!IsStdByte && !IsUChar) {
7377 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7378 Info.FFDiag(BCE->getExprLoc(),
7379 diag::note_constexpr_bit_cast_indet_dest)
7380 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7381 return std::nullopt;
7382 }
7383
7385 }
7386
7387 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7388 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7389
7391 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7392
7393 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7394 if (IntWidth != Val.getBitWidth()) {
7395 APSInt Truncated = Val.trunc(IntWidth);
7396 if (Truncated.extend(Val.getBitWidth()) != Val)
7397 return unrepresentableValue(QualType(T, 0), Val);
7398 Val = Truncated;
7399 }
7400
7401 return APValue(Val);
7402 }
7403
7404 if (T->isRealFloatingType()) {
7405 const llvm::fltSemantics &Semantics =
7406 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7407 return APValue(APFloat(Semantics, Val));
7408 }
7409
7410 return unsupportedType(QualType(T, 0));
7411 }
7412
7413 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7414 const RecordDecl *RD = RTy->getAsRecordDecl();
7415 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7416
7417 unsigned NumBases = 0;
7418 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7419 NumBases = CXXRD->getNumBases();
7420
7421 APValue ResultVal(APValue::UninitStruct(), NumBases,
7422 std::distance(RD->field_begin(), RD->field_end()));
7423
7424 // Visit the base classes.
7425 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7426 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7427 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7428 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7429
7430 std::optional<APValue> SubObj = visitType(
7431 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7432 if (!SubObj)
7433 return std::nullopt;
7434 ResultVal.getStructBase(I) = *SubObj;
7435 }
7436 }
7437
7438 // Visit the fields.
7439 unsigned FieldIdx = 0;
7440 for (FieldDecl *FD : RD->fields()) {
7441 // FIXME: We don't currently support bit-fields. A lot of the logic for
7442 // this is in CodeGen, so we need to factor it around.
7443 if (FD->isBitField()) {
7444 Info.FFDiag(BCE->getBeginLoc(),
7445 diag::note_constexpr_bit_cast_unsupported_bitfield);
7446 return std::nullopt;
7447 }
7448
7449 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7450 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7451
7452 CharUnits FieldOffset =
7453 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7454 Offset;
7455 QualType FieldTy = FD->getType();
7456 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7457 if (!SubObj)
7458 return std::nullopt;
7459 ResultVal.getStructField(FieldIdx) = *SubObj;
7460 ++FieldIdx;
7461 }
7462
7463 return ResultVal;
7464 }
7465
7466 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7467 QualType RepresentationType = Ty->getDecl()->getIntegerType();
7468 assert(!RepresentationType.isNull() &&
7469 "enum forward decl should be caught by Sema");
7470 const auto *AsBuiltin =
7471 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7472 // Recurse into the underlying type. Treat std::byte transparently as
7473 // unsigned char.
7474 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7475 }
7476
7477 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7478 size_t Size = Ty->getLimitedSize();
7479 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7480
7481 APValue ArrayValue(APValue::UninitArray(), Size, Size);
7482 for (size_t I = 0; I != Size; ++I) {
7483 std::optional<APValue> ElementValue =
7484 visitType(Ty->getElementType(), Offset + I * ElementWidth);
7485 if (!ElementValue)
7486 return std::nullopt;
7487 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7488 }
7489
7490 return ArrayValue;
7491 }
7492
7493 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
7494 QualType EltTy = VTy->getElementType();
7495 unsigned NElts = VTy->getNumElements();
7496 unsigned EltSize =
7497 VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);
7498
7499 if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) {
7500 // The vector's size in bits is not a multiple of the target's byte size,
7501 // so its layout is unspecified. For now, we'll simply treat these cases
7502 // as unsupported (this should only be possible with OpenCL bool vectors
7503 // whose element count isn't a multiple of the byte size).
7504 Info.FFDiag(BCE->getBeginLoc(),
7505 diag::note_constexpr_bit_cast_invalid_vector)
7506 << QualType(VTy, 0) << EltSize << NElts << Info.Ctx.getCharWidth();
7507 return std::nullopt;
7508 }
7509
7510 if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(EltTy) ==
7511 &APFloat::x87DoubleExtended()) {
7512 // The layout for x86_fp80 vectors seems to be handled very inconsistently
7513 // by both clang and LLVM, so for now we won't allow bit_casts involving
7514 // it in a constexpr context.
7515 Info.FFDiag(BCE->getBeginLoc(),
7516 diag::note_constexpr_bit_cast_unsupported_type)
7517 << EltTy;
7518 return std::nullopt;
7519 }
7520
7522 Elts.reserve(NElts);
7523 if (VTy->isExtVectorBoolType()) {
7524 // Special handling for OpenCL bool vectors:
7525 // Since these vectors are stored as packed bits, but we can't read
7526 // individual bits from the BitCastBuffer, we'll buffer all of the
7527 // elements together into an appropriately sized APInt and write them all
7528 // out at once. Because we don't accept vectors where NElts * EltSize
7529 // isn't a multiple of the char size, there will be no padding space, so
7530 // we don't have to worry about reading any padding data which didn't
7531 // actually need to be accessed.
7532 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7533
7535 Bytes.reserve(NElts / 8);
7536 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
7537 return std::nullopt;
7538
7539 APSInt SValInt(NElts, true);
7540 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
7541
7542 for (unsigned I = 0; I < NElts; ++I) {
7543 llvm::APInt Elt =
7544 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
7545 Elts.emplace_back(
7546 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
7547 }
7548 } else {
7549 // Iterate over each of the elements and read them from the buffer at
7550 // the appropriate offset.
7551 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7552 for (unsigned I = 0; I < NElts; ++I) {
7553 std::optional<APValue> EltValue =
7554 visitType(EltTy, Offset + I * EltSizeChars);
7555 if (!EltValue)
7556 return std::nullopt;
7557 Elts.push_back(std::move(*EltValue));
7558 }
7559 }
7560
7561 return APValue(Elts.data(), Elts.size());
7562 }
7563
7564 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7565 return unsupportedType(QualType(Ty, 0));
7566 }
7567
7568 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7569 QualType Can = Ty.getCanonicalType();
7570
7571 switch (Can->getTypeClass()) {
7572#define TYPE(Class, Base) \
7573 case Type::Class: \
7574 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7575#define ABSTRACT_TYPE(Class, Base)
7576#define NON_CANONICAL_TYPE(Class, Base) \
7577 case Type::Class: \
7578 llvm_unreachable("non-canonical type should be impossible!");
7579#define DEPENDENT_TYPE(Class, Base) \
7580 case Type::Class: \
7581 llvm_unreachable( \
7582 "dependent types aren't supported in the constant evaluator!");
7583#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
7584 case Type::Class: \
7585 llvm_unreachable("either dependent or not canonical!");
7586#include "clang/AST/TypeNodes.inc"
7587 }
7588 llvm_unreachable("Unhandled Type::TypeClass");
7589 }
7590
7591public:
7592 // Pull out a full value of type DstType.
7593 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7594 const CastExpr *BCE) {
7595 BufferToAPValueConverter Converter(Info, Buffer, BCE);
7596 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7597 }
7598};
7599
7600static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7601 QualType Ty, EvalInfo *Info,
7602 const ASTContext &Ctx,
7603 bool CheckingDest) {
7604 Ty = Ty.getCanonicalType();
7605
7606 auto diag = [&](int Reason) {
7607 if (Info)
7608 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7609 << CheckingDest << (Reason == 4) << Reason;
7610 return false;
7611 };
7612 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7613 if (Info)
7614 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7615 << NoteTy << Construct << Ty;
7616 return false;
7617 };
7618
7619 if (Ty->isUnionType())
7620 return diag(0);
7621 if (Ty->isPointerType())
7622 return diag(1);
7623 if (Ty->isMemberPointerType())
7624 return diag(2);
7625 if (Ty.isVolatileQualified())
7626 return diag(3);
7627
7628 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7629 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7630 for (CXXBaseSpecifier &BS : CXXRD->bases())
7631 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7632 CheckingDest))
7633 return note(1, BS.getType(), BS.getBeginLoc());
7634 }
7635 for (FieldDecl *FD : Record->fields()) {
7636 if (FD->getType()->isReferenceType())
7637 return diag(4);
7638 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7639 CheckingDest))
7640 return note(0, FD->getType(), FD->getBeginLoc());
7641 }
7642 }
7643
7644 if (Ty->isArrayType() &&
7645 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7646 Info, Ctx, CheckingDest))
7647 return false;
7648
7649 return true;
7650}
7651
7652static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7653 const ASTContext &Ctx,
7654 const CastExpr *BCE) {
7655 bool DestOK = checkBitCastConstexprEligibilityType(
7656 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7657 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7658 BCE->getBeginLoc(),
7659 BCE->getSubExpr()->getType(), Info, Ctx, false);
7660 return SourceOK;
7661}
7662
7663static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7664 const APValue &SourceRValue,
7665 const CastExpr *BCE) {
7666 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7667 "no host or target supports non 8-bit chars");
7668
7669 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7670 return false;
7671
7672 // Read out SourceValue into a char buffer.
7673 std::optional<BitCastBuffer> Buffer =
7674 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7675 if (!Buffer)
7676 return false;
7677
7678 // Write out the buffer into a new APValue.
7679 std::optional<APValue> MaybeDestValue =
7680 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7681 if (!MaybeDestValue)
7682 return false;
7683
7684 DestValue = std::move(*MaybeDestValue);
7685 return true;
7686}
7687
7688static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7689 APValue &SourceValue,
7690 const CastExpr *BCE) {
7691 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7692 "no host or target supports non 8-bit chars");
7693 assert(SourceValue.isLValue() &&
7694 "LValueToRValueBitcast requires an lvalue operand!");
7695
7696 LValue SourceLValue;
7697 APValue SourceRValue;
7698 SourceLValue.setFrom(Info.Ctx, SourceValue);
7700 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7701 SourceRValue, /*WantObjectRepresentation=*/true))
7702 return false;
7703
7704 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
7705}
7706
7707template <class Derived>
7708class ExprEvaluatorBase
7709 : public ConstStmtVisitor<Derived, bool> {
7710private:
7711 Derived &getDerived() { return static_cast<Derived&>(*this); }
7712 bool DerivedSuccess(const APValue &V, const Expr *E) {
7713 return getDerived().Success(V, E);
7714 }
7715 bool DerivedZeroInitialization(const Expr *E) {
7716 return getDerived().ZeroInitialization(E);
7717 }
7718
7719 // Check whether a conditional operator with a non-constant condition is a
7720 // potential constant expression. If neither arm is a potential constant
7721 // expression, then the conditional operator is not either.
7722 template<typename ConditionalOperator>
7723 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7724 assert(Info.checkingPotentialConstantExpression());
7725
7726 // Speculatively evaluate both arms.
7728 {
7729 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7730 StmtVisitorTy::Visit(E->getFalseExpr());
7731 if (Diag.empty())
7732 return;
7733 }
7734
7735 {
7736 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7737 Diag.clear();
7738 StmtVisitorTy::Visit(E->getTrueExpr());
7739 if (Diag.empty())
7740 return;
7741 }
7742
7743 Error(E, diag::note_constexpr_conditional_never_const);
7744 }
7745
7746
7747 template<typename ConditionalOperator>
7748 bool HandleConditionalOperator(const ConditionalOperator *E) {
7749 bool BoolResult;
7750 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7751 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7752 CheckPotentialConstantConditional(E);
7753 return false;
7754 }
7755 if (Info.noteFailure()) {
7756 StmtVisitorTy::Visit(E->getTrueExpr());
7757 StmtVisitorTy::Visit(E->getFalseExpr());
7758 }
7759 return false;
7760 }
7761
7762 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7763 return StmtVisitorTy::Visit(EvalExpr);
7764 }
7765
7766protected:
7767 EvalInfo &Info;
7768 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7769 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7770
7771 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7772 return Info.CCEDiag(E, D);
7773 }
7774
7775 bool ZeroInitialization(const Expr *E) { return Error(E); }
7776
7777 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7778 unsigned BuiltinOp = E->getBuiltinCallee();
7779 return BuiltinOp != 0 &&
7780 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
7781 }
7782
7783public:
7784 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7785
7786 EvalInfo &getEvalInfo() { return Info; }
7787
7788 /// Report an evaluation error. This should only be called when an error is
7789 /// first discovered. When propagating an error, just return false.
7790 bool Error(const Expr *E, diag::kind D) {
7791 Info.FFDiag(E, D) << E->getSourceRange();
7792 return false;
7793 }
7794 bool Error(const Expr *E) {
7795 return Error(E, diag::note_invalid_subexpr_in_const_expr);
7796 }
7797
7798 bool VisitStmt(const Stmt *) {
7799 llvm_unreachable("Expression evaluator should not be called on stmts");
7800 }
7801 bool VisitExpr(const Expr *E) {
7802 return Error(E);
7803 }
7804
7805 bool VisitEmbedExpr(const EmbedExpr *E) {
7806 const auto It = E->begin();
7807 return StmtVisitorTy::Visit(*It);
7808 }
7809
7810 bool VisitPredefinedExpr(const PredefinedExpr *E) {
7811 return StmtVisitorTy::Visit(E->getFunctionName());
7812 }
7813 bool VisitConstantExpr(const ConstantExpr *E) {
7814 if (E->hasAPValueResult())
7815 return DerivedSuccess(E->getAPValueResult(), E);
7816
7817 return StmtVisitorTy::Visit(E->getSubExpr());
7818 }
7819
7820 bool VisitParenExpr(const ParenExpr *E)
7821 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7822 bool VisitUnaryExtension(const UnaryOperator *E)
7823 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7824 bool VisitUnaryPlus(const UnaryOperator *E)
7825 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7826 bool VisitChooseExpr(const ChooseExpr *E)
7827 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7828 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7829 { return StmtVisitorTy::Visit(E->getResultExpr()); }
7830 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7831 { return StmtVisitorTy::Visit(E->getReplacement()); }
7832 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7833 TempVersionRAII RAII(*Info.CurrentCall);
7834 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7835 return StmtVisitorTy::Visit(E->getExpr());
7836 }
7837 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7838 TempVersionRAII RAII(*Info.CurrentCall);
7839 // The initializer may not have been parsed yet, or might be erroneous.
7840 if (!E->getExpr())
7841 return Error(E);
7842 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7843 return StmtVisitorTy::Visit(E->getExpr());
7844 }
7845
7846 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7847 FullExpressionRAII Scope(Info);
7848 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7849 }
7850
7851 // Temporaries are registered when created, so we don't care about
7852 // CXXBindTemporaryExpr.
7853 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7854 return StmtVisitorTy::Visit(E->getSubExpr());
7855 }
7856
7857 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7858 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7859 return static_cast<Derived*>(this)->VisitCastExpr(E);
7860 }
7861 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7862 if (!Info.Ctx.getLangOpts().CPlusPlus20)
7863 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7864 return static_cast<Derived*>(this)->VisitCastExpr(E);
7865 }
7866 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7867 return static_cast<Derived*>(this)->VisitCastExpr(E);
7868 }
7869
7870 bool VisitBinaryOperator(const BinaryOperator *E) {
7871 switch (E->getOpcode()) {
7872 default:
7873 return Error(E);
7874
7875 case BO_Comma:
7876 VisitIgnoredValue(E->getLHS());
7877 return StmtVisitorTy::Visit(E->getRHS());
7878
7879 case BO_PtrMemD:
7880 case BO_PtrMemI: {
7881 LValue Obj;
7882 if (!HandleMemberPointerAccess(Info, E, Obj))
7883 return false;
7884 APValue Result;
7885 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7886 return false;
7887 return DerivedSuccess(Result, E);
7888 }
7889 }
7890 }
7891
7892 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7893 return StmtVisitorTy::Visit(E->getSemanticForm());
7894 }
7895
7896 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7897 // Evaluate and cache the common expression. We treat it as a temporary,
7898 // even though it's not quite the same thing.
7899 LValue CommonLV;
7900 if (!Evaluate(Info.CurrentCall->createTemporary(
7901 E->getOpaqueValue(),
7902 getStorageType(Info.Ctx, E->getOpaqueValue()),
7903 ScopeKind::FullExpression, CommonLV),
7904 Info, E->getCommon()))
7905 return false;
7906
7907 return HandleConditionalOperator(E);
7908 }
7909
7910 bool VisitConditionalOperator(const ConditionalOperator *E) {
7911 bool IsBcpCall = false;
7912 // If the condition (ignoring parens) is a __builtin_constant_p call,
7913 // the result is a constant expression if it can be folded without
7914 // side-effects. This is an important GNU extension. See GCC PR38377
7915 // for discussion.
7916 if (const CallExpr *CallCE =
7917 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7918 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7919 IsBcpCall = true;
7920
7921 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7922 // constant expression; we can't check whether it's potentially foldable.
7923 // FIXME: We should instead treat __builtin_constant_p as non-constant if
7924 // it would return 'false' in this mode.
7925 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7926 return false;
7927
7928 FoldConstant Fold(Info, IsBcpCall);
7929 if (!HandleConditionalOperator(E)) {
7930 Fold.keepDiagnostics();
7931 return false;
7932 }
7933
7934 return true;
7935 }
7936
7937 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7938 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
7939 Value && !Value->isAbsent())
7940 return DerivedSuccess(*Value, E);
7941
7942 const Expr *Source = E->getSourceExpr();
7943 if (!Source)
7944 return Error(E);
7945 if (Source == E) {
7946 assert(0 && "OpaqueValueExpr recursively refers to itself");
7947 return Error(E);
7948 }
7949 return StmtVisitorTy::Visit(Source);
7950 }
7951
7952 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7953 for (const Expr *SemE : E->semantics()) {
7954 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7955 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7956 // result expression: there could be two different LValues that would
7957 // refer to the same object in that case, and we can't model that.
7958 if (SemE == E->getResultExpr())
7959 return Error(E);
7960
7961 // Unique OVEs get evaluated if and when we encounter them when
7962 // emitting the rest of the semantic form, rather than eagerly.
7963 if (OVE->isUnique())
7964 continue;
7965
7966 LValue LV;
7967 if (!Evaluate(Info.CurrentCall->createTemporary(
7968 OVE, getStorageType(Info.Ctx, OVE),
7969 ScopeKind::FullExpression, LV),
7970 Info, OVE->getSourceExpr()))
7971 return false;
7972 } else if (SemE == E->getResultExpr()) {
7973 if (!StmtVisitorTy::Visit(SemE))
7974 return false;
7975 } else {
7976 if (!EvaluateIgnoredValue(Info, SemE))
7977 return false;
7978 }
7979 }
7980 return true;
7981 }
7982
7983 bool VisitCallExpr(const CallExpr *E) {
7984 APValue Result;
7985 if (!handleCallExpr(E, Result, nullptr))
7986 return false;
7987 return DerivedSuccess(Result, E);
7988 }
7989
7990 bool handleCallExpr(const CallExpr *E, APValue &Result,
7991 const LValue *ResultSlot) {
7992 CallScopeRAII CallScope(Info);
7993
7994 const Expr *Callee = E->getCallee()->IgnoreParens();
7995 QualType CalleeType = Callee->getType();
7996
7997 const FunctionDecl *FD = nullptr;
7998 LValue *This = nullptr, ThisVal;
7999 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
8000 bool HasQualifier = false;
8001
8002 CallRef Call;
8003
8004 // Extract function decl and 'this' pointer from the callee.
8005 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8006 const CXXMethodDecl *Member = nullptr;
8007 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8008 // Explicit bound member calls, such as x.f() or p->g();
8009 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
8010 return false;
8011 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8012 if (!Member)
8013 return Error(Callee);
8014 This = &ThisVal;
8015 HasQualifier = ME->hasQualifier();
8016 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8017 // Indirect bound member calls ('.*' or '->*').
8018 const ValueDecl *D =
8019 HandleMemberPointerAccess(Info, BE, ThisVal, false);
8020 if (!D)
8021 return false;
8022 Member = dyn_cast<CXXMethodDecl>(D);
8023 if (!Member)
8024 return Error(Callee);
8025 This = &ThisVal;
8026 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8027 if (!Info.getLangOpts().CPlusPlus20)
8028 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8029 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
8030 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
8031 } else
8032 return Error(Callee);
8033 FD = Member;
8034 } else if (CalleeType->isFunctionPointerType()) {
8035 LValue CalleeLV;
8036 if (!EvaluatePointer(Callee, CalleeLV, Info))
8037 return false;
8038
8039 if (!CalleeLV.getLValueOffset().isZero())
8040 return Error(Callee);
8041 if (CalleeLV.isNullPointer()) {
8042 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8043 << const_cast<Expr *>(Callee);
8044 return false;
8045 }
8046 FD = dyn_cast_or_null<FunctionDecl>(
8047 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8048 if (!FD)
8049 return Error(Callee);
8050 // Don't call function pointers which have been cast to some other type.
8051 // Per DR (no number yet), the caller and callee can differ in noexcept.
8052 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
8053 CalleeType->getPointeeType(), FD->getType())) {
8054 return Error(E);
8055 }
8056
8057 // For an (overloaded) assignment expression, evaluate the RHS before the
8058 // LHS.
8059 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8060 if (OCE && OCE->isAssignmentOp()) {
8061 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8062 Call = Info.CurrentCall->createCall(FD);
8063 bool HasThis = false;
8064 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8065 HasThis = MD->isImplicitObjectMemberFunction();
8066 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8067 /*RightToLeft=*/true))
8068 return false;
8069 }
8070
8071 // Overloaded operator calls to member functions are represented as normal
8072 // calls with '*this' as the first argument.
8073 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8074 if (MD &&
8075 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8076 // FIXME: When selecting an implicit conversion for an overloaded
8077 // operator delete, we sometimes try to evaluate calls to conversion
8078 // operators without a 'this' parameter!
8079 if (Args.empty())
8080 return Error(E);
8081
8082 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
8083 return false;
8084
8085 // If we are calling a static operator, the 'this' argument needs to be
8086 // ignored after being evaluated.
8087 if (MD->isInstance())
8088 This = &ThisVal;
8089
8090 // If this is syntactically a simple assignment using a trivial
8091 // assignment operator, start the lifetimes of union members as needed,
8092 // per C++20 [class.union]5.
8093 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8094 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8095 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal))
8096 return false;
8097
8098 Args = Args.slice(1);
8099 } else if (MD && MD->isLambdaStaticInvoker()) {
8100 // Map the static invoker for the lambda back to the call operator.
8101 // Conveniently, we don't have to slice out the 'this' argument (as is
8102 // being done for the non-static case), since a static member function
8103 // doesn't have an implicit argument passed in.
8104 const CXXRecordDecl *ClosureClass = MD->getParent();
8105 assert(
8106 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
8107 "Number of captures must be zero for conversion to function-ptr");
8108
8109 const CXXMethodDecl *LambdaCallOp =
8110 ClosureClass->getLambdaCallOperator();
8111
8112 // Set 'FD', the function that will be called below, to the call
8113 // operator. If the closure object represents a generic lambda, find
8114 // the corresponding specialization of the call operator.
8115
8116 if (ClosureClass->isGenericLambda()) {
8117 assert(MD->isFunctionTemplateSpecialization() &&
8118 "A generic lambda's static-invoker function must be a "
8119 "template specialization");
8121 FunctionTemplateDecl *CallOpTemplate =
8122 LambdaCallOp->getDescribedFunctionTemplate();
8123 void *InsertPos = nullptr;
8124 FunctionDecl *CorrespondingCallOpSpecialization =
8125 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8126 assert(CorrespondingCallOpSpecialization &&
8127 "We must always have a function call operator specialization "
8128 "that corresponds to our static invoker specialization");
8129 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8130 FD = CorrespondingCallOpSpecialization;
8131 } else
8132 FD = LambdaCallOp;
8133 } else if (FD->isReplaceableGlobalAllocationFunction()) {
8134 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
8135 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
8136 LValue Ptr;
8137 if (!HandleOperatorNewCall(Info, E, Ptr))
8138 return false;
8139 Ptr.moveInto(Result);
8140 return CallScope.destroy();
8141 } else {
8142 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8143 }
8144 }
8145 } else
8146 return Error(E);
8147
8148 // Evaluate the arguments now if we've not already done so.
8149 if (!Call) {
8150 Call = Info.CurrentCall->createCall(FD);
8151 if (!EvaluateArgs(Args, Call, Info, FD))
8152 return false;
8153 }
8154
8155 SmallVector<QualType, 4> CovariantAdjustmentPath;
8156 if (This) {
8157 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8158 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8159 // Perform virtual dispatch, if necessary.
8160 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8161 CovariantAdjustmentPath);
8162 if (!FD)
8163 return false;
8164 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8165 // Check that the 'this' pointer points to an object of the right type.
8166 // FIXME: If this is an assignment operator call, we may need to change
8167 // the active union member before we check this.
8168 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8169 return false;
8170 }
8171 }
8172
8173 // Destructor calls are different enough that they have their own codepath.
8174 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8175 assert(This && "no 'this' pointer for destructor call");
8176 return HandleDestruction(Info, E, *This,
8177 Info.Ctx.getRecordType(DD->getParent())) &&
8178 CallScope.destroy();
8179 }
8180
8181 const FunctionDecl *Definition = nullptr;
8182 Stmt *Body = FD->getBody(Definition);
8183
8184 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8185 !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8186 Body, Info, Result, ResultSlot))
8187 return false;
8188
8189 if (!CovariantAdjustmentPath.empty() &&
8190 !HandleCovariantReturnAdjustment(Info, E, Result,
8191 CovariantAdjustmentPath))
8192 return false;
8193
8194 return CallScope.destroy();
8195 }
8196
8197 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8198 return StmtVisitorTy::Visit(E->getInitializer());
8199 }
8200 bool VisitInitListExpr(const InitListExpr *E) {
8201 if (E->getNumInits() == 0)
8202 return DerivedZeroInitialization(E);
8203 if (E->getNumInits() == 1)
8204 return StmtVisitorTy::Visit(E->getInit(0));
8205 return Error(E);
8206 }
8207 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8208 return DerivedZeroInitialization(E);
8209 }
8210 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8211 return DerivedZeroInitialization(E);
8212 }
8213 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8214 return DerivedZeroInitialization(E);
8215 }
8216
8217 /// A member expression where the object is a prvalue is itself a prvalue.
8218 bool VisitMemberExpr(const MemberExpr *E) {
8219 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8220 "missing temporary materialization conversion");
8221 assert(!E->isArrow() && "missing call to bound member function?");
8222
8223 APValue Val;
8224 if (!Evaluate(Val, Info, E->getBase()))
8225 return false;
8226
8227 QualType BaseTy = E->getBase()->getType();
8228
8229 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8230 if (!FD) return Error(E);
8231 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8232 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8233 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8234
8235 // Note: there is no lvalue base here. But this case should only ever
8236 // happen in C or in C++98, where we cannot be evaluating a constexpr
8237 // constructor, which is the only case the base matters.
8238 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8239 SubobjectDesignator Designator(BaseTy);
8240 Designator.addDeclUnchecked(FD);
8241
8242 APValue Result;
8243 return extractSubobject(Info, E, Obj, Designator, Result) &&
8244 DerivedSuccess(Result, E);
8245 }
8246
8247 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8248 APValue Val;
8249 if (!Evaluate(Val, Info, E->getBase()))
8250 return false;
8251
8252 if (Val.isVector()) {
8254 E->getEncodedElementAccess(Indices);
8255 if (Indices.size() == 1) {
8256 // Return scalar.
8257 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8258 } else {
8259 // Construct new APValue vector.
8261 for (unsigned I = 0; I < Indices.size(); ++I) {
8262 Elts.push_back(Val.getVectorElt(Indices[I]));
8263 }
8264 APValue VecResult(Elts.data(), Indices.size());
8265 return DerivedSuccess(VecResult, E);
8266 }
8267 }
8268
8269 return false;
8270 }
8271
8272 bool VisitCastExpr(const CastExpr *E) {
8273 switch (E->getCastKind()) {
8274 default:
8275 break;
8276
8277 case CK_AtomicToNonAtomic: {
8278 APValue AtomicVal;
8279 // This does not need to be done in place even for class/array types:
8280 // atomic-to-non-atomic conversion implies copying the object
8281 // representation.
8282 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8283 return false;
8284 return DerivedSuccess(AtomicVal, E);
8285 }
8286
8287 case CK_NoOp:
8288 case CK_UserDefinedConversion:
8289 return StmtVisitorTy::Visit(E->getSubExpr());
8290
8291 case CK_LValueToRValue: {
8292 LValue LVal;
8293 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8294 return false;
8295 APValue RVal;
8296 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8297 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8298 LVal, RVal))
8299 return false;
8300 return DerivedSuccess(RVal, E);
8301 }
8302 case CK_LValueToRValueBitCast: {
8303 APValue DestValue, SourceValue;
8304 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8305 return false;
8306 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8307 return false;
8308 return DerivedSuccess(DestValue, E);
8309 }
8310
8311 case CK_AddressSpaceConversion: {
8312 APValue Value;
8313 if (!Evaluate(Value, Info, E->getSubExpr()))
8314 return false;
8315 return DerivedSuccess(Value, E);
8316 }
8317 }
8318
8319 return Error(E);
8320 }
8321
8322 bool VisitUnaryPostInc(const UnaryOperator *UO) {
8323 return VisitUnaryPostIncDec(UO);
8324 }
8325 bool VisitUnaryPostDec(const UnaryOperator *UO) {
8326 return VisitUnaryPostIncDec(UO);
8327 }
8328 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8329 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8330 return Error(UO);
8331
8332 LValue LVal;
8333 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8334 return false;
8335 APValue RVal;
8336 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8337 UO->isIncrementOp(), &RVal))
8338 return false;
8339 return DerivedSuccess(RVal, UO);
8340 }
8341
8342 bool VisitStmtExpr(const StmtExpr *E) {
8343 // We will have checked the full-expressions inside the statement expression
8344 // when they were completed, and don't need to check them again now.
8345 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8346 false);
8347
8348 const CompoundStmt *CS = E->getSubStmt();
8349 if (CS->body_empty())
8350 return true;
8351
8352 BlockScopeRAII Scope(Info);
8354 BE = CS->body_end();
8355 /**/; ++BI) {
8356 if (BI + 1 == BE) {
8357 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8358 if (!FinalExpr) {
8359 Info.FFDiag((*BI)->getBeginLoc(),
8360 diag::note_constexpr_stmt_expr_unsupported);
8361 return false;
8362 }
8363 return this->Visit(FinalExpr) && Scope.destroy();
8364 }
8365
8367 StmtResult Result = { ReturnValue, nullptr };
8368 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8369 if (ESR != ESR_Succeeded) {
8370 // FIXME: If the statement-expression terminated due to 'return',
8371 // 'break', or 'continue', it would be nice to propagate that to
8372 // the outer statement evaluation rather than bailing out.
8373 if (ESR != ESR_Failed)
8374 Info.FFDiag((*BI)->getBeginLoc(),
8375 diag::note_constexpr_stmt_expr_unsupported);
8376 return false;
8377 }
8378 }
8379
8380 llvm_unreachable("Return from function from the loop above.");
8381 }
8382
8383 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
8384 return StmtVisitorTy::Visit(E->getSelectedExpr());
8385 }
8386
8387 /// Visit a value which is evaluated, but whose value is ignored.
8388 void VisitIgnoredValue(const Expr *E) {
8389 EvaluateIgnoredValue(Info, E);
8390 }
8391
8392 /// Potentially visit a MemberExpr's base expression.
8393 void VisitIgnoredBaseExpression(const Expr *E) {
8394 // While MSVC doesn't evaluate the base expression, it does diagnose the
8395 // presence of side-effecting behavior.
8396 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8397 return;
8398 VisitIgnoredValue(E);
8399 }
8400};
8401
8402} // namespace
8403
8404//===----------------------------------------------------------------------===//
8405// Common base class for lvalue and temporary evaluation.
8406//===----------------------------------------------------------------------===//
8407namespace {
8408template<class Derived>
8409class LValueExprEvaluatorBase
8410 : public ExprEvaluatorBase<Derived> {
8411protected:
8412 LValue &Result;
8413 bool InvalidBaseOK;
8414 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8415 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8416
8418 Result.set(B);
8419 return true;
8420 }
8421
8422 bool evaluatePointer(const Expr *E, LValue &Result) {
8423 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8424 }
8425
8426public:
8427 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8428 : ExprEvaluatorBaseTy(Info), Result(Result),
8429 InvalidBaseOK(InvalidBaseOK) {}
8430
8431 bool Success(const APValue &V, const Expr *E) {
8432 Result.setFrom(this->Info.Ctx, V);
8433 return true;
8434 }
8435
8436 bool VisitMemberExpr(const MemberExpr *E) {
8437 // Handle non-static data members.
8438 QualType BaseTy;
8439 bool EvalOK;
8440 if (E->isArrow()) {
8441 EvalOK = evaluatePointer(E->getBase(), Result);
8442 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8443 } else if (E->getBase()->isPRValue()) {
8444 assert(E->getBase()->getType()->isRecordType());
8445 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8446 BaseTy = E->getBase()->getType();
8447 } else {
8448 EvalOK = this->Visit(E->getBase());
8449 BaseTy = E->getBase()->getType();
8450 }
8451 if (!EvalOK) {
8452 if (!InvalidBaseOK)
8453 return false;
8454 Result.setInvalid(E);
8455 return true;
8456 }
8457
8458 const ValueDecl *MD = E->getMemberDecl();
8459 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8460 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8461 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8462 (void)BaseTy;
8463 if (!HandleLValueMember(this->Info, E, Result, FD))
8464 return false;
8465 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8466 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8467 return false;
8468 } else
8469 return this->Error(E);
8470
8471 if (MD->getType()->isReferenceType()) {
8472 APValue RefValue;
8473 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8474 RefValue))
8475 return false;
8476 return Success(RefValue, E);
8477 }
8478 return true;
8479 }
8480
8481 bool VisitBinaryOperator(const BinaryOperator *E) {
8482 switch (E->getOpcode()) {
8483 default:
8484 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8485
8486 case BO_PtrMemD:
8487 case BO_PtrMemI:
8488 return HandleMemberPointerAccess(this->Info, E, Result);
8489 }
8490 }
8491
8492 bool VisitCastExpr(const CastExpr *E) {
8493 switch (E->getCastKind()) {
8494 default:
8495 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8496
8497 case CK_DerivedToBase:
8498 case CK_UncheckedDerivedToBase:
8499 if (!this->Visit(E->getSubExpr()))
8500 return false;
8501
8502 // Now figure out the necessary offset to add to the base LV to get from
8503 // the derived class to the base class.
8504 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8505 Result);
8506 }
8507 }
8508};
8509}
8510
8511//===----------------------------------------------------------------------===//
8512// LValue Evaluation
8513//
8514// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8515// function designators (in C), decl references to void objects (in C), and
8516// temporaries (if building with -Wno-address-of-temporary).
8517//
8518// LValue evaluation produces values comprising a base expression of one of the
8519// following types:
8520// - Declarations
8521// * VarDecl
8522// * FunctionDecl
8523// - Literals
8524// * CompoundLiteralExpr in C (and in global scope in C++)
8525// * StringLiteral
8526// * PredefinedExpr
8527// * ObjCStringLiteralExpr
8528// * ObjCEncodeExpr
8529// * AddrLabelExpr
8530// * BlockExpr
8531// * CallExpr for a MakeStringConstant builtin
8532// - typeid(T) expressions, as TypeInfoLValues
8533// - Locals and temporaries
8534// * MaterializeTemporaryExpr
8535// * Any Expr, with a CallIndex indicating the function in which the temporary
8536// was evaluated, for cases where the MaterializeTemporaryExpr is missing
8537// from the AST (FIXME).
8538// * A MaterializeTemporaryExpr that has static storage duration, with no
8539// CallIndex, for a lifetime-extended temporary.
8540// * The ConstantExpr that is currently being evaluated during evaluation of an
8541// immediate invocation.
8542// plus an offset in bytes.
8543//===----------------------------------------------------------------------===//
8544namespace {
8545class LValueExprEvaluator
8546 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8547public:
8548 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8549 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8550
8551 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8552 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8553
8554 bool VisitCallExpr(const CallExpr *E);
8555 bool VisitDeclRefExpr(const DeclRefExpr *E);
8556 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8557 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8558 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8559 bool VisitMemberExpr(const MemberExpr *E);
8560 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8561 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8562 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8563 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8564 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8565 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
8566 bool VisitUnaryDeref(const UnaryOperator *E);
8567 bool VisitUnaryReal(const UnaryOperator *E);
8568 bool VisitUnaryImag(const UnaryOperator *E);
8569 bool VisitUnaryPreInc(const UnaryOperator *UO) {
8570 return VisitUnaryPreIncDec(UO);
8571 }
8572 bool VisitUnaryPreDec(const UnaryOperator *UO) {
8573 return VisitUnaryPreIncDec(UO);
8574 }
8575 bool VisitBinAssign(const BinaryOperator *BO);
8576 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8577
8578 bool VisitCastExpr(const CastExpr *E) {
8579 switch (E->getCastKind()) {
8580 default:
8581 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8582
8583 case CK_LValueBitCast:
8584 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8585 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8586 if (!Visit(E->getSubExpr()))
8587 return false;
8588 Result.Designator.setInvalid();
8589 return true;
8590
8591 case CK_BaseToDerived:
8592 if (!Visit(E->getSubExpr()))
8593 return false;
8594 return HandleBaseToDerivedCast(Info, E, Result);
8595
8596 case CK_Dynamic:
8597 if (!Visit(E->getSubExpr()))
8598 return false;
8599 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8600 }
8601 }
8602};
8603} // end anonymous namespace
8604
8605/// Get an lvalue to a field of a lambda's closure type.
8606static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
8607 const CXXMethodDecl *MD, const FieldDecl *FD,
8608 bool LValueToRValueConversion) {
8609 // Static lambda function call operators can't have captures. We already
8610 // diagnosed this, so bail out here.
8611 if (MD->isStatic()) {
8612 assert(Info.CurrentCall->This == nullptr &&
8613 "This should not be set for a static call operator");
8614 return false;
8615 }
8616
8617 // Start with 'Result' referring to the complete closure object...
8619 // Self may be passed by reference or by value.
8620 const ParmVarDecl *Self = MD->getParamDecl(0);
8621 if (Self->getType()->isReferenceType()) {
8622 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
8623 Result.setFrom(Info.Ctx, *RefValue);
8624 } else {
8625 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
8626 CallStackFrame *Frame =
8627 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
8628 .first;
8629 unsigned Version = Info.CurrentCall->Arguments.Version;
8630 Result.set({VD, Frame->Index, Version});
8631 }
8632 } else
8633 Result = *Info.CurrentCall->This;
8634
8635 // ... then update it to refer to the field of the closure object
8636 // that represents the capture.
8637 if (!HandleLValueMember(Info, E, Result, FD))
8638 return false;
8639
8640 // And if the field is of reference type (or if we captured '*this' by
8641 // reference), update 'Result' to refer to what
8642 // the field refers to.
8643 if (LValueToRValueConversion) {
8644 APValue RVal;
8645 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
8646 return false;
8647 Result.setFrom(Info.Ctx, RVal);
8648 }
8649 return true;
8650}
8651
8652/// Evaluate an expression as an lvalue. This can be legitimately called on
8653/// expressions which are not glvalues, in three cases:
8654/// * function designators in C, and
8655/// * "extern void" objects
8656/// * @selector() expressions in Objective-C
8657static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8658 bool InvalidBaseOK) {
8659 assert(!E->isValueDependent());
8660 assert(E->isGLValue() || E->getType()->isFunctionType() ||
8661 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
8662 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8663}
8664
8665bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8666 const NamedDecl *D = E->getDecl();
8669 return Success(cast<ValueDecl>(D));
8670 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8671 return VisitVarDecl(E, VD);
8672 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8673 return Visit(BD->getBinding());
8674 return Error(E);
8675}
8676
8677
8678bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8679
8680 // If we are within a lambda's call operator, check whether the 'VD' referred
8681 // to within 'E' actually represents a lambda-capture that maps to a
8682 // data-member/field within the closure object, and if so, evaluate to the
8683 // field or what the field refers to.
8684 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8685 isa<DeclRefExpr>(E) &&
8686 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8687 // We don't always have a complete capture-map when checking or inferring if
8688 // the function call operator meets the requirements of a constexpr function
8689 // - but we don't need to evaluate the captures to determine constexprness
8690 // (dcl.constexpr C++17).
8691 if (Info.checkingPotentialConstantExpression())
8692 return false;
8693
8694 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8695 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
8696 return HandleLambdaCapture(Info, E, Result, MD, FD,
8697 FD->getType()->isReferenceType());
8698 }
8699 }
8700
8701 CallStackFrame *Frame = nullptr;
8702 unsigned Version = 0;
8703 if (VD->hasLocalStorage()) {
8704 // Only if a local variable was declared in the function currently being
8705 // evaluated, do we expect to be able to find its value in the current
8706 // frame. (Otherwise it was likely declared in an enclosing context and
8707 // could either have a valid evaluatable value (for e.g. a constexpr
8708 // variable) or be ill-formed (and trigger an appropriate evaluation
8709 // diagnostic)).
8710 CallStackFrame *CurrFrame = Info.CurrentCall;
8711 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8712 // Function parameters are stored in some caller's frame. (Usually the
8713 // immediate caller, but for an inherited constructor they may be more
8714 // distant.)
8715 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8716 if (CurrFrame->Arguments) {
8717 VD = CurrFrame->Arguments.getOrigParam(PVD);
8718 Frame =
8719 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8720 Version = CurrFrame->Arguments.Version;
8721 }
8722 } else {
8723 Frame = CurrFrame;
8724 Version = CurrFrame->getCurrentTemporaryVersion(VD);
8725 }
8726 }
8727 }
8728
8729 if (!VD->getType()->isReferenceType()) {
8730 if (Frame) {
8731 Result.set({VD, Frame->Index, Version});
8732 return true;
8733 }
8734 return Success(VD);
8735 }
8736
8737 if (!Info.getLangOpts().CPlusPlus11) {
8738 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8739 << VD << VD->getType();
8740 Info.Note(VD->getLocation(), diag::note_declared_at);
8741 }
8742
8743 APValue *V;
8744 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8745 return false;
8746 if (!V->hasValue()) {
8747 // FIXME: Is it possible for V to be indeterminate here? If so, we should
8748 // adjust the diagnostic to say that.
8749 if (!Info.checkingPotentialConstantExpression())
8750 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8751 return false;
8752 }
8753 return Success(*V, E);
8754}
8755
8756bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8757 if (!IsConstantEvaluatedBuiltinCall(E))
8758 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8759
8760 switch (E->getBuiltinCallee()) {
8761 default:
8762 return false;
8763 case Builtin::BIas_const:
8764 case Builtin::BIforward:
8765 case Builtin::BIforward_like:
8766 case Builtin::BImove:
8767 case Builtin::BImove_if_noexcept:
8768 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8769 return Visit(E->getArg(0));
8770 break;
8771 }
8772
8773 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8774}
8775
8776bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8777 const MaterializeTemporaryExpr *E) {
8778 // Walk through the expression to find the materialized temporary itself.
8781 const Expr *Inner =
8782 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8783
8784 // If we passed any comma operators, evaluate their LHSs.
8785 for (const Expr *E : CommaLHSs)
8786 if (!EvaluateIgnoredValue(Info, E))
8787 return false;
8788
8789 // A materialized temporary with static storage duration can appear within the
8790 // result of a constant expression evaluation, so we need to preserve its
8791 // value for use outside this evaluation.
8792 APValue *Value;
8793 if (E->getStorageDuration() == SD_Static) {
8794 if (Info.EvalMode == EvalInfo::EM_ConstantFold)
8795 return false;
8796 // FIXME: What about SD_Thread?
8797 Value = E->getOrCreateValue(true);
8798 *Value = APValue();
8799 Result.set(E);
8800 } else {
8801 Value = &Info.CurrentCall->createTemporary(
8802 E, Inner->getType(),
8803 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8804 : ScopeKind::Block,
8805 Result);
8806 }
8807
8808 QualType Type = Inner->getType();
8809
8810 // Materialize the temporary itself.
8811 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8812 *Value = APValue();
8813 return false;
8814 }
8815
8816 // Adjust our lvalue to refer to the desired subobject.
8817 for (unsigned I = Adjustments.size(); I != 0; /**/) {
8818 --I;
8819 switch (Adjustments[I].Kind) {
8821 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8822 Type, Result))
8823 return false;
8824 Type = Adjustments[I].DerivedToBase.BasePath->getType();
8825 break;
8826
8828 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8829 return false;
8830 Type = Adjustments[I].Field->getType();
8831 break;
8832
8834 if (!HandleMemberPointerAccess(this->Info, Type, Result,
8835 Adjustments[I].Ptr.RHS))
8836 return false;
8837 Type = Adjustments[I].Ptr.MPT->getPointeeType();
8838 break;
8839 }
8840 }
8841
8842 return true;
8843}
8844
8845bool
8846LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8847 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8848 "lvalue compound literal in c++?");
8849 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8850 // only see this when folding in C, so there's no standard to follow here.
8851 return Success(E);
8852}
8853
8854bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8856
8857 if (!E->isPotentiallyEvaluated()) {
8858 if (E->isTypeOperand())
8859 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8860 else
8861 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8862 } else {
8863 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8864 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8865 << E->getExprOperand()->getType()
8866 << E->getExprOperand()->getSourceRange();
8867 }
8868
8869 if (!Visit(E->getExprOperand()))
8870 return false;
8871
8872 std::optional<DynamicType> DynType =
8873 ComputeDynamicType(Info, E, Result, AK_TypeId);
8874 if (!DynType)
8875 return false;
8876
8877 TypeInfo =
8878 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8879 }
8880
8882}
8883
8884bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8885 return Success(E->getGuidDecl());
8886}
8887
8888bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8889 // Handle static data members.
8890 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8891 VisitIgnoredBaseExpression(E->getBase());
8892 return VisitVarDecl(E, VD);
8893 }
8894
8895 // Handle static member functions.
8896 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8897 if (MD->isStatic()) {
8898 VisitIgnoredBaseExpression(E->getBase());
8899 return Success(MD);
8900 }
8901 }
8902
8903 // Handle non-static data members.
8904 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8905}
8906
8907bool LValueExprEvaluator::VisitExtVectorElementExpr(
8908 const ExtVectorElementExpr *E) {
8909 bool Success = true;
8910
8911 APValue Val;
8912 if (!Evaluate(Val, Info, E->getBase())) {
8913 if (!Info.noteFailure())
8914 return false;
8915 Success = false;
8916 }
8917
8919 E->getEncodedElementAccess(Indices);
8920 // FIXME: support accessing more than one element
8921 if (Indices.size() > 1)
8922 return false;
8923
8924 if (Success) {
8925 Result.setFrom(Info.Ctx, Val);
8926 const auto *VT = E->getBase()->getType()->castAs<VectorType>();
8927 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
8928 VT->getNumElements(), Indices[0]);
8929 }
8930
8931 return Success;
8932}
8933
8934bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8935 if (E->getBase()->getType()->isSveVLSBuiltinType())
8936 return Error(E);
8937
8938 APSInt Index;
8939 bool Success = true;
8940
8941 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
8942 APValue Val;
8943 if (!Evaluate(Val, Info, E->getBase())) {
8944 if (!Info.noteFailure())
8945 return false;
8946 Success = false;
8947 }
8948
8949 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
8950 if (!Info.noteFailure())
8951 return false;
8952 Success = false;
8953 }
8954
8955 if (Success) {
8956 Result.setFrom(Info.Ctx, Val);
8957 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
8958 VT->getNumElements(), Index.getExtValue());
8959 }
8960
8961 return Success;
8962 }
8963
8964 // C++17's rules require us to evaluate the LHS first, regardless of which
8965 // side is the base.
8966 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8967 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8968 : !EvaluateInteger(SubExpr, Index, Info)) {
8969 if (!Info.noteFailure())
8970 return false;
8971 Success = false;
8972 }
8973 }
8974
8975 return Success &&
8976 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8977}
8978
8979bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8980 return evaluatePointer(E->getSubExpr(), Result);
8981}
8982
8983bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8984 if (!Visit(E->getSubExpr()))
8985 return false;
8986 // __real is a no-op on scalar lvalues.
8987 if (E->getSubExpr()->getType()->isAnyComplexType())
8988 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8989 return true;
8990}
8991
8992bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8993 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8994 "lvalue __imag__ on scalar?");
8995 if (!Visit(E->getSubExpr()))
8996 return false;
8997 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8998 return true;
8999}
9000
9001bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9002 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9003 return Error(UO);
9004
9005 if (!this->Visit(UO->getSubExpr()))
9006 return false;
9007
9008 return handleIncDec(
9009 this->Info, UO, Result, UO->getSubExpr()->getType(),
9010 UO->isIncrementOp(), nullptr);
9011}
9012
9013bool LValueExprEvaluator::VisitCompoundAssignOperator(
9014 const CompoundAssignOperator *CAO) {
9015 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9016 return Error(CAO);
9017
9018 bool Success = true;
9019
9020 // C++17 onwards require that we evaluate the RHS first.
9021 APValue RHS;
9022 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9023 if (!Info.noteFailure())
9024 return false;
9025 Success = false;
9026 }
9027
9028 // The overall lvalue result is the result of evaluating the LHS.
9029 if (!this->Visit(CAO->getLHS()) || !Success)
9030 return false;
9031
9033 this->Info, CAO,
9034 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9035 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9036}
9037
9038bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9039 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9040 return Error(E);
9041
9042 bool Success = true;
9043
9044 // C++17 onwards require that we evaluate the RHS first.
9045 APValue NewVal;
9046 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9047 if (!Info.noteFailure())
9048 return false;
9049 Success = false;
9050 }
9051
9052 if (!this->Visit(E->getLHS()) || !Success)
9053 return false;
9054
9055 if (Info.getLangOpts().CPlusPlus20 &&
9056 !MaybeHandleUnionActiveMemberChange(Info, E->getLHS(), Result))
9057 return false;
9058
9059 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9060 NewVal);
9061}
9062
9063//===----------------------------------------------------------------------===//
9064// Pointer Evaluation
9065//===----------------------------------------------------------------------===//
9066
9067/// Attempts to compute the number of bytes available at the pointer
9068/// returned by a function with the alloc_size attribute. Returns true if we
9069/// were successful. Places an unsigned number into `Result`.
9070///
9071/// This expects the given CallExpr to be a call to a function with an
9072/// alloc_size attribute.
9074 const CallExpr *Call,
9075 llvm::APInt &Result) {
9076 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
9077
9078 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
9079 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
9080 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
9081 if (Call->getNumArgs() <= SizeArgNo)
9082 return false;
9083
9084 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
9087 return false;
9088 Into = ExprResult.Val.getInt();
9089 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
9090 return false;
9091 Into = Into.zext(BitsInSizeT);
9092 return true;
9093 };
9094
9095 APSInt SizeOfElem;
9096 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
9097 return false;
9098
9099 if (!AllocSize->getNumElemsParam().isValid()) {
9100 Result = std::move(SizeOfElem);
9101 return true;
9102 }
9103
9104 APSInt NumberOfElems;
9105 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
9106 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
9107 return false;
9108
9109 bool Overflow;
9110 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
9111 if (Overflow)
9112 return false;
9113
9114 Result = std::move(BytesAvailable);
9115 return true;
9116}
9117
9118/// Convenience function. LVal's base must be a call to an alloc_size
9119/// function.
9121 const LValue &LVal,
9122 llvm::APInt &Result) {
9123 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9124 "Can't get the size of a non alloc_size function");
9125 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9126 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9127 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
9128}
9129
9130/// Attempts to evaluate the given LValueBase as the result of a call to
9131/// a function with the alloc_size attribute. If it was possible to do so, this
9132/// function will return true, make Result's Base point to said function call,
9133/// and mark Result's Base as invalid.
9135 LValue &Result) {
9136 if (Base.isNull())
9137 return false;
9138
9139 // Because we do no form of static analysis, we only support const variables.
9140 //
9141 // Additionally, we can't support parameters, nor can we support static
9142 // variables (in the latter case, use-before-assign isn't UB; in the former,
9143 // we have no clue what they'll be assigned to).
9144 const auto *VD =
9145 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9146 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9147 return false;
9148
9149 const Expr *Init = VD->getAnyInitializer();
9150 if (!Init || Init->getType().isNull())
9151 return false;
9152
9153 const Expr *E = Init->IgnoreParens();
9154 if (!tryUnwrapAllocSizeCall(E))
9155 return false;
9156
9157 // Store E instead of E unwrapped so that the type of the LValue's base is
9158 // what the user wanted.
9159 Result.setInvalid(E);
9160
9161 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9162 Result.addUnsizedArray(Info, E, Pointee);
9163 return true;
9164}
9165
9166namespace {
9167class PointerExprEvaluator
9168 : public ExprEvaluatorBase<PointerExprEvaluator> {
9169 LValue &Result;
9170 bool InvalidBaseOK;
9171
9172 bool Success(const Expr *E) {
9173 Result.set(E);
9174 return true;
9175 }
9176
9177 bool evaluateLValue(const Expr *E, LValue &Result) {
9178 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9179 }
9180
9181 bool evaluatePointer(const Expr *E, LValue &Result) {
9182 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9183 }
9184
9185 bool visitNonBuiltinCallExpr(const CallExpr *E);
9186public:
9187
9188 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9189 : ExprEvaluatorBaseTy(info), Result(Result),
9190 InvalidBaseOK(InvalidBaseOK) {}
9191
9192 bool Success(const APValue &V, const Expr *E) {
9193 Result.setFrom(Info.Ctx, V);
9194 return true;
9195 }
9196 bool ZeroInitialization(const Expr *E) {
9197 Result.setNull(Info.Ctx, E->getType());
9198 return true;
9199 }
9200
9201 bool VisitBinaryOperator(const BinaryOperator *E);
9202 bool VisitCastExpr(const CastExpr* E);
9203 bool VisitUnaryAddrOf(const UnaryOperator *E);
9204 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9205 { return Success(E); }
9206 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9207 if (E->isExpressibleAsConstantInitializer())
9208 return Success(E);
9209 if (Info.noteFailure())
9210 EvaluateIgnoredValue(Info, E->getSubExpr());
9211 return Error(E);
9212 }
9213 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9214 { return Success(E); }
9215 bool VisitCallExpr(const CallExpr *E);
9216 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9217 bool VisitBlockExpr(const BlockExpr *E) {
9218 if (!E->getBlockDecl()->hasCaptures())
9219 return Success(E);
9220 return Error(E);
9221 }
9222 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9223 auto DiagnoseInvalidUseOfThis = [&] {
9224 if (Info.getLangOpts().CPlusPlus11)
9225 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9226 else
9227 Info.FFDiag(E);
9228 };
9229
9230 // Can't look at 'this' when checking a potential constant expression.
9231 if (Info.checkingPotentialConstantExpression())
9232 return false;
9233
9234 bool IsExplicitLambda =
9235 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9236 if (!IsExplicitLambda) {
9237 if (!Info.CurrentCall->This) {
9238 DiagnoseInvalidUseOfThis();
9239 return false;
9240 }
9241
9242 Result = *Info.CurrentCall->This;
9243 }
9244
9245 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9246 // Ensure we actually have captured 'this'. If something was wrong with
9247 // 'this' capture, the error would have been previously reported.
9248 // Otherwise we can be inside of a default initialization of an object
9249 // declared by lambda's body, so no need to return false.
9250 if (!Info.CurrentCall->LambdaThisCaptureField) {
9251 if (IsExplicitLambda && !Info.CurrentCall->This) {
9252 DiagnoseInvalidUseOfThis();
9253 return false;
9254 }
9255
9256 return true;
9257 }
9258
9259 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9260 return HandleLambdaCapture(
9261 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
9262 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9263 }
9264 return true;
9265 }
9266
9267 bool VisitCXXNewExpr(const CXXNewExpr *E);
9268
9269 bool VisitSourceLocExpr(const SourceLocExpr *E) {
9270 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9271 APValue LValResult = E->EvaluateInContext(
9272 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9273 Result.setFrom(Info.Ctx, LValResult);
9274 return true;
9275 }
9276
9277 bool VisitEmbedExpr(const EmbedExpr *E) {
9278 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
9279 return true;
9280 }
9281
9282 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9283 std::string ResultStr = E->ComputeName(Info.Ctx);
9284
9285 QualType CharTy = Info.Ctx.CharTy.withConst();
9286 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9287 ResultStr.size() + 1);
9288 QualType ArrayTy = Info.Ctx.getConstantArrayType(
9289 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9290
9291 StringLiteral *SL =
9292 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9293 /*Pascal*/ false, ArrayTy, E->getLocation());
9294
9295 evaluateLValue(SL, Result);
9296 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
9297 return true;
9298 }
9299
9300 // FIXME: Missing: @protocol, @selector
9301};
9302} // end anonymous namespace
9303
9304static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
9305 bool InvalidBaseOK) {
9306 assert(!E->isValueDependent());
9307 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
9308 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9309}
9310
9311bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9312 if (E->getOpcode() != BO_Add &&
9313 E->getOpcode() != BO_Sub)
9314 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9315
9316 const Expr *PExp = E->getLHS();
9317 const Expr *IExp = E->getRHS();
9318 if (IExp->getType()->isPointerType())
9319 std::swap(PExp, IExp);
9320
9321 bool EvalPtrOK = evaluatePointer(PExp, Result);
9322 if (!EvalPtrOK && !Info.noteFailure())
9323 return false;
9324
9325 llvm::APSInt Offset;
9326 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
9327 return false;
9328
9329 if (E->getOpcode() == BO_Sub)
9330 negateAsSigned(Offset);
9331
9332 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
9333 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
9334}
9335
9336bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9337 return evaluateLValue(E->getSubExpr(), Result);
9338}
9339
9340// Is the provided decl 'std::source_location::current'?
9342 if (!FD)
9343 return false;
9344 const IdentifierInfo *FnII = FD->getIdentifier();
9345 if (!FnII || !FnII->isStr("current"))
9346 return false;
9347
9348 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
9349 if (!RD)
9350 return false;
9351
9352 const IdentifierInfo *ClassII = RD->getIdentifier();
9353 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
9354}
9355
9356bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9357 const Expr *SubExpr = E->getSubExpr();
9358
9359 switch (E->getCastKind()) {
9360 default:
9361 break;
9362 case CK_BitCast:
9363 case CK_CPointerToObjCPointerCast:
9364 case CK_BlockPointerToObjCPointerCast:
9365 case CK_AnyPointerToBlockPointerCast:
9366 case CK_AddressSpaceConversion:
9367 if (!Visit(SubExpr))
9368 return false;
9369 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
9370 // permitted in constant expressions in C++11. Bitcasts from cv void* are
9371 // also static_casts, but we disallow them as a resolution to DR1312.
9372 if (!E->getType()->isVoidPointerType()) {
9373 // In some circumstances, we permit casting from void* to cv1 T*, when the
9374 // actual pointee object is actually a cv2 T.
9375 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
9376 !Result.IsNullPtr;
9377 bool VoidPtrCastMaybeOK =
9378 Result.IsNullPtr ||
9379 (HasValidResult &&
9380 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
9381 E->getType()->getPointeeType()));
9382 // 1. We'll allow it in std::allocator::allocate, and anything which that
9383 // calls.
9384 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9385 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9386 // We'll allow it in the body of std::source_location::current. GCC's
9387 // implementation had a parameter of type `void*`, and casts from
9388 // that back to `const __impl*` in its body.
9389 if (VoidPtrCastMaybeOK &&
9390 (Info.getStdAllocatorCaller("allocate") ||
9391 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
9392 Info.getLangOpts().CPlusPlus26)) {
9393 // Permitted.
9394 } else {
9395 if (SubExpr->getType()->isVoidPointerType() &&
9396 Info.getLangOpts().CPlusPlus) {
9397 if (HasValidResult)
9398 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
9399 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
9400 << Result.Designator.getType(Info.Ctx).getCanonicalType()
9401 << E->getType()->getPointeeType();
9402 else
9403 CCEDiag(E, diag::note_constexpr_invalid_cast)
9404 << 3 << SubExpr->getType();
9405 } else
9406 CCEDiag(E, diag::note_constexpr_invalid_cast)
9407 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9408 Result.Designator.setInvalid();
9409 }
9410 }
9411 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
9412 ZeroInitialization(E);
9413 return true;
9414
9415 case CK_DerivedToBase:
9416 case CK_UncheckedDerivedToBase:
9417 if (!evaluatePointer(E->getSubExpr(), Result))
9418 return false;
9419 if (!Result.Base && Result.Offset.isZero())
9420 return true;
9421
9422 // Now figure out the necessary offset to add to the base LV to get from
9423 // the derived class to the base class.
9424 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
9425 castAs<PointerType>()->getPointeeType(),
9426 Result);
9427
9428 case CK_BaseToDerived:
9429 if (!Visit(E->getSubExpr()))
9430 return false;
9431 if (!Result.Base && Result.Offset.isZero())
9432 return true;
9433 return HandleBaseToDerivedCast(Info, E, Result);
9434
9435 case CK_Dynamic:
9436 if (!Visit(E->getSubExpr()))
9437 return false;
9438 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
9439
9440 case CK_NullToPointer:
9441 VisitIgnoredValue(E->getSubExpr());
9442 return ZeroInitialization(E);
9443
9444 case CK_IntegralToPointer: {
9445 CCEDiag(E, diag::note_constexpr_invalid_cast)
9446 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9447
9448 APValue Value;
9449 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
9450 break;
9451
9452 if (Value.isInt()) {
9453 unsigned Size = Info.Ctx.getTypeSize(E->getType());
9454 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
9455 Result.Base = (Expr*)nullptr;
9456 Result.InvalidBase = false;
9457 Result.Offset = CharUnits::fromQuantity(N);
9458 Result.Designator.setInvalid();
9459 Result.IsNullPtr = false;
9460 return true;
9461 } else {
9462 // In rare instances, the value isn't an lvalue.
9463 // For example, when the value is the difference between the addresses of
9464 // two labels. We reject that as a constant expression because we can't
9465 // compute a valid offset to convert into a pointer.
9466 if (!Value.isLValue())
9467 return false;
9468
9469 // Cast is of an lvalue, no need to change value.
9470 Result.setFrom(Info.Ctx, Value);
9471 return true;
9472 }
9473 }
9474
9475 case CK_ArrayToPointerDecay: {
9476 if (SubExpr->isGLValue()) {
9477 if (!evaluateLValue(SubExpr, Result))
9478 return false;
9479 } else {
9480 APValue &Value = Info.CurrentCall->createTemporary(
9481 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
9482 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
9483 return false;
9484 }
9485 // The result is a pointer to the first element of the array.
9486 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
9487 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
9488 Result.addArray(Info, E, CAT);
9489 else
9490 Result.addUnsizedArray(Info, E, AT->getElementType());
9491 return true;
9492 }
9493
9494 case CK_FunctionToPointerDecay:
9495 return evaluateLValue(SubExpr, Result);
9496
9497 case CK_LValueToRValue: {
9498 LValue LVal;
9499 if (!evaluateLValue(E->getSubExpr(), LVal))
9500 return false;
9501
9502 APValue RVal;
9503 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9504 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9505 LVal, RVal))
9506 return InvalidBaseOK &&
9507 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9508 return Success(RVal, E);
9509 }
9510 }
9511
9512 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9513}
9514
9515static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
9516 UnaryExprOrTypeTrait ExprKind) {
9517 // C++ [expr.alignof]p3:
9518 // When alignof is applied to a reference type, the result is the
9519 // alignment of the referenced type.
9520 T = T.getNonReferenceType();
9521
9522 if (T.getQualifiers().hasUnaligned())
9523 return CharUnits::One();
9524
9525 const bool AlignOfReturnsPreferred =
9526 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9527
9528 // __alignof is defined to return the preferred alignment.
9529 // Before 8, clang returned the preferred alignment for alignof and _Alignof
9530 // as well.
9531 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9532 return Info.Ctx.toCharUnitsFromBits(
9533 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
9534 // alignof and _Alignof are defined to return the ABI alignment.
9535 else if (ExprKind == UETT_AlignOf)
9536 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
9537 else
9538 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9539}
9540
9541static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
9542 UnaryExprOrTypeTrait ExprKind) {
9543 E = E->IgnoreParens();
9544
9545 // The kinds of expressions that we have special-case logic here for
9546 // should be kept up to date with the special checks for those
9547 // expressions in Sema.
9548
9549 // alignof decl is always accepted, even if it doesn't make sense: we default
9550 // to 1 in those cases.
9551 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9552 return Info.Ctx.getDeclAlign(DRE->getDecl(),
9553 /*RefAsPointee*/true);
9554
9555 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9556 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
9557 /*RefAsPointee*/true);
9558
9559 return GetAlignOfType(Info, E->getType(), ExprKind);
9560}
9561
9562static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9563 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9564 return Info.Ctx.getDeclAlign(VD);
9565 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9566 return GetAlignOfExpr(Info, E, UETT_AlignOf);
9567 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
9568}
9569
9570/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9571/// __builtin_is_aligned and __builtin_assume_aligned.
9572static bool getAlignmentArgument(const Expr *E, QualType ForType,
9573 EvalInfo &Info, APSInt &Alignment) {
9574 if (!EvaluateInteger(E, Alignment, Info))
9575 return false;
9576 if (Alignment < 0 || !Alignment.isPowerOf2()) {
9577 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9578 return false;
9579 }
9580 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9581 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9582 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9583 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9584 << MaxValue << ForType << Alignment;
9585 return false;
9586 }
9587 // Ensure both alignment and source value have the same bit width so that we
9588 // don't assert when computing the resulting value.
9589 APSInt ExtAlignment =
9590 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9591 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9592 "Alignment should not be changed by ext/trunc");
9593 Alignment = ExtAlignment;
9594 assert(Alignment.getBitWidth() == SrcWidth);
9595 return true;
9596}
9597
9598// To be clear: this happily visits unsupported builtins. Better name welcomed.
9599bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9600 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9601 return true;
9602
9603 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9604 return false;
9605
9606 Result.setInvalid(E);
9607 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9608 Result.addUnsizedArray(Info, E, PointeeTy);
9609 return true;
9610}
9611
9612bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9613 if (!IsConstantEvaluatedBuiltinCall(E))
9614 return visitNonBuiltinCallExpr(E);
9615 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9616}
9617
9618// Determine if T is a character type for which we guarantee that
9619// sizeof(T) == 1.
9621 return T->isCharType() || T->isChar8Type();
9622}
9623
9624bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9625 unsigned BuiltinOp) {
9626 if (IsNoOpCall(E))
9627 return Success(E);
9628
9629 switch (BuiltinOp) {
9630 case Builtin::BIaddressof:
9631 case Builtin::BI__addressof:
9632 case Builtin::BI__builtin_addressof:
9633 return evaluateLValue(E->getArg(0), Result);
9634 case Builtin::BI__builtin_assume_aligned: {
9635 // We need to be very careful here because: if the pointer does not have the
9636 // asserted alignment, then the behavior is undefined, and undefined
9637 // behavior is non-constant.
9638 if (!evaluatePointer(E->getArg(0), Result))
9639 return false;
9640
9641 LValue OffsetResult(Result);
9642 APSInt Alignment;
9643 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9644 Alignment))
9645 return false;
9646 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9647
9648 if (E->getNumArgs() > 2) {
9649 APSInt Offset;
9650 if (!EvaluateInteger(E->getArg(2), Offset, Info))
9651 return false;
9652
9653 int64_t AdditionalOffset = -Offset.getZExtValue();
9654 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9655 }
9656
9657 // If there is a base object, then it must have the correct alignment.
9658 if (OffsetResult.Base) {
9659 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9660
9661 if (BaseAlignment < Align) {
9662 Result.Designator.setInvalid();
9663 // FIXME: Add support to Diagnostic for long / long long.
9664 CCEDiag(E->getArg(0),
9665 diag::note_constexpr_baa_insufficient_alignment) << 0
9666 << (unsigned)BaseAlignment.getQuantity()
9667 << (unsigned)Align.getQuantity();
9668 return false;
9669 }
9670 }
9671
9672 // The offset must also have the correct alignment.
9673 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9674 Result.Designator.setInvalid();
9675
9676 (OffsetResult.Base
9677 ? CCEDiag(E->getArg(0),
9678 diag::note_constexpr_baa_insufficient_alignment) << 1
9679 : CCEDiag(E->getArg(0),
9680 diag::note_constexpr_baa_value_insufficient_alignment))
9681 << (int)OffsetResult.Offset.getQuantity()
9682 << (unsigned)Align.getQuantity();
9683 return false;
9684 }
9685
9686 return true;
9687 }
9688 case Builtin::BI__builtin_align_up:
9689 case Builtin::BI__builtin_align_down: {
9690 if (!evaluatePointer(E->getArg(0), Result))
9691 return false;
9692 APSInt Alignment;
9693 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9694 Alignment))
9695 return false;
9696 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9697 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9698 // For align_up/align_down, we can return the same value if the alignment
9699 // is known to be greater or equal to the requested value.
9700 if (PtrAlign.getQuantity() >= Alignment)
9701 return true;
9702
9703 // The alignment could be greater than the minimum at run-time, so we cannot
9704 // infer much about the resulting pointer value. One case is possible:
9705 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9706 // can infer the correct index if the requested alignment is smaller than
9707 // the base alignment so we can perform the computation on the offset.
9708 if (BaseAlignment.getQuantity() >= Alignment) {
9709 assert(Alignment.getBitWidth() <= 64 &&
9710 "Cannot handle > 64-bit address-space");
9711 uint64_t Alignment64 = Alignment.getZExtValue();
9713 BuiltinOp == Builtin::BI__builtin_align_down
9714 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9715 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9716 Result.adjustOffset(NewOffset - Result.Offset);
9717 // TODO: diagnose out-of-bounds values/only allow for arrays?
9718 return true;
9719 }
9720 // Otherwise, we cannot constant-evaluate the result.
9721 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9722 << Alignment;
9723 return false;
9724 }
9725 case Builtin::BI__builtin_operator_new:
9726 return HandleOperatorNewCall(Info, E, Result);
9727 case Builtin::BI__builtin_launder:
9728 return evaluatePointer(E->getArg(0), Result);
9729 case Builtin::BIstrchr:
9730 case Builtin::BIwcschr:
9731 case Builtin::BImemchr:
9732 case Builtin::BIwmemchr:
9733 if (Info.getLangOpts().CPlusPlus11)
9734 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9735 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9736 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9737 else
9738 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9739 [[fallthrough]];
9740 case Builtin::BI__builtin_strchr:
9741 case Builtin::BI__builtin_wcschr:
9742 case Builtin::BI__builtin_memchr:
9743 case Builtin::BI__builtin_char_memchr:
9744 case Builtin::BI__builtin_wmemchr: {
9745 if (!Visit(E->getArg(0)))
9746 return false;
9747 APSInt Desired;
9748 if (!EvaluateInteger(E->getArg(1), Desired, Info))
9749 return false;
9750 uint64_t MaxLength = uint64_t(-1);
9751 if (BuiltinOp != Builtin::BIstrchr &&
9752 BuiltinOp != Builtin::BIwcschr &&
9753 BuiltinOp != Builtin::BI__builtin_strchr &&
9754 BuiltinOp != Builtin::BI__builtin_wcschr) {
9755 APSInt N;
9756 if (!EvaluateInteger(E->getArg(2), N, Info))
9757 return false;
9758 MaxLength = N.getZExtValue();
9759 }
9760 // We cannot find the value if there are no candidates to match against.
9761 if (MaxLength == 0u)
9762 return ZeroInitialization(E);
9763 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9764 Result.Designator.Invalid)
9765 return false;
9766 QualType CharTy = Result.Designator.getType(Info.Ctx);
9767 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9768 BuiltinOp == Builtin::BI__builtin_memchr;
9769 assert(IsRawByte ||
9770 Info.Ctx.hasSameUnqualifiedType(
9771 CharTy, E->getArg(0)->getType()->getPointeeType()));
9772 // Pointers to const void may point to objects of incomplete type.
9773 if (IsRawByte && CharTy->isIncompleteType()) {
9774 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9775 return false;
9776 }
9777 // Give up on byte-oriented matching against multibyte elements.
9778 // FIXME: We can compare the bytes in the correct order.
9779 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9780 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9781 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
9782 << CharTy;
9783 return false;
9784 }
9785 // Figure out what value we're actually looking for (after converting to
9786 // the corresponding unsigned type if necessary).
9787 uint64_t DesiredVal;
9788 bool StopAtNull = false;
9789 switch (BuiltinOp) {
9790 case Builtin::BIstrchr:
9791 case Builtin::BI__builtin_strchr:
9792 // strchr compares directly to the passed integer, and therefore
9793 // always fails if given an int that is not a char.
9794 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9795 E->getArg(1)->getType(),
9796 Desired),
9797 Desired))
9798 return ZeroInitialization(E);
9799 StopAtNull = true;
9800 [[fallthrough]];
9801 case Builtin::BImemchr:
9802 case Builtin::BI__builtin_memchr:
9803 case Builtin::BI__builtin_char_memchr:
9804 // memchr compares by converting both sides to unsigned char. That's also
9805 // correct for strchr if we get this far (to cope with plain char being
9806 // unsigned in the strchr case).
9807 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9808 break;
9809
9810 case Builtin::BIwcschr:
9811 case Builtin::BI__builtin_wcschr:
9812 StopAtNull = true;
9813 [[fallthrough]];
9814 case Builtin::BIwmemchr:
9815 case Builtin::BI__builtin_wmemchr:
9816 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9817 DesiredVal = Desired.getZExtValue();
9818 break;
9819 }
9820
9821 for (; MaxLength; --MaxLength) {
9822 APValue Char;
9823 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9824 !Char.isInt())
9825 return false;
9826 if (Char.getInt().getZExtValue() == DesiredVal)
9827 return true;
9828 if (StopAtNull && !Char.getInt())
9829 break;
9830 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9831 return false;
9832 }
9833 // Not found: return nullptr.
9834 return ZeroInitialization(E);
9835 }
9836
9837 case Builtin::BImemcpy:
9838 case Builtin::BImemmove:
9839 case Builtin::BIwmemcpy:
9840 case Builtin::BIwmemmove:
9841 if (Info.getLangOpts().CPlusPlus11)
9842 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9843 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9844 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9845 else
9846 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9847 [[fallthrough]];
9848 case Builtin::BI__builtin_memcpy:
9849 case Builtin::BI__builtin_memmove:
9850 case Builtin::BI__builtin_wmemcpy:
9851 case Builtin::BI__builtin_wmemmove: {
9852 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9853 BuiltinOp == Builtin::BIwmemmove ||
9854 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9855 BuiltinOp == Builtin::BI__builtin_wmemmove;
9856 bool Move = BuiltinOp == Builtin::BImemmove ||
9857 BuiltinOp == Builtin::BIwmemmove ||
9858 BuiltinOp == Builtin::BI__builtin_memmove ||
9859 BuiltinOp == Builtin::BI__builtin_wmemmove;
9860
9861 // The result of mem* is the first argument.
9862 if (!Visit(E->getArg(0)))
9863 return false;
9864 LValue Dest = Result;
9865
9866 LValue Src;
9867 if (!EvaluatePointer(E->getArg(1), Src, Info))
9868 return false;
9869
9870 APSInt N;
9871 if (!EvaluateInteger(E->getArg(2), N, Info))
9872 return false;
9873 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9874
9875 // If the size is zero, we treat this as always being a valid no-op.
9876 // (Even if one of the src and dest pointers is null.)
9877 if (!N)
9878 return true;
9879
9880 // Otherwise, if either of the operands is null, we can't proceed. Don't
9881 // try to determine the type of the copied objects, because there aren't
9882 // any.
9883 if (!Src.Base || !Dest.Base) {
9884 APValue Val;
9885 (!Src.Base ? Src : Dest).moveInto(Val);
9886 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9887 << Move << WChar << !!Src.Base
9888 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9889 return false;
9890 }
9891 if (Src.Designator.Invalid || Dest.Designator.Invalid)
9892 return false;
9893
9894 // We require that Src and Dest are both pointers to arrays of
9895 // trivially-copyable type. (For the wide version, the designator will be
9896 // invalid if the designated object is not a wchar_t.)
9897 QualType T = Dest.Designator.getType(Info.Ctx);
9898 QualType SrcT = Src.Designator.getType(Info.Ctx);
9899 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9900 // FIXME: Consider using our bit_cast implementation to support this.
9901 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9902 return false;
9903 }
9904 if (T->isIncompleteType()) {
9905 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9906 return false;
9907 }
9908 if (!T.isTriviallyCopyableType(Info.Ctx)) {
9909 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9910 return false;
9911 }
9912
9913 // Figure out how many T's we're copying.
9914 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9915 if (TSize == 0)
9916 return false;
9917 if (!WChar) {
9918 uint64_t Remainder;
9919 llvm::APInt OrigN = N;
9920 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9921 if (Remainder) {
9922 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9923 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9924 << (unsigned)TSize;
9925 return false;
9926 }
9927 }
9928
9929 // Check that the copying will remain within the arrays, just so that we
9930 // can give a more meaningful diagnostic. This implicitly also checks that
9931 // N fits into 64 bits.
9932 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9933 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9934 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9935 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9936 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9937 << toString(N, 10, /*Signed*/false);
9938 return false;
9939 }
9940 uint64_t NElems = N.getZExtValue();
9941 uint64_t NBytes = NElems * TSize;
9942
9943 // Check for overlap.
9944 int Direction = 1;
9945 if (HasSameBase(Src, Dest)) {
9946 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9947 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9948 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9949 // Dest is inside the source region.
9950 if (!Move) {
9951 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9952 return false;
9953 }
9954 // For memmove and friends, copy backwards.
9955 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9956 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9957 return false;
9958 Direction = -1;
9959 } else if (!Move && SrcOffset >= DestOffset &&
9960 SrcOffset - DestOffset < NBytes) {
9961 // Src is inside the destination region for memcpy: invalid.
9962 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9963 return false;
9964 }
9965 }
9966
9967 while (true) {
9968 APValue Val;
9969 // FIXME: Set WantObjectRepresentation to true if we're copying a
9970 // char-like type?
9971 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9972 !handleAssignment(Info, E, Dest, T, Val))
9973 return false;
9974 // Do not iterate past the last element; if we're copying backwards, that
9975 // might take us off the start of the array.
9976 if (--NElems == 0)
9977 return true;
9978 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9979 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9980 return false;
9981 }
9982 }
9983
9984 default:
9985 return false;
9986 }
9987}
9988
9989static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9990 APValue &Result, const InitListExpr *ILE,
9991 QualType AllocType);
9992static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9993 APValue &Result,
9994 const CXXConstructExpr *CCE,
9995 QualType AllocType);
9996
9997bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9998 if (!Info.getLangOpts().CPlusPlus20)
9999 Info.CCEDiag(E, diag::note_constexpr_new);
10000
10001 // We cannot speculatively evaluate a delete expression.
10002 if (Info.SpeculativeEvaluationDepth)
10003 return false;
10004
10005 FunctionDecl *OperatorNew = E->getOperatorNew();
10006
10007 bool IsNothrow = false;
10008 bool IsPlacement = false;
10009 if (OperatorNew->isReservedGlobalPlacementOperator() &&
10010 Info.CurrentCall->isStdFunction() && !E->isArray()) {
10011 // FIXME Support array placement new.
10012 assert(E->getNumPlacementArgs() == 1);
10013 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10014 return false;
10015 if (Result.Designator.Invalid)
10016 return false;
10017 IsPlacement = true;
10018 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
10019 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10020 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10021 return false;
10022 } else if (E->getNumPlacementArgs()) {
10023 // The only new-placement list we support is of the form (std::nothrow).
10024 //
10025 // FIXME: There is no restriction on this, but it's not clear that any
10026 // other form makes any sense. We get here for cases such as:
10027 //
10028 // new (std::align_val_t{N}) X(int)
10029 //
10030 // (which should presumably be valid only if N is a multiple of
10031 // alignof(int), and in any case can't be deallocated unless N is
10032 // alignof(X) and X has new-extended alignment).
10033 if (E->getNumPlacementArgs() != 1 ||
10034 !E->getPlacementArg(0)->getType()->isNothrowT())
10035 return Error(E, diag::note_constexpr_new_placement);
10036
10037 LValue Nothrow;
10038 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10039 return false;
10040 IsNothrow = true;
10041 }
10042
10043 const Expr *Init = E->getInitializer();
10044 const InitListExpr *ResizedArrayILE = nullptr;
10045 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10046 bool ValueInit = false;
10047
10048 QualType AllocType = E->getAllocatedType();
10049 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10050 const Expr *Stripped = *ArraySize;
10051 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10052 Stripped = ICE->getSubExpr())
10053 if (ICE->getCastKind() != CK_NoOp &&
10054 ICE->getCastKind() != CK_IntegralCast)
10055 break;
10056
10057 llvm::APSInt ArrayBound;
10058 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10059 return false;
10060
10061 // C++ [expr.new]p9:
10062 // The expression is erroneous if:
10063 // -- [...] its value before converting to size_t [or] applying the
10064 // second standard conversion sequence is less than zero
10065 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10066 if (IsNothrow)
10067 return ZeroInitialization(E);
10068
10069 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10070 << ArrayBound << (*ArraySize)->getSourceRange();
10071 return false;
10072 }
10073
10074 // -- its value is such that the size of the allocated object would
10075 // exceed the implementation-defined limit
10076 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10078 Info.Ctx, AllocType, ArrayBound),
10079 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10080 if (IsNothrow)
10081 return ZeroInitialization(E);
10082 return false;
10083 }
10084
10085 // -- the new-initializer is a braced-init-list and the number of
10086 // array elements for which initializers are provided [...]
10087 // exceeds the number of elements to initialize
10088 if (!Init) {
10089 // No initialization is performed.
10090 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10091 isa<ImplicitValueInitExpr>(Init)) {
10092 ValueInit = true;
10093 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10094 ResizedArrayCCE = CCE;
10095 } else {
10096 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10097 assert(CAT && "unexpected type for array initializer");
10098
10099 unsigned Bits =
10100 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10101 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10102 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10103 if (InitBound.ugt(AllocBound)) {
10104 if (IsNothrow)
10105 return ZeroInitialization(E);
10106
10107 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10108 << toString(AllocBound, 10, /*Signed=*/false)
10109 << toString(InitBound, 10, /*Signed=*/false)
10110 << (*ArraySize)->getSourceRange();
10111 return false;
10112 }
10113
10114 // If the sizes differ, we must have an initializer list, and we need
10115 // special handling for this case when we initialize.
10116 if (InitBound != AllocBound)
10117 ResizedArrayILE = cast<InitListExpr>(Init);
10118 }
10119
10120 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10121 ArraySizeModifier::Normal, 0);
10122 } else {
10123 assert(!AllocType->isArrayType() &&
10124 "array allocation with non-array new");
10125 }
10126
10127 APValue *Val;
10128 if (IsPlacement) {
10130 struct FindObjectHandler {
10131 EvalInfo &Info;
10132 const Expr *E;
10133 QualType AllocType;
10134 const AccessKinds AccessKind;
10135 APValue *Value;
10136
10137 typedef bool result_type;
10138 bool failed() { return false; }
10139 bool found(APValue &Subobj, QualType SubobjType) {
10140 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10141 // old name of the object to be used to name the new object.
10142 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
10143 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
10144 SubobjType << AllocType;
10145 return false;
10146 }
10147 Value = &Subobj;
10148 return true;
10149 }
10150 bool found(APSInt &Value, QualType SubobjType) {
10151 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10152 return false;
10153 }
10154 bool found(APFloat &Value, QualType SubobjType) {
10155 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10156 return false;
10157 }
10158 } Handler = {Info, E, AllocType, AK, nullptr};
10159
10160 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10161 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10162 return false;
10163
10164 Val = Handler.Value;
10165
10166 // [basic.life]p1:
10167 // The lifetime of an object o of type T ends when [...] the storage
10168 // which the object occupies is [...] reused by an object that is not
10169 // nested within o (6.6.2).
10170 *Val = APValue();
10171 } else {
10172 // Perform the allocation and obtain a pointer to the resulting object.
10173 Val = Info.createHeapAlloc(E, AllocType, Result);
10174 if (!Val)
10175 return false;
10176 }
10177
10178 if (ValueInit) {
10179 ImplicitValueInitExpr VIE(AllocType);
10180 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10181 return false;
10182 } else if (ResizedArrayILE) {
10183 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10184 AllocType))
10185 return false;
10186 } else if (ResizedArrayCCE) {
10187 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10188 AllocType))
10189 return false;
10190 } else if (Init) {
10191 if (!EvaluateInPlace(*Val, Info, Result, Init))
10192 return false;
10193 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10194 return false;
10195 }
10196
10197 // Array new returns a pointer to the first element, not a pointer to the
10198 // array.
10199 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10200 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10201
10202 return true;
10203}
10204//===----------------------------------------------------------------------===//
10205// Member Pointer Evaluation
10206//===----------------------------------------------------------------------===//
10207
10208namespace {
10209class MemberPointerExprEvaluator
10210 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10211 MemberPtr &Result;
10212
10213 bool Success(const ValueDecl *D) {
10214 Result = MemberPtr(D);
10215 return true;
10216 }
10217public:
10218
10219 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10220 : ExprEvaluatorBaseTy(Info), Result(Result) {}
10221
10222 bool Success(const APValue &V, const Expr *E) {
10223 Result.setFrom(V);
10224 return true;
10225 }
10226 bool ZeroInitialization(const Expr *E) {
10227 return Success((const ValueDecl*)nullptr);
10228 }
10229
10230 bool VisitCastExpr(const CastExpr *E);
10231 bool VisitUnaryAddrOf(const UnaryOperator *E);
10232};
10233} // end anonymous namespace
10234
10235static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10236 EvalInfo &Info) {
10237 assert(!E->isValueDependent());
10238 assert(E->isPRValue() && E->getType()->isMemberPointerType());
10239 return MemberPointerExprEvaluator(Info, Result).Visit(E);
10240}
10241
10242bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10243 switch (E->getCastKind()) {
10244 default:
10245 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10246
10247 case CK_NullToMemberPointer:
10248 VisitIgnoredValue(E->getSubExpr());
10249 return ZeroInitialization(E);
10250
10251 case CK_BaseToDerivedMemberPointer: {
10252 if (!Visit(E->getSubExpr()))
10253 return false;
10254 if (E->path_empty())
10255 return true;
10256 // Base-to-derived member pointer casts store the path in derived-to-base
10257 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10258 // the wrong end of the derived->base arc, so stagger the path by one class.
10259 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10260 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10261 PathI != PathE; ++PathI) {
10262 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10263 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10264 if (!Result.castToDerived(Derived))
10265 return Error(E);
10266 }
10267 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
10268 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
10269 return Error(E);
10270 return true;
10271 }
10272
10273 case CK_DerivedToBaseMemberPointer:
10274 if (!Visit(E->getSubExpr()))
10275 return false;
10276 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10277 PathE = E->path_end(); PathI != PathE; ++PathI) {
10278 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10279 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10280 if (!Result.castToBase(Base))
10281 return Error(E);
10282 }
10283 return true;
10284 }
10285}
10286
10287bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10288 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
10289 // member can be formed.
10290 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
10291}
10292
10293//===----------------------------------------------------------------------===//
10294// Record Evaluation
10295//===----------------------------------------------------------------------===//
10296
10297namespace {
10298 class RecordExprEvaluator
10299 : public ExprEvaluatorBase<RecordExprEvaluator> {
10300 const LValue &This;
10301 APValue &Result;
10302 public:
10303
10304 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
10305 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
10306
10307 bool Success(const APValue &V, const Expr *E) {
10308 Result = V;
10309 return true;
10310 }
10311 bool ZeroInitialization(const Expr *E) {
10312 return ZeroInitialization(E, E->getType());
10313 }
10314 bool ZeroInitialization(const Expr *E, QualType T);
10315
10316 bool VisitCallExpr(const CallExpr *E) {
10317 return handleCallExpr(E, Result, &This);
10318 }
10319 bool VisitCastExpr(const CastExpr *E);
10320 bool VisitInitListExpr(const InitListExpr *E);
10321 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10322 return VisitCXXConstructExpr(E, E->getType());
10323 }
10324 bool VisitLambdaExpr(const LambdaExpr *E);
10325 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
10326 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
10327 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
10328 bool VisitBinCmp(const BinaryOperator *E);
10329 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10330 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10331 ArrayRef<Expr *> Args);
10332 };
10333}
10334
10335/// Perform zero-initialization on an object of non-union class type.
10336/// C++11 [dcl.init]p5:
10337/// To zero-initialize an object or reference of type T means:
10338/// [...]
10339/// -- if T is a (possibly cv-qualified) non-union class type,
10340/// each non-static data member and each base-class subobject is
10341/// zero-initialized
10342static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
10343 const RecordDecl *RD,
10344 const LValue &This, APValue &Result) {
10345 assert(!RD->isUnion() && "Expected non-union class type");
10346 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
10347 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
10348 std::distance(RD->field_begin(), RD->field_end()));
10349
10350 if (RD->isInvalidDecl()) return false;
10351 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10352
10353 if (CD) {
10354 unsigned Index = 0;
10356 End = CD->bases_end(); I != End; ++I, ++Index) {
10357 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
10358 LValue Subobject = This;
10359 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
10360 return false;
10361 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
10362 Result.getStructBase(Index)))
10363 return false;
10364 }
10365 }
10366
10367 for (const auto *I : RD->fields()) {
10368 // -- if T is a reference type, no initialization is performed.
10369 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
10370 continue;
10371
10372 LValue Subobject = This;
10373 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
10374 return false;
10375
10376 ImplicitValueInitExpr VIE(I->getType());
10377 if (!EvaluateInPlace(
10378 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
10379 return false;
10380 }
10381
10382 return true;
10383}
10384
10385bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
10386 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
10387 if (RD->isInvalidDecl()) return false;
10388 if (RD->isUnion()) {
10389 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10390 // object's first non-static named data member is zero-initialized
10392 while (I != RD->field_end() && (*I)->isUnnamedBitField())
10393 ++I;
10394 if (I == RD->field_end()) {
10395 Result = APValue((const FieldDecl*)nullptr);
10396 return true;
10397 }
10398
10399 LValue Subobject = This;
10400 if (!HandleLValueMember(Info, E, Subobject, *I))
10401 return false;
10402 Result = APValue(*I);
10403 ImplicitValueInitExpr VIE(I->getType());
10404 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
10405 }
10406
10407 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
10408 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
10409 return false;
10410 }
10411
10412 return HandleClassZeroInitialization(Info, E, RD, This, Result);
10413}
10414
10415bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
10416 switch (E->getCastKind()) {
10417 default:
10418 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10419
10420 case CK_ConstructorConversion:
10421 return Visit(E->getSubExpr());
10422
10423 case CK_DerivedToBase:
10424 case CK_UncheckedDerivedToBase: {
10425 APValue DerivedObject;
10426 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
10427 return false;
10428 if (!DerivedObject.isStruct())
10429 return Error(E->getSubExpr());
10430
10431 // Derived-to-base rvalue conversion: just slice off the derived part.
10432 APValue *Value = &DerivedObject;
10433 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
10434 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10435 PathE = E->path_end(); PathI != PathE; ++PathI) {
10436 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10437 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10438 Value = &Value->getStructBase(getBaseIndex(RD, Base));
10439 RD = Base;
10440 }
10441 Result = *Value;
10442 return true;
10443 }
10444 }
10445}
10446
10447bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10448 if (E->isTransparent())
10449 return Visit(E->getInit(0));
10450 return VisitCXXParenListOrInitListExpr(E, E->inits());
10451}
10452
10453bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10454 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
10455 const RecordDecl *RD =
10456 ExprToVisit->getType()->castAs<RecordType>()->getDecl();
10457 if (RD->isInvalidDecl()) return false;
10458 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10459 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
10460
10461 EvalInfo::EvaluatingConstructorRAII EvalObj(
10462 Info,
10463 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
10464 CXXRD && CXXRD->getNumBases());
10465
10466 if (RD->isUnion()) {
10467 const FieldDecl *Field;
10468 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
10469 Field = ILE->getInitializedFieldInUnion();
10470 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
10471 Field = PLIE->getInitializedFieldInUnion();
10472 } else {
10473 llvm_unreachable(
10474 "Expression is neither an init list nor a C++ paren list");
10475 }
10476
10477 Result = APValue(Field);
10478 if (!Field)
10479 return true;
10480
10481 // If the initializer list for a union does not contain any elements, the
10482 // first element of the union is value-initialized.
10483 // FIXME: The element should be initialized from an initializer list.
10484 // Is this difference ever observable for initializer lists which
10485 // we don't build?
10486 ImplicitValueInitExpr VIE(Field->getType());
10487 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
10488
10489 LValue Subobject = This;
10490 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
10491 return false;
10492
10493 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10494 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10495 isa<CXXDefaultInitExpr>(InitExpr));
10496
10497 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10498 if (Field->isBitField())
10499 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10500 Field);
10501 return true;
10502 }
10503
10504 return false;
10505 }
10506
10507 if (!Result.hasValue())
10508 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10509 std::distance(RD->field_begin(), RD->field_end()));
10510 unsigned ElementNo = 0;
10511 bool Success = true;
10512
10513 // Initialize base classes.
10514 if (CXXRD && CXXRD->getNumBases()) {
10515 for (const auto &Base : CXXRD->bases()) {
10516 assert(ElementNo < Args.size() && "missing init for base class");
10517 const Expr *Init = Args[ElementNo];
10518
10519 LValue Subobject = This;
10520 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10521 return false;
10522
10523 APValue &FieldVal = Result.getStructBase(ElementNo);
10524 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10525 if (!Info.noteFailure())
10526 return false;
10527 Success = false;
10528 }
10529 ++ElementNo;
10530 }
10531
10532 EvalObj.finishedConstructingBases();
10533 }
10534
10535 // Initialize members.
10536 for (const auto *Field : RD->fields()) {
10537 // Anonymous bit-fields are not considered members of the class for
10538 // purposes of aggregate initialization.
10539 if (Field->isUnnamedBitField())
10540 continue;
10541
10542 LValue Subobject = This;
10543
10544 bool HaveInit = ElementNo < Args.size();
10545
10546 // FIXME: Diagnostics here should point to the end of the initializer
10547 // list, not the start.
10548 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10549 Subobject, Field, &Layout))
10550 return false;
10551
10552 // Perform an implicit value-initialization for members beyond the end of
10553 // the initializer list.
10554 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10555 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10556
10557 if (Field->getType()->isIncompleteArrayType()) {
10558 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10559 if (!CAT->isZeroSize()) {
10560 // Bail out for now. This might sort of "work", but the rest of the
10561 // code isn't really prepared to handle it.
10562 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10563 return false;
10564 }
10565 }
10566 }
10567
10568 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10569 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10570 isa<CXXDefaultInitExpr>(Init));
10571
10572 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10573 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10574 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10575 FieldVal, Field))) {
10576 if (!Info.noteFailure())
10577 return false;
10578 Success = false;
10579 }
10580 }
10581
10582 EvalObj.finishedConstructingFields();
10583
10584 return Success;
10585}
10586
10587bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10588 QualType T) {
10589 // Note that E's type is not necessarily the type of our class here; we might
10590 // be initializing an array element instead.
10591 const CXXConstructorDecl *FD = E->getConstructor();
10592 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10593
10594 bool ZeroInit = E->requiresZeroInitialization();
10595 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10596 // If we've already performed zero-initialization, we're already done.
10597 if (Result.hasValue())
10598 return true;
10599
10600 if (ZeroInit)
10601 return ZeroInitialization(E, T);
10602
10603 return handleDefaultInitValue(T, Result);
10604 }
10605
10606 const FunctionDecl *Definition = nullptr;
10607 auto Body = FD->getBody(Definition);
10608
10609 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10610 return false;
10611
10612 // Avoid materializing a temporary for an elidable copy/move constructor.
10613 if (E->isElidable() && !ZeroInit) {
10614 // FIXME: This only handles the simplest case, where the source object
10615 // is passed directly as the first argument to the constructor.
10616 // This should also handle stepping though implicit casts and
10617 // and conversion sequences which involve two steps, with a
10618 // conversion operator followed by a converting constructor.
10619 const Expr *SrcObj = E->getArg(0);
10620 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10621 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10622 if (const MaterializeTemporaryExpr *ME =
10623 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10624 return Visit(ME->getSubExpr());
10625 }
10626
10627 if (ZeroInit && !ZeroInitialization(E, T))
10628 return false;
10629
10630 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
10631 return HandleConstructorCall(E, This, Args,
10632 cast<CXXConstructorDecl>(Definition), Info,
10633 Result);
10634}
10635
10636bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10637 const CXXInheritedCtorInitExpr *E) {
10638 if (!Info.CurrentCall) {
10639 assert(Info.checkingPotentialConstantExpression());
10640 return false;
10641 }
10642
10643 const CXXConstructorDecl *FD = E->getConstructor();
10644 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10645 return false;
10646
10647 const FunctionDecl *Definition = nullptr;
10648 auto Body = FD->getBody(Definition);
10649
10650 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10651 return false;
10652
10653 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10654 cast<CXXConstructorDecl>(Definition), Info,
10655 Result);
10656}
10657
10658bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10661 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10662
10663 LValue Array;
10664 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10665 return false;
10666
10667 assert(ArrayType && "unexpected type for array initializer");
10668
10669 // Get a pointer to the first element of the array.
10670 Array.addArray(Info, E, ArrayType);
10671
10672 // FIXME: What if the initializer_list type has base classes, etc?
10673 Result = APValue(APValue::UninitStruct(), 0, 2);
10674 Array.moveInto(Result.getStructField(0));
10675
10676 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10677 RecordDecl::field_iterator Field = Record->field_begin();
10678 assert(Field != Record->field_end() &&
10679 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10681 "Expected std::initializer_list first field to be const E *");
10682 ++Field;
10683 assert(Field != Record->field_end() &&
10684 "Expected std::initializer_list to have two fields");
10685
10686 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
10687 // Length.
10688 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10689 } else {
10690 // End pointer.
10691 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10693 "Expected std::initializer_list second field to be const E *");
10694 if (!HandleLValueArrayAdjustment(Info, E, Array,
10696 ArrayType->getZExtSize()))
10697 return false;
10698 Array.moveInto(Result.getStructField(1));
10699 }
10700
10701 assert(++Field == Record->field_end() &&
10702 "Expected std::initializer_list to only have two fields");
10703
10704 return true;
10705}
10706
10707bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10708 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10709 if (ClosureClass->isInvalidDecl())
10710 return false;
10711
10712 const size_t NumFields =
10713 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10714
10715 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10716 E->capture_init_end()) &&
10717 "The number of lambda capture initializers should equal the number of "
10718 "fields within the closure type");
10719
10720 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10721 // Iterate through all the lambda's closure object's fields and initialize
10722 // them.
10723 auto *CaptureInitIt = E->capture_init_begin();
10724 bool Success = true;
10725 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10726 for (const auto *Field : ClosureClass->fields()) {
10727 assert(CaptureInitIt != E->capture_init_end());
10728 // Get the initializer for this field
10729 Expr *const CurFieldInit = *CaptureInitIt++;
10730
10731 // If there is no initializer, either this is a VLA or an error has
10732 // occurred.
10733 if (!CurFieldInit)
10734 return Error(E);
10735
10736 LValue Subobject = This;
10737
10738 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10739 return false;
10740
10741 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10742 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10743 if (!Info.keepEvaluatingAfterFailure())
10744 return false;
10745 Success = false;
10746 }
10747 }
10748 return Success;
10749}
10750
10751static bool EvaluateRecord(const Expr *E, const LValue &This,
10752 APValue &Result, EvalInfo &Info) {
10753 assert(!E->isValueDependent());
10754 assert(E->isPRValue() && E->getType()->isRecordType() &&
10755 "can't evaluate expression as a record rvalue");
10756 return RecordExprEvaluator(Info, This, Result).Visit(E);
10757}
10758
10759//===----------------------------------------------------------------------===//
10760// Temporary Evaluation
10761//
10762// Temporaries are represented in the AST as rvalues, but generally behave like
10763// lvalues. The full-object of which the temporary is a subobject is implicitly
10764// materialized so that a reference can bind to it.
10765//===----------------------------------------------------------------------===//
10766namespace {
10767class TemporaryExprEvaluator
10768 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10769public:
10770 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10771 LValueExprEvaluatorBaseTy(Info, Result, false) {}
10772
10773 /// Visit an expression which constructs the value of this temporary.
10774 bool VisitConstructExpr(const Expr *E) {
10775 APValue &Value = Info.CurrentCall->createTemporary(
10776 E, E->getType(), ScopeKind::FullExpression, Result);
10777 return EvaluateInPlace(Value, Info, Result, E);
10778 }
10779
10780 bool VisitCastExpr(const CastExpr *E) {
10781 switch (E->getCastKind()) {
10782 default:
10783 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10784
10785 case CK_ConstructorConversion:
10786 return VisitConstructExpr(E->getSubExpr());
10787 }
10788 }
10789 bool VisitInitListExpr(const InitListExpr *E) {
10790 return VisitConstructExpr(E);
10791 }
10792 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10793 return VisitConstructExpr(E);
10794 }
10795 bool VisitCallExpr(const CallExpr *E) {
10796 return VisitConstructExpr(E);
10797 }
10798 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10799 return VisitConstructExpr(E);
10800 }
10801 bool VisitLambdaExpr(const LambdaExpr *E) {
10802 return VisitConstructExpr(E);
10803 }
10804};
10805} // end anonymous namespace
10806
10807/// Evaluate an expression of record type as a temporary.
10808static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10809 assert(!E->isValueDependent());
10810 assert(E->isPRValue() && E->getType()->isRecordType());
10811 return TemporaryExprEvaluator(Info, Result).Visit(E);
10812}
10813
10814//===----------------------------------------------------------------------===//
10815// Vector Evaluation
10816//===----------------------------------------------------------------------===//
10817
10818namespace {
10819 class VectorExprEvaluator
10820 : public ExprEvaluatorBase<VectorExprEvaluator> {
10821 APValue &Result;
10822 public:
10823
10824 VectorExprEvaluator(EvalInfo &info, APValue &Result)
10825 : ExprEvaluatorBaseTy(info), Result(Result) {}
10826
10827 bool Success(ArrayRef<APValue> V, const Expr *E) {
10828 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10829 // FIXME: remove this APValue copy.
10830 Result = APValue(V.data(), V.size());
10831 return true;
10832 }
10833 bool Success(const APValue &V, const Expr *E) {
10834 assert(V.isVector());
10835 Result = V;
10836 return true;
10837 }
10838 bool ZeroInitialization(const Expr *E);
10839
10840 bool VisitUnaryReal(const UnaryOperator *E)
10841 { return Visit(E->getSubExpr()); }
10842 bool VisitCastExpr(const CastExpr* E);
10843 bool VisitInitListExpr(const InitListExpr *E);
10844 bool VisitUnaryImag(const UnaryOperator *E);
10845 bool VisitBinaryOperator(const BinaryOperator *E);
10846 bool VisitUnaryOperator(const UnaryOperator *E);
10847 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
10848 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
10849
10850 // FIXME: Missing: conditional operator (for GNU
10851 // conditional select), ExtVectorElementExpr
10852 };
10853} // end anonymous namespace
10854
10855static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10856 assert(E->isPRValue() && E->getType()->isVectorType() &&
10857 "not a vector prvalue");
10858 return VectorExprEvaluator(Info, Result).Visit(E);
10859}
10860
10861bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10862 const VectorType *VTy = E->getType()->castAs<VectorType>();
10863 unsigned NElts = VTy->getNumElements();
10864
10865 const Expr *SE = E->getSubExpr();
10866 QualType SETy = SE->getType();
10867
10868 switch (E->getCastKind()) {
10869 case CK_VectorSplat: {
10870 APValue Val = APValue();
10871 if (SETy->isIntegerType()) {
10872 APSInt IntResult;
10873 if (!EvaluateInteger(SE, IntResult, Info))
10874 return false;
10875 Val = APValue(std::move(IntResult));
10876 } else if (SETy->isRealFloatingType()) {
10877 APFloat FloatResult(0.0);
10878 if (!EvaluateFloat(SE, FloatResult, Info))
10879 return false;
10880 Val = APValue(std::move(FloatResult));
10881 } else {
10882 return Error(E);
10883 }
10884
10885 // Splat and create vector APValue.
10886 SmallVector<APValue, 4> Elts(NElts, Val);
10887 return Success(Elts, E);
10888 }
10889 case CK_BitCast: {
10890 APValue SVal;
10891 if (!Evaluate(SVal, Info, SE))
10892 return false;
10893
10894 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
10895 // Give up if the input isn't an int, float, or vector. For example, we
10896 // reject "(v4i16)(intptr_t)&a".
10897 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
10898 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
10899 return false;
10900 }
10901
10902 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
10903 return false;
10904
10905 return true;
10906 }
10907 default:
10908 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10909 }
10910}
10911
10912bool
10913VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10914 const VectorType *VT = E->getType()->castAs<VectorType>();
10915 unsigned NumInits = E->getNumInits();
10916 unsigned NumElements = VT->getNumElements();
10917
10918 QualType EltTy = VT->getElementType();
10919 SmallVector<APValue, 4> Elements;
10920
10921 // The number of initializers can be less than the number of
10922 // vector elements. For OpenCL, this can be due to nested vector
10923 // initialization. For GCC compatibility, missing trailing elements
10924 // should be initialized with zeroes.
10925 unsigned CountInits = 0, CountElts = 0;
10926 while (CountElts < NumElements) {
10927 // Handle nested vector initialization.
10928 if (CountInits < NumInits
10929 && E->getInit(CountInits)->getType()->isVectorType()) {
10930 APValue v;
10931 if (!EvaluateVector(E->getInit(CountInits), v, Info))
10932 return Error(E);
10933 unsigned vlen = v.getVectorLength();
10934 for (unsigned j = 0; j < vlen; j++)
10935 Elements.push_back(v.getVectorElt(j));
10936 CountElts += vlen;
10937 } else if (EltTy->isIntegerType()) {
10938 llvm::APSInt sInt(32);
10939 if (CountInits < NumInits) {
10940 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10941 return false;
10942 } else // trailing integer zero.
10943 sInt = Info.Ctx.MakeIntValue(0, EltTy);
10944 Elements.push_back(APValue(sInt));
10945 CountElts++;
10946 } else {
10947 llvm::APFloat f(0.0);
10948 if (CountInits < NumInits) {
10949 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10950 return false;
10951 } else // trailing float zero.
10952 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10953 Elements.push_back(APValue(f));
10954 CountElts++;
10955 }
10956 CountInits++;
10957 }
10958 return Success(Elements, E);
10959}
10960
10961bool
10962VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10963 const auto *VT = E->getType()->castAs<VectorType>();
10964 QualType EltTy = VT->getElementType();
10965 APValue ZeroElement;
10966 if (EltTy->isIntegerType())
10967 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10968 else
10969 ZeroElement =
10970 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10971
10972 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10973 return Success(Elements, E);
10974}
10975
10976bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10977 VisitIgnoredValue(E->getSubExpr());
10978 return ZeroInitialization(E);
10979}
10980
10981bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10982 BinaryOperatorKind Op = E->getOpcode();
10983 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10984 "Operation not supported on vector types");
10985
10986 if (Op == BO_Comma)
10987 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10988
10989 Expr *LHS = E->getLHS();
10990 Expr *RHS = E->getRHS();
10991
10992 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10993 "Must both be vector types");
10994 // Checking JUST the types are the same would be fine, except shifts don't
10995 // need to have their types be the same (since you always shift by an int).
10996 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10998 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11000 "All operands must be the same size.");
11001
11002 APValue LHSValue;
11003 APValue RHSValue;
11004 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11005 if (!LHSOK && !Info.noteFailure())
11006 return false;
11007 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11008 return false;
11009
11010 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11011 return false;
11012
11013 return Success(LHSValue, E);
11014}
11015
11016static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11017 QualType ResultTy,
11019 APValue Elt) {
11020 switch (Op) {
11021 case UO_Plus:
11022 // Nothing to do here.
11023 return Elt;
11024 case UO_Minus:
11025 if (Elt.getKind() == APValue::Int) {
11026 Elt.getInt().negate();
11027 } else {
11028 assert(Elt.getKind() == APValue::Float &&
11029 "Vector can only be int or float type");
11030 Elt.getFloat().changeSign();
11031 }
11032 return Elt;
11033 case UO_Not:
11034 // This is only valid for integral types anyway, so we don't have to handle
11035 // float here.
11036 assert(Elt.getKind() == APValue::Int &&
11037 "Vector operator ~ can only be int");
11038 Elt.getInt().flipAllBits();
11039 return Elt;
11040 case UO_LNot: {
11041 if (Elt.getKind() == APValue::Int) {
11042 Elt.getInt() = !Elt.getInt();
11043 // operator ! on vectors returns -1 for 'truth', so negate it.
11044 Elt.getInt().negate();
11045 return Elt;
11046 }
11047 assert(Elt.getKind() == APValue::Float &&
11048 "Vector can only be int or float type");
11049 // Float types result in an int of the same size, but -1 for true, or 0 for
11050 // false.
11051 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11052 ResultTy->isUnsignedIntegerType()};
11053 if (Elt.getFloat().isZero())
11054 EltResult.setAllBits();
11055 else
11056 EltResult.clearAllBits();
11057
11058 return APValue{EltResult};
11059 }
11060 default:
11061 // FIXME: Implement the rest of the unary operators.
11062 return std::nullopt;
11063 }
11064}
11065
11066bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11067 Expr *SubExpr = E->getSubExpr();
11068 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11069 // This result element type differs in the case of negating a floating point
11070 // vector, since the result type is the a vector of the equivilant sized
11071 // integer.
11072 const QualType ResultEltTy = VD->getElementType();
11073 UnaryOperatorKind Op = E->getOpcode();
11074
11075 APValue SubExprValue;
11076 if (!Evaluate(SubExprValue, Info, SubExpr))
11077 return false;
11078
11079 // FIXME: This vector evaluator someday needs to be changed to be LValue
11080 // aware/keep LValue information around, rather than dealing with just vector
11081 // types directly. Until then, we cannot handle cases where the operand to
11082 // these unary operators is an LValue. The only case I've been able to see
11083 // cause this is operator++ assigning to a member expression (only valid in
11084 // altivec compilations) in C mode, so this shouldn't limit us too much.
11085 if (SubExprValue.isLValue())
11086 return false;
11087
11088 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11089 "Vector length doesn't match type?");
11090
11091 SmallVector<APValue, 4> ResultElements;
11092 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
11093 std::optional<APValue> Elt = handleVectorUnaryOperator(
11094 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
11095 if (!Elt)
11096 return false;
11097 ResultElements.push_back(*Elt);
11098 }
11099 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11100}
11101
11102static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
11103 const Expr *E, QualType SourceTy,
11104 QualType DestTy, APValue const &Original,
11105 APValue &Result) {
11106 if (SourceTy->isIntegerType()) {
11107 if (DestTy->isRealFloatingType()) {
11108 Result = APValue(APFloat(0.0));
11109 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
11110 DestTy, Result.getFloat());
11111 }
11112 if (DestTy->isIntegerType()) {
11113 Result = APValue(
11114 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
11115 return true;
11116 }
11117 } else if (SourceTy->isRealFloatingType()) {
11118 if (DestTy->isRealFloatingType()) {
11119 Result = Original;
11120 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
11121 Result.getFloat());
11122 }
11123 if (DestTy->isIntegerType()) {
11124 Result = APValue(APSInt());
11125 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
11126 DestTy, Result.getInt());
11127 }
11128 }
11129
11130 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
11131 << SourceTy << DestTy;
11132 return false;
11133}
11134
11135bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
11136 APValue Source;
11137 QualType SourceVecType = E->getSrcExpr()->getType();
11138 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
11139 return false;
11140
11141 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
11142 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
11143
11144 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11145
11146 auto SourceLen = Source.getVectorLength();
11147 SmallVector<APValue, 4> ResultElements;
11148 ResultElements.reserve(SourceLen);
11149 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11150 APValue Elt;
11151 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
11152 Source.getVectorElt(EltNum), Elt))
11153 return false;
11154 ResultElements.push_back(std::move(Elt));
11155 }
11156
11157 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11158}
11159
11160static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
11161 QualType ElemType, APValue const &VecVal1,
11162 APValue const &VecVal2, unsigned EltNum,
11163 APValue &Result) {
11164 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
11165 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
11166
11167 APSInt IndexVal = E->getShuffleMaskIdx(Info.Ctx, EltNum);
11168 int64_t index = IndexVal.getExtValue();
11169 // The spec says that -1 should be treated as undef for optimizations,
11170 // but in constexpr we'd have to produce an APValue::Indeterminate,
11171 // which is prohibited from being a top-level constant value. Emit a
11172 // diagnostic instead.
11173 if (index == -1) {
11174 Info.FFDiag(
11175 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
11176 << EltNum;
11177 return false;
11178 }
11179
11180 if (index < 0 ||
11181 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
11182 llvm_unreachable("Out of bounds shuffle index");
11183
11184 if (index >= TotalElementsInInputVector1)
11185 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
11186 else
11187 Result = VecVal1.getVectorElt(index);
11188 return true;
11189}
11190
11191bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
11192 APValue VecVal1;
11193 const Expr *Vec1 = E->getExpr(0);
11194 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
11195 return false;
11196 APValue VecVal2;
11197 const Expr *Vec2 = E->getExpr(1);
11198 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
11199 return false;
11200
11201 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
11202 QualType DestElTy = DestVecTy->getElementType();
11203
11204 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
11205
11206 SmallVector<APValue, 4> ResultElements;
11207 ResultElements.reserve(TotalElementsInOutputVector);
11208 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
11209 APValue Elt;
11210 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
11211 return false;
11212 ResultElements.push_back(std::move(Elt));
11213 }
11214
11215 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11216}
11217
11218//===----------------------------------------------------------------------===//
11219// Array Evaluation
11220//===----------------------------------------------------------------------===//
11221
11222namespace {
11223 class ArrayExprEvaluator
11224 : public ExprEvaluatorBase<ArrayExprEvaluator> {
11225 const LValue &This;
11226 APValue &Result;
11227 public:
11228
11229 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
11230 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
11231
11232 bool Success(const APValue &V, const Expr *E) {
11233 assert(V.isArray() && "expected array");
11234 Result = V;
11235 return true;
11236 }
11237
11238 bool ZeroInitialization(const Expr *E) {
11239 const ConstantArrayType *CAT =
11240 Info.Ctx.getAsConstantArrayType(E->getType());
11241 if (!CAT) {
11242 if (E->getType()->isIncompleteArrayType()) {
11243 // We can be asked to zero-initialize a flexible array member; this
11244 // is represented as an ImplicitValueInitExpr of incomplete array
11245 // type. In this case, the array has zero elements.
11246 Result = APValue(APValue::UninitArray(), 0, 0);
11247 return true;
11248 }
11249 // FIXME: We could handle VLAs here.
11250 return Error(E);
11251 }
11252
11253 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
11254 if (!Result.hasArrayFiller())
11255 return true;
11256
11257 // Zero-initialize all elements.
11258 LValue Subobject = This;
11259 Subobject.addArray(Info, E, CAT);
11261 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
11262 }
11263
11264 bool VisitCallExpr(const CallExpr *E) {
11265 return handleCallExpr(E, Result, &This);
11266 }
11267 bool VisitInitListExpr(const InitListExpr *E,
11268 QualType AllocType = QualType());
11269 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
11270 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
11271 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
11272 const LValue &Subobject,
11274 bool VisitStringLiteral(const StringLiteral *E,
11275 QualType AllocType = QualType()) {
11276 expandStringLiteral(Info, E, Result, AllocType);
11277 return true;
11278 }
11279 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11280 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11281 ArrayRef<Expr *> Args,
11282 const Expr *ArrayFiller,
11283 QualType AllocType = QualType());
11284 };
11285} // end anonymous namespace
11286
11287static bool EvaluateArray(const Expr *E, const LValue &This,
11288 APValue &Result, EvalInfo &Info) {
11289 assert(!E->isValueDependent());
11290 assert(E->isPRValue() && E->getType()->isArrayType() &&
11291 "not an array prvalue");
11292 return ArrayExprEvaluator(Info, This, Result).Visit(E);
11293}
11294
11295static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
11296 APValue &Result, const InitListExpr *ILE,
11297 QualType AllocType) {
11298 assert(!ILE->isValueDependent());
11299 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
11300 "not an array prvalue");
11301 return ArrayExprEvaluator(Info, This, Result)
11302 .VisitInitListExpr(ILE, AllocType);
11303}
11304
11305static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
11306 APValue &Result,
11307 const CXXConstructExpr *CCE,
11308 QualType AllocType) {
11309 assert(!CCE->isValueDependent());
11310 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
11311 "not an array prvalue");
11312 return ArrayExprEvaluator(Info, This, Result)
11313 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
11314}
11315
11316// Return true iff the given array filler may depend on the element index.
11317static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
11318 // For now, just allow non-class value-initialization and initialization
11319 // lists comprised of them.
11320 if (isa<ImplicitValueInitExpr>(FillerExpr))
11321 return false;
11322 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
11323 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
11324 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
11325 return true;
11326 }
11327
11328 if (ILE->hasArrayFiller() &&
11329 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
11330 return true;
11331
11332 return false;
11333 }
11334 return true;
11335}
11336
11337bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
11338 QualType AllocType) {
11339 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11340 AllocType.isNull() ? E->getType() : AllocType);
11341 if (!CAT)
11342 return Error(E);
11343
11344 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
11345 // an appropriately-typed string literal enclosed in braces.
11346 if (E->isStringLiteralInit()) {
11347 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
11348 // FIXME: Support ObjCEncodeExpr here once we support it in
11349 // ArrayExprEvaluator generally.
11350 if (!SL)
11351 return Error(E);
11352 return VisitStringLiteral(SL, AllocType);
11353 }
11354 // Any other transparent list init will need proper handling of the
11355 // AllocType; we can't just recurse to the inner initializer.
11356 assert(!E->isTransparent() &&
11357 "transparent array list initialization is not string literal init?");
11358
11359 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
11360 AllocType);
11361}
11362
11363bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
11364 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
11365 QualType AllocType) {
11366 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11367 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
11368
11369 bool Success = true;
11370
11371 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
11372 "zero-initialized array shouldn't have any initialized elts");
11373 APValue Filler;
11374 if (Result.isArray() && Result.hasArrayFiller())
11375 Filler = Result.getArrayFiller();
11376
11377 unsigned NumEltsToInit = Args.size();
11378 unsigned NumElts = CAT->getZExtSize();
11379
11380 // If the initializer might depend on the array index, run it for each
11381 // array element.
11382 if (NumEltsToInit != NumElts &&
11383 MaybeElementDependentArrayFiller(ArrayFiller)) {
11384 NumEltsToInit = NumElts;
11385 } else {
11386 for (auto *Init : Args) {
11387 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
11388 NumEltsToInit += EmbedS->getDataElementCount() - 1;
11389 }
11390 if (NumEltsToInit > NumElts)
11391 NumEltsToInit = NumElts;
11392 }
11393
11394 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
11395 << NumEltsToInit << ".\n");
11396
11397 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
11398
11399 // If the array was previously zero-initialized, preserve the
11400 // zero-initialized values.
11401 if (Filler.hasValue()) {
11402 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
11403 Result.getArrayInitializedElt(I) = Filler;
11404 if (Result.hasArrayFiller())
11405 Result.getArrayFiller() = Filler;
11406 }
11407
11408 LValue Subobject = This;
11409 Subobject.addArray(Info, ExprToVisit, CAT);
11410 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
11411 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
11412 Subobject, Init) ||
11413 !HandleLValueArrayAdjustment(Info, Init, Subobject,
11414 CAT->getElementType(), 1)) {
11415 if (!Info.noteFailure())
11416 return false;
11417 Success = false;
11418 }
11419 return true;
11420 };
11421 unsigned ArrayIndex = 0;
11422 QualType DestTy = CAT->getElementType();
11423 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
11424 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
11425 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
11426 if (ArrayIndex >= NumEltsToInit)
11427 break;
11428 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
11429 StringLiteral *SL = EmbedS->getDataStringLiteral();
11430 for (unsigned I = EmbedS->getStartingElementPos(),
11431 N = EmbedS->getDataElementCount();
11432 I != EmbedS->getStartingElementPos() + N; ++I) {
11433 Value = SL->getCodeUnit(I);
11434 if (DestTy->isIntegerType()) {
11435 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
11436 } else {
11437 assert(DestTy->isFloatingType() && "unexpected type");
11438 const FPOptions FPO =
11439 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11440 APFloat FValue(0.0);
11441 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
11442 DestTy, FValue))
11443 return false;
11444 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
11445 }
11446 ArrayIndex++;
11447 }
11448 } else {
11449 if (!Eval(Init, ArrayIndex))
11450 return false;
11451 ++ArrayIndex;
11452 }
11453 }
11454
11455 if (!Result.hasArrayFiller())
11456 return Success;
11457
11458 // If we get here, we have a trivial filler, which we can just evaluate
11459 // once and splat over the rest of the array elements.
11460 assert(ArrayFiller && "no array filler for incomplete init list");
11461 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
11462 ArrayFiller) &&
11463 Success;
11464}
11465
11466bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
11467 LValue CommonLV;
11468 if (E->getCommonExpr() &&
11469 !Evaluate(Info.CurrentCall->createTemporary(
11470 E->getCommonExpr(),
11471 getStorageType(Info.Ctx, E->getCommonExpr()),
11472 ScopeKind::FullExpression, CommonLV),
11473 Info, E->getCommonExpr()->getSourceExpr()))
11474 return false;
11475
11476 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
11477
11478 uint64_t Elements = CAT->getZExtSize();
11479 Result = APValue(APValue::UninitArray(), Elements, Elements);
11480
11481 LValue Subobject = This;
11482 Subobject.addArray(Info, E, CAT);
11483
11484 bool Success = true;
11485 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
11486 // C++ [class.temporary]/5
11487 // There are four contexts in which temporaries are destroyed at a different
11488 // point than the end of the full-expression. [...] The second context is
11489 // when a copy constructor is called to copy an element of an array while
11490 // the entire array is copied [...]. In either case, if the constructor has
11491 // one or more default arguments, the destruction of every temporary created
11492 // in a default argument is sequenced before the construction of the next
11493 // array element, if any.
11494 FullExpressionRAII Scope(Info);
11495
11496 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
11497 Info, Subobject, E->getSubExpr()) ||
11498 !HandleLValueArrayAdjustment(Info, E, Subobject,
11499 CAT->getElementType(), 1)) {
11500 if (!Info.noteFailure())
11501 return false;
11502 Success = false;
11503 }
11504
11505 // Make sure we run the destructors too.
11506 Scope.destroy();
11507 }
11508
11509 return Success;
11510}
11511
11512bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
11513 return VisitCXXConstructExpr(E, This, &Result, E->getType());
11514}
11515
11516bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11517 const LValue &Subobject,
11518 APValue *Value,
11519 QualType Type) {
11520 bool HadZeroInit = Value->hasValue();
11521
11522 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
11523 unsigned FinalSize = CAT->getZExtSize();
11524
11525 // Preserve the array filler if we had prior zero-initialization.
11526 APValue Filler =
11527 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
11528 : APValue();
11529
11530 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
11531 if (FinalSize == 0)
11532 return true;
11533
11534 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
11535 Info, E->getExprLoc(), E->getConstructor(),
11536 E->requiresZeroInitialization());
11537 LValue ArrayElt = Subobject;
11538 ArrayElt.addArray(Info, E, CAT);
11539 // We do the whole initialization in two passes, first for just one element,
11540 // then for the whole array. It's possible we may find out we can't do const
11541 // init in the first pass, in which case we avoid allocating a potentially
11542 // large array. We don't do more passes because expanding array requires
11543 // copying the data, which is wasteful.
11544 for (const unsigned N : {1u, FinalSize}) {
11545 unsigned OldElts = Value->getArrayInitializedElts();
11546 if (OldElts == N)
11547 break;
11548
11549 // Expand the array to appropriate size.
11550 APValue NewValue(APValue::UninitArray(), N, FinalSize);
11551 for (unsigned I = 0; I < OldElts; ++I)
11552 NewValue.getArrayInitializedElt(I).swap(
11553 Value->getArrayInitializedElt(I));
11554 Value->swap(NewValue);
11555
11556 if (HadZeroInit)
11557 for (unsigned I = OldElts; I < N; ++I)
11558 Value->getArrayInitializedElt(I) = Filler;
11559
11560 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
11561 // If we have a trivial constructor, only evaluate it once and copy
11562 // the result into all the array elements.
11563 APValue &FirstResult = Value->getArrayInitializedElt(0);
11564 for (unsigned I = OldElts; I < FinalSize; ++I)
11565 Value->getArrayInitializedElt(I) = FirstResult;
11566 } else {
11567 for (unsigned I = OldElts; I < N; ++I) {
11568 if (!VisitCXXConstructExpr(E, ArrayElt,
11569 &Value->getArrayInitializedElt(I),
11570 CAT->getElementType()) ||
11571 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
11572 CAT->getElementType(), 1))
11573 return false;
11574 // When checking for const initilization any diagnostic is considered
11575 // an error.
11576 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
11577 !Info.keepEvaluatingAfterFailure())
11578 return false;
11579 }
11580 }
11581 }
11582
11583 return true;
11584 }
11585
11586 if (!Type->isRecordType())
11587 return Error(E);
11588
11589 return RecordExprEvaluator(Info, Subobject, *Value)
11590 .VisitCXXConstructExpr(E, Type);
11591}
11592
11593bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
11594 const CXXParenListInitExpr *E) {
11595 assert(E->getType()->isConstantArrayType() &&
11596 "Expression result is not a constant array type");
11597
11598 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
11599 E->getArrayFiller());
11600}
11601
11602//===----------------------------------------------------------------------===//
11603// Integer Evaluation
11604//
11605// As a GNU extension, we support casting pointers to sufficiently-wide integer
11606// types and back in constant folding. Integer values are thus represented
11607// either as an integer-valued APValue, or as an lvalue-valued APValue.
11608//===----------------------------------------------------------------------===//
11609
11610namespace {
11611class IntExprEvaluator
11612 : public ExprEvaluatorBase<IntExprEvaluator> {
11613 APValue &Result;
11614public:
11615 IntExprEvaluator(EvalInfo &info, APValue &result)
11616 : ExprEvaluatorBaseTy(info), Result(result) {}
11617
11618 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
11619 assert(E->getType()->isIntegralOrEnumerationType() &&
11620 "Invalid evaluation result.");
11621 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
11622 "Invalid evaluation result.");
11623 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11624 "Invalid evaluation result.");
11625 Result = APValue(SI);
11626 return true;
11627 }
11628 bool Success(const llvm::APSInt &SI, const Expr *E) {
11629 return Success(SI, E, Result);
11630 }
11631
11632 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
11633 assert(E->getType()->isIntegralOrEnumerationType() &&
11634 "Invalid evaluation result.");
11635 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11636 "Invalid evaluation result.");
11637 Result = APValue(APSInt(I));
11638 Result.getInt().setIsUnsigned(
11640 return true;
11641 }
11642 bool Success(const llvm::APInt &I, const Expr *E) {
11643 return Success(I, E, Result);
11644 }
11645
11646 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11647 assert(E->getType()->isIntegralOrEnumerationType() &&
11648 "Invalid evaluation result.");
11649 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
11650 return true;
11651 }
11652 bool Success(uint64_t Value, const Expr *E) {
11653 return Success(Value, E, Result);
11654 }
11655
11656 bool Success(CharUnits Size, const Expr *E) {
11657 return Success(Size.getQuantity(), E);
11658 }
11659
11660 bool Success(const APValue &V, const Expr *E) {
11661 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
11662 Result = V;
11663 return true;
11664 }
11665 return Success(V.getInt(), E);
11666 }
11667
11668 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
11669
11670 //===--------------------------------------------------------------------===//
11671 // Visitor Methods
11672 //===--------------------------------------------------------------------===//
11673
11674 bool VisitIntegerLiteral(const IntegerLiteral *E) {
11675 return Success(E->getValue(), E);
11676 }
11677 bool VisitCharacterLiteral(const CharacterLiteral *E) {
11678 return Success(E->getValue(), E);
11679 }
11680
11681 bool CheckReferencedDecl(const Expr *E, const Decl *D);
11682 bool VisitDeclRefExpr(const DeclRefExpr *E) {
11683 if (CheckReferencedDecl(E, E->getDecl()))
11684 return true;
11685
11686 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
11687 }
11688 bool VisitMemberExpr(const MemberExpr *E) {
11689 if (CheckReferencedDecl(E, E->getMemberDecl())) {
11690 VisitIgnoredBaseExpression(E->getBase());
11691 return true;
11692 }
11693
11694 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
11695 }
11696
11697 bool VisitCallExpr(const CallExpr *E);
11698 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
11699 bool VisitBinaryOperator(const BinaryOperator *E);
11700 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
11701 bool VisitUnaryOperator(const UnaryOperator *E);
11702
11703 bool VisitCastExpr(const CastExpr* E);
11704 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
11705
11706 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
11707 return Success(E->getValue(), E);
11708 }
11709
11710 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
11711 return Success(E->getValue(), E);
11712 }
11713
11714 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
11715 if (Info.ArrayInitIndex == uint64_t(-1)) {
11716 // We were asked to evaluate this subexpression independent of the
11717 // enclosing ArrayInitLoopExpr. We can't do that.
11718 Info.FFDiag(E);
11719 return false;
11720 }
11721 return Success(Info.ArrayInitIndex, E);
11722 }
11723
11724 // Note, GNU defines __null as an integer, not a pointer.
11725 bool VisitGNUNullExpr(const GNUNullExpr *E) {
11726 return ZeroInitialization(E);
11727 }
11728
11729 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11730 return Success(E->getValue(), E);
11731 }
11732
11733 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11734 return Success(E->getValue(), E);
11735 }
11736
11737 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11738 return Success(E->getValue(), E);
11739 }
11740
11741 bool VisitUnaryReal(const UnaryOperator *E);
11742 bool VisitUnaryImag(const UnaryOperator *E);
11743
11744 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11745 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11746 bool VisitSourceLocExpr(const SourceLocExpr *E);
11747 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11748 bool VisitRequiresExpr(const RequiresExpr *E);
11749 // FIXME: Missing: array subscript of vector, member of vector
11750};
11751
11752class FixedPointExprEvaluator
11753 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11754 APValue &Result;
11755
11756 public:
11757 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11758 : ExprEvaluatorBaseTy(info), Result(result) {}
11759
11760 bool Success(const llvm::APInt &I, const Expr *E) {
11761 return Success(
11762 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11763 }
11764
11765 bool Success(uint64_t Value, const Expr *E) {
11766 return Success(
11767 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11768 }
11769
11770 bool Success(const APValue &V, const Expr *E) {
11771 return Success(V.getFixedPoint(), E);
11772 }
11773
11774 bool Success(const APFixedPoint &V, const Expr *E) {
11775 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
11776 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11777 "Invalid evaluation result.");
11778 Result = APValue(V);
11779 return true;
11780 }
11781
11782 bool ZeroInitialization(const Expr *E) {
11783 return Success(0, E);
11784 }
11785
11786 //===--------------------------------------------------------------------===//
11787 // Visitor Methods
11788 //===--------------------------------------------------------------------===//
11789
11790 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11791 return Success(E->getValue(), E);
11792 }
11793
11794 bool VisitCastExpr(const CastExpr *E);
11795 bool VisitUnaryOperator(const UnaryOperator *E);
11796 bool VisitBinaryOperator(const BinaryOperator *E);
11797};
11798} // end anonymous namespace
11799
11800/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11801/// produce either the integer value or a pointer.
11802///
11803/// GCC has a heinous extension which folds casts between pointer types and
11804/// pointer-sized integral types. We support this by allowing the evaluation of
11805/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11806/// Some simple arithmetic on such values is supported (they are treated much
11807/// like char*).
11808static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11809 EvalInfo &Info) {
11810 assert(!E->isValueDependent());
11811 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
11812 return IntExprEvaluator(Info, Result).Visit(E);
11813}
11814
11815static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11816 assert(!E->isValueDependent());
11817 APValue Val;
11818 if (!EvaluateIntegerOrLValue(E, Val, Info))
11819 return false;
11820 if (!Val.isInt()) {
11821 // FIXME: It would be better to produce the diagnostic for casting
11822 // a pointer to an integer.
11823 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11824 return false;
11825 }
11826 Result = Val.getInt();
11827 return true;
11828}
11829
11830bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11831 APValue Evaluated = E->EvaluateInContext(
11832 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11833 return Success(Evaluated, E);
11834}
11835
11836static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11837 EvalInfo &Info) {
11838 assert(!E->isValueDependent());
11839 if (E->getType()->isFixedPointType()) {
11840 APValue Val;
11841 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11842 return false;
11843 if (!Val.isFixedPoint())
11844 return false;
11845
11846 Result = Val.getFixedPoint();
11847 return true;
11848 }
11849 return false;
11850}
11851
11852static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11853 EvalInfo &Info) {
11854 assert(!E->isValueDependent());
11855 if (E->getType()->isIntegerType()) {
11856 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11857 APSInt Val;
11858 if (!EvaluateInteger(E, Val, Info))
11859 return false;
11860 Result = APFixedPoint(Val, FXSema);
11861 return true;
11862 } else if (E->getType()->isFixedPointType()) {
11863 return EvaluateFixedPoint(E, Result, Info);
11864 }
11865 return false;
11866}
11867
11868/// Check whether the given declaration can be directly converted to an integral
11869/// rvalue. If not, no diagnostic is produced; there are other things we can
11870/// try.
11871bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11872 // Enums are integer constant exprs.
11873 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11874 // Check for signedness/width mismatches between E type and ECD value.
11875 bool SameSign = (ECD->getInitVal().isSigned()
11877 bool SameWidth = (ECD->getInitVal().getBitWidth()
11878 == Info.Ctx.getIntWidth(E->getType()));
11879 if (SameSign && SameWidth)
11880 return Success(ECD->getInitVal(), E);
11881 else {
11882 // Get rid of mismatch (otherwise Success assertions will fail)
11883 // by computing a new value matching the type of E.
11884 llvm::APSInt Val = ECD->getInitVal();
11885 if (!SameSign)
11886 Val.setIsSigned(!ECD->getInitVal().isSigned());
11887 if (!SameWidth)
11888 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11889 return Success(Val, E);
11890 }
11891 }
11892 return false;
11893}
11894
11895/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11896/// as GCC.
11898 const LangOptions &LangOpts) {
11899 assert(!T->isDependentType() && "unexpected dependent type");
11900
11901 QualType CanTy = T.getCanonicalType();
11902
11903 switch (CanTy->getTypeClass()) {
11904#define TYPE(ID, BASE)
11905#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11906#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11907#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11908#include "clang/AST/TypeNodes.inc"
11909 case Type::Auto:
11910 case Type::DeducedTemplateSpecialization:
11911 llvm_unreachable("unexpected non-canonical or dependent type");
11912
11913 case Type::Builtin:
11914 switch (cast<BuiltinType>(CanTy)->getKind()) {
11915#define BUILTIN_TYPE(ID, SINGLETON_ID)
11916#define SIGNED_TYPE(ID, SINGLETON_ID) \
11917 case BuiltinType::ID: return GCCTypeClass::Integer;
11918#define FLOATING_TYPE(ID, SINGLETON_ID) \
11919 case BuiltinType::ID: return GCCTypeClass::RealFloat;
11920#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11921 case BuiltinType::ID: break;
11922#include "clang/AST/BuiltinTypes.def"
11923 case BuiltinType::Void:
11924 return GCCTypeClass::Void;
11925
11926 case BuiltinType::Bool:
11927 return GCCTypeClass::Bool;
11928
11929 case BuiltinType::Char_U:
11930 case BuiltinType::UChar:
11931 case BuiltinType::WChar_U:
11932 case BuiltinType::Char8:
11933 case BuiltinType::Char16:
11934 case BuiltinType::Char32:
11935 case BuiltinType::UShort:
11936 case BuiltinType::UInt:
11937 case BuiltinType::ULong:
11938 case BuiltinType::ULongLong:
11939 case BuiltinType::UInt128:
11940 return GCCTypeClass::Integer;
11941
11942 case BuiltinType::UShortAccum:
11943 case BuiltinType::UAccum:
11944 case BuiltinType::ULongAccum:
11945 case BuiltinType::UShortFract:
11946 case BuiltinType::UFract:
11947 case BuiltinType::ULongFract:
11948 case BuiltinType::SatUShortAccum:
11949 case BuiltinType::SatUAccum:
11950 case BuiltinType::SatULongAccum:
11951 case BuiltinType::SatUShortFract:
11952 case BuiltinType::SatUFract:
11953 case BuiltinType::SatULongFract:
11954 return GCCTypeClass::None;
11955
11956 case BuiltinType::NullPtr:
11957
11958 case BuiltinType::ObjCId:
11959 case BuiltinType::ObjCClass:
11960 case BuiltinType::ObjCSel:
11961#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11962 case BuiltinType::Id:
11963#include "clang/Basic/OpenCLImageTypes.def"
11964#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11965 case BuiltinType::Id:
11966#include "clang/Basic/OpenCLExtensionTypes.def"
11967 case BuiltinType::OCLSampler:
11968 case BuiltinType::OCLEvent:
11969 case BuiltinType::OCLClkEvent:
11970 case BuiltinType::OCLQueue:
11971 case BuiltinType::OCLReserveID:
11972#define SVE_TYPE(Name, Id, SingletonId) \
11973 case BuiltinType::Id:
11974#include "clang/Basic/AArch64SVEACLETypes.def"
11975#define PPC_VECTOR_TYPE(Name, Id, Size) \
11976 case BuiltinType::Id:
11977#include "clang/Basic/PPCTypes.def"
11978#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11979#include "clang/Basic/RISCVVTypes.def"
11980#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11981#include "clang/Basic/WebAssemblyReferenceTypes.def"
11982#define AMDGPU_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11983#include "clang/Basic/AMDGPUTypes.def"
11984#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11985#include "clang/Basic/HLSLIntangibleTypes.def"
11986 return GCCTypeClass::None;
11987
11988 case BuiltinType::Dependent:
11989 llvm_unreachable("unexpected dependent type");
11990 };
11991 llvm_unreachable("unexpected placeholder type");
11992
11993 case Type::Enum:
11994 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11995
11996 case Type::Pointer:
11997 case Type::ConstantArray:
11998 case Type::VariableArray:
11999 case Type::IncompleteArray:
12000 case Type::FunctionNoProto:
12001 case Type::FunctionProto:
12002 case Type::ArrayParameter:
12003 return GCCTypeClass::Pointer;
12004
12005 case Type::MemberPointer:
12006 return CanTy->isMemberDataPointerType()
12007 ? GCCTypeClass::PointerToDataMember
12008 : GCCTypeClass::PointerToMemberFunction;
12009
12010 case Type::Complex:
12011 return GCCTypeClass::Complex;
12012
12013 case Type::Record:
12014 return CanTy->isUnionType() ? GCCTypeClass::Union
12015 : GCCTypeClass::ClassOrStruct;
12016
12017 case Type::Atomic:
12018 // GCC classifies _Atomic T the same as T.
12020 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
12021
12022 case Type::Vector:
12023 case Type::ExtVector:
12024 return GCCTypeClass::Vector;
12025
12026 case Type::BlockPointer:
12027 case Type::ConstantMatrix:
12028 case Type::ObjCObject:
12029 case Type::ObjCInterface:
12030 case Type::ObjCObjectPointer:
12031 case Type::Pipe:
12032 // Classify all other types that don't fit into the regular
12033 // classification the same way.
12034 return GCCTypeClass::None;
12035
12036 case Type::BitInt:
12037 return GCCTypeClass::BitInt;
12038
12039 case Type::LValueReference:
12040 case Type::RValueReference:
12041 llvm_unreachable("invalid type for expression");
12042 }
12043
12044 llvm_unreachable("unexpected type class");
12045}
12046
12047/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
12048/// as GCC.
12049static GCCTypeClass
12051 // If no argument was supplied, default to None. This isn't
12052 // ideal, however it is what gcc does.
12053 if (E->getNumArgs() == 0)
12054 return GCCTypeClass::None;
12055
12056 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
12057 // being an ICE, but still folds it to a constant using the type of the first
12058 // argument.
12059 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
12060}
12061
12062/// EvaluateBuiltinConstantPForLValue - Determine the result of
12063/// __builtin_constant_p when applied to the given pointer.
12064///
12065/// A pointer is only "constant" if it is null (or a pointer cast to integer)
12066/// or it points to the first character of a string literal.
12069 if (Base.isNull()) {
12070 // A null base is acceptable.
12071 return true;
12072 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
12073 if (!isa<StringLiteral>(E))
12074 return false;
12075 return LV.getLValueOffset().isZero();
12076 } else if (Base.is<TypeInfoLValue>()) {
12077 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
12078 // evaluate to true.
12079 return true;
12080 } else {
12081 // Any other base is not constant enough for GCC.
12082 return false;
12083 }
12084}
12085
12086/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
12087/// GCC as we can manage.
12088static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
12089 // This evaluation is not permitted to have side-effects, so evaluate it in
12090 // a speculative evaluation context.
12091 SpeculativeEvaluationRAII SpeculativeEval(Info);
12092
12093 // Constant-folding is always enabled for the operand of __builtin_constant_p
12094 // (even when the enclosing evaluation context otherwise requires a strict
12095 // language-specific constant expression).
12096 FoldConstant Fold(Info, true);
12097
12098 QualType ArgType = Arg->getType();
12099
12100 // __builtin_constant_p always has one operand. The rules which gcc follows
12101 // are not precisely documented, but are as follows:
12102 //
12103 // - If the operand is of integral, floating, complex or enumeration type,
12104 // and can be folded to a known value of that type, it returns 1.
12105 // - If the operand can be folded to a pointer to the first character
12106 // of a string literal (or such a pointer cast to an integral type)
12107 // or to a null pointer or an integer cast to a pointer, it returns 1.
12108 //
12109 // Otherwise, it returns 0.
12110 //
12111 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
12112 // its support for this did not work prior to GCC 9 and is not yet well
12113 // understood.
12114 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
12115 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
12116 ArgType->isNullPtrType()) {
12117 APValue V;
12118 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
12119 Fold.keepDiagnostics();
12120 return false;
12121 }
12122
12123 // For a pointer (possibly cast to integer), there are special rules.
12124 if (V.getKind() == APValue::LValue)
12126
12127 // Otherwise, any constant value is good enough.
12128 return V.hasValue();
12129 }
12130
12131 // Anything else isn't considered to be sufficiently constant.
12132 return false;
12133}
12134
12135/// Retrieves the "underlying object type" of the given expression,
12136/// as used by __builtin_object_size.
12138 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
12139 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
12140 return VD->getType();
12141 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
12142 if (isa<CompoundLiteralExpr>(E))
12143 return E->getType();
12144 } else if (B.is<TypeInfoLValue>()) {
12145 return B.getTypeInfoType();
12146 } else if (B.is<DynamicAllocLValue>()) {
12147 return B.getDynamicAllocType();
12148 }
12149
12150 return QualType();
12151}
12152
12153/// A more selective version of E->IgnoreParenCasts for
12154/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
12155/// to change the type of E.
12156/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
12157///
12158/// Always returns an RValue with a pointer representation.
12160 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
12161
12162 const Expr *NoParens = E->IgnoreParens();
12163 const auto *Cast = dyn_cast<CastExpr>(NoParens);
12164 if (Cast == nullptr)
12165 return NoParens;
12166
12167 // We only conservatively allow a few kinds of casts, because this code is
12168 // inherently a simple solution that seeks to support the common case.
12169 auto CastKind = Cast->getCastKind();
12170 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
12171 CastKind != CK_AddressSpaceConversion)
12172 return NoParens;
12173
12174 const auto *SubExpr = Cast->getSubExpr();
12175 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
12176 return NoParens;
12177 return ignorePointerCastsAndParens(SubExpr);
12178}
12179
12180/// Checks to see if the given LValue's Designator is at the end of the LValue's
12181/// record layout. e.g.
12182/// struct { struct { int a, b; } fst, snd; } obj;
12183/// obj.fst // no
12184/// obj.snd // yes
12185/// obj.fst.a // no
12186/// obj.fst.b // no
12187/// obj.snd.a // no
12188/// obj.snd.b // yes
12189///
12190/// Please note: this function is specialized for how __builtin_object_size
12191/// views "objects".
12192///
12193/// If this encounters an invalid RecordDecl or otherwise cannot determine the
12194/// correct result, it will always return true.
12195static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
12196 assert(!LVal.Designator.Invalid);
12197
12198 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
12199 const RecordDecl *Parent = FD->getParent();
12200 Invalid = Parent->isInvalidDecl();
12201 if (Invalid || Parent->isUnion())
12202 return true;
12203 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
12204 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
12205 };
12206
12207 auto &Base = LVal.getLValueBase();
12208 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
12209 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
12210 bool Invalid;
12211 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
12212 return Invalid;
12213 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
12214 for (auto *FD : IFD->chain()) {
12215 bool Invalid;
12216 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
12217 return Invalid;
12218 }
12219 }
12220 }
12221
12222 unsigned I = 0;
12223 QualType BaseType = getType(Base);
12224 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
12225 // If we don't know the array bound, conservatively assume we're looking at
12226 // the final array element.
12227 ++I;
12228 if (BaseType->isIncompleteArrayType())
12229 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
12230 else
12231 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
12232 }
12233
12234 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
12235 const auto &Entry = LVal.Designator.Entries[I];
12236 if (BaseType->isArrayType()) {
12237 // Because __builtin_object_size treats arrays as objects, we can ignore
12238 // the index iff this is the last array in the Designator.
12239 if (I + 1 == E)
12240 return true;
12241 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
12242 uint64_t Index = Entry.getAsArrayIndex();
12243 if (Index + 1 != CAT->getZExtSize())
12244 return false;
12245 BaseType = CAT->getElementType();
12246 } else if (BaseType->isAnyComplexType()) {
12247 const auto *CT = BaseType->castAs<ComplexType>();
12248 uint64_t Index = Entry.getAsArrayIndex();
12249 if (Index != 1)
12250 return false;
12251 BaseType = CT->getElementType();
12252 } else if (auto *FD = getAsField(Entry)) {
12253 bool Invalid;
12254 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
12255 return Invalid;
12256 BaseType = FD->getType();
12257 } else {
12258 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
12259 return false;
12260 }
12261 }
12262 return true;
12263}
12264
12265/// Tests to see if the LValue has a user-specified designator (that isn't
12266/// necessarily valid). Note that this always returns 'true' if the LValue has
12267/// an unsized array as its first designator entry, because there's currently no
12268/// way to tell if the user typed *foo or foo[0].
12269static bool refersToCompleteObject(const LValue &LVal) {
12270 if (LVal.Designator.Invalid)
12271 return false;
12272
12273 if (!LVal.Designator.Entries.empty())
12274 return LVal.Designator.isMostDerivedAnUnsizedArray();
12275
12276 if (!LVal.InvalidBase)
12277 return true;
12278
12279 // If `E` is a MemberExpr, then the first part of the designator is hiding in
12280 // the LValueBase.
12281 const auto *E = LVal.Base.dyn_cast<const Expr *>();
12282 return !E || !isa<MemberExpr>(E);
12283}
12284
12285/// Attempts to detect a user writing into a piece of memory that's impossible
12286/// to figure out the size of by just using types.
12287static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
12288 const SubobjectDesignator &Designator = LVal.Designator;
12289 // Notes:
12290 // - Users can only write off of the end when we have an invalid base. Invalid
12291 // bases imply we don't know where the memory came from.
12292 // - We used to be a bit more aggressive here; we'd only be conservative if
12293 // the array at the end was flexible, or if it had 0 or 1 elements. This
12294 // broke some common standard library extensions (PR30346), but was
12295 // otherwise seemingly fine. It may be useful to reintroduce this behavior
12296 // with some sort of list. OTOH, it seems that GCC is always
12297 // conservative with the last element in structs (if it's an array), so our
12298 // current behavior is more compatible than an explicit list approach would
12299 // be.
12300 auto isFlexibleArrayMember = [&] {
12302 FAMKind StrictFlexArraysLevel =
12303 Ctx.getLangOpts().getStrictFlexArraysLevel();
12304
12305 if (Designator.isMostDerivedAnUnsizedArray())
12306 return true;
12307
12308 if (StrictFlexArraysLevel == FAMKind::Default)
12309 return true;
12310
12311 if (Designator.getMostDerivedArraySize() == 0 &&
12312 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
12313 return true;
12314
12315 if (Designator.getMostDerivedArraySize() == 1 &&
12316 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
12317 return true;
12318
12319 return false;
12320 };
12321
12322 return LVal.InvalidBase &&
12323 Designator.Entries.size() == Designator.MostDerivedPathLength &&
12324 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
12325 isDesignatorAtObjectEnd(Ctx, LVal);
12326}
12327
12328/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
12329/// Fails if the conversion would cause loss of precision.
12330static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
12331 CharUnits &Result) {
12332 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
12333 if (Int.ugt(CharUnitsMax))
12334 return false;
12335 Result = CharUnits::fromQuantity(Int.getZExtValue());
12336 return true;
12337}
12338
12339/// If we're evaluating the object size of an instance of a struct that
12340/// contains a flexible array member, add the size of the initializer.
12341static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
12342 const LValue &LV, CharUnits &Size) {
12343 if (!T.isNull() && T->isStructureType() &&
12345 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
12346 if (const auto *VD = dyn_cast<VarDecl>(V))
12347 if (VD->hasInit())
12348 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
12349}
12350
12351/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
12352/// determine how many bytes exist from the beginning of the object to either
12353/// the end of the current subobject, or the end of the object itself, depending
12354/// on what the LValue looks like + the value of Type.
12355///
12356/// If this returns false, the value of Result is undefined.
12357static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
12358 unsigned Type, const LValue &LVal,
12359 CharUnits &EndOffset) {
12360 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
12361
12362 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
12363 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
12364 return false;
12365 return HandleSizeof(Info, ExprLoc, Ty, Result);
12366 };
12367
12368 // We want to evaluate the size of the entire object. This is a valid fallback
12369 // for when Type=1 and the designator is invalid, because we're asked for an
12370 // upper-bound.
12371 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
12372 // Type=3 wants a lower bound, so we can't fall back to this.
12373 if (Type == 3 && !DetermineForCompleteObject)
12374 return false;
12375
12376 llvm::APInt APEndOffset;
12377 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12378 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12379 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12380
12381 if (LVal.InvalidBase)
12382 return false;
12383
12384 QualType BaseTy = getObjectType(LVal.getLValueBase());
12385 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
12386 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
12387 return Ret;
12388 }
12389
12390 // We want to evaluate the size of a subobject.
12391 const SubobjectDesignator &Designator = LVal.Designator;
12392
12393 // The following is a moderately common idiom in C:
12394 //
12395 // struct Foo { int a; char c[1]; };
12396 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
12397 // strcpy(&F->c[0], Bar);
12398 //
12399 // In order to not break too much legacy code, we need to support it.
12400 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
12401 // If we can resolve this to an alloc_size call, we can hand that back,
12402 // because we know for certain how many bytes there are to write to.
12403 llvm::APInt APEndOffset;
12404 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12405 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12406 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12407
12408 // If we cannot determine the size of the initial allocation, then we can't
12409 // given an accurate upper-bound. However, we are still able to give
12410 // conservative lower-bounds for Type=3.
12411 if (Type == 1)
12412 return false;
12413 }
12414
12415 CharUnits BytesPerElem;
12416 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
12417 return false;
12418
12419 // According to the GCC documentation, we want the size of the subobject
12420 // denoted by the pointer. But that's not quite right -- what we actually
12421 // want is the size of the immediately-enclosing array, if there is one.
12422 int64_t ElemsRemaining;
12423 if (Designator.MostDerivedIsArrayElement &&
12424 Designator.Entries.size() == Designator.MostDerivedPathLength) {
12425 uint64_t ArraySize = Designator.getMostDerivedArraySize();
12426 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
12427 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
12428 } else {
12429 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
12430 }
12431
12432 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
12433 return true;
12434}
12435
12436/// Tries to evaluate the __builtin_object_size for @p E. If successful,
12437/// returns true and stores the result in @p Size.
12438///
12439/// If @p WasError is non-null, this will report whether the failure to evaluate
12440/// is to be treated as an Error in IntExprEvaluator.
12441static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
12442 EvalInfo &Info, uint64_t &Size) {
12443 // Determine the denoted object.
12444 LValue LVal;
12445 {
12446 // The operand of __builtin_object_size is never evaluated for side-effects.
12447 // If there are any, but we can determine the pointed-to object anyway, then
12448 // ignore the side-effects.
12449 SpeculativeEvaluationRAII SpeculativeEval(Info);
12450 IgnoreSideEffectsRAII Fold(Info);
12451
12452 if (E->isGLValue()) {
12453 // It's possible for us to be given GLValues if we're called via
12454 // Expr::tryEvaluateObjectSize.
12455 APValue RVal;
12456 if (!EvaluateAsRValue(Info, E, RVal))
12457 return false;
12458 LVal.setFrom(Info.Ctx, RVal);
12459 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
12460 /*InvalidBaseOK=*/true))
12461 return false;
12462 }
12463
12464 // If we point to before the start of the object, there are no accessible
12465 // bytes.
12466 if (LVal.getLValueOffset().isNegative()) {
12467 Size = 0;
12468 return true;
12469 }
12470
12471 CharUnits EndOffset;
12472 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
12473 return false;
12474
12475 // If we've fallen outside of the end offset, just pretend there's nothing to
12476 // write to/read from.
12477 if (EndOffset <= LVal.getLValueOffset())
12478 Size = 0;
12479 else
12480 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
12481 return true;
12482}
12483
12484bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
12485 if (!IsConstantEvaluatedBuiltinCall(E))
12486 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12487 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
12488}
12489
12490static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
12491 APValue &Val, APSInt &Alignment) {
12492 QualType SrcTy = E->getArg(0)->getType();
12493 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
12494 return false;
12495 // Even though we are evaluating integer expressions we could get a pointer
12496 // argument for the __builtin_is_aligned() case.
12497 if (SrcTy->isPointerType()) {
12498 LValue Ptr;
12499 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
12500 return false;
12501 Ptr.moveInto(Val);
12502 } else if (!SrcTy->isIntegralOrEnumerationType()) {
12503 Info.FFDiag(E->getArg(0));
12504 return false;
12505 } else {
12506 APSInt SrcInt;
12507 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
12508 return false;
12509 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
12510 "Bit widths must be the same");
12511 Val = APValue(SrcInt);
12512 }
12513 assert(Val.hasValue());
12514 return true;
12515}
12516
12517bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
12518 unsigned BuiltinOp) {
12519 switch (BuiltinOp) {
12520 default:
12521 return false;
12522
12523 case Builtin::BI__builtin_dynamic_object_size:
12524 case Builtin::BI__builtin_object_size: {
12525 // The type was checked when we built the expression.
12526 unsigned Type =
12527 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12528 assert(Type <= 3 && "unexpected type");
12529
12530 uint64_t Size;
12531 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
12532 return Success(Size, E);
12533
12534 if (E->getArg(0)->HasSideEffects(Info.Ctx))
12535 return Success((Type & 2) ? 0 : -1, E);
12536
12537 // Expression had no side effects, but we couldn't statically determine the
12538 // size of the referenced object.
12539 switch (Info.EvalMode) {
12540 case EvalInfo::EM_ConstantExpression:
12541 case EvalInfo::EM_ConstantFold:
12542 case EvalInfo::EM_IgnoreSideEffects:
12543 // Leave it to IR generation.
12544 return Error(E);
12545 case EvalInfo::EM_ConstantExpressionUnevaluated:
12546 // Reduce it to a constant now.
12547 return Success((Type & 2) ? 0 : -1, E);
12548 }
12549
12550 llvm_unreachable("unexpected EvalMode");
12551 }
12552
12553 case Builtin::BI__builtin_os_log_format_buffer_size: {
12556 return Success(Layout.size().getQuantity(), E);
12557 }
12558
12559 case Builtin::BI__builtin_is_aligned: {
12560 APValue Src;
12561 APSInt Alignment;
12562 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12563 return false;
12564 if (Src.isLValue()) {
12565 // If we evaluated a pointer, check the minimum known alignment.
12566 LValue Ptr;
12567 Ptr.setFrom(Info.Ctx, Src);
12568 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
12569 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
12570 // We can return true if the known alignment at the computed offset is
12571 // greater than the requested alignment.
12572 assert(PtrAlign.isPowerOfTwo());
12573 assert(Alignment.isPowerOf2());
12574 if (PtrAlign.getQuantity() >= Alignment)
12575 return Success(1, E);
12576 // If the alignment is not known to be sufficient, some cases could still
12577 // be aligned at run time. However, if the requested alignment is less or
12578 // equal to the base alignment and the offset is not aligned, we know that
12579 // the run-time value can never be aligned.
12580 if (BaseAlignment.getQuantity() >= Alignment &&
12581 PtrAlign.getQuantity() < Alignment)
12582 return Success(0, E);
12583 // Otherwise we can't infer whether the value is sufficiently aligned.
12584 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
12585 // in cases where we can't fully evaluate the pointer.
12586 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
12587 << Alignment;
12588 return false;
12589 }
12590 assert(Src.isInt());
12591 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
12592 }
12593 case Builtin::BI__builtin_align_up: {
12594 APValue Src;
12595 APSInt Alignment;
12596 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12597 return false;
12598 if (!Src.isInt())
12599 return Error(E);
12600 APSInt AlignedVal =
12601 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
12602 Src.getInt().isUnsigned());
12603 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12604 return Success(AlignedVal, E);
12605 }
12606 case Builtin::BI__builtin_align_down: {
12607 APValue Src;
12608 APSInt Alignment;
12609 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12610 return false;
12611 if (!Src.isInt())
12612 return Error(E);
12613 APSInt AlignedVal =
12614 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
12615 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12616 return Success(AlignedVal, E);
12617 }
12618
12619 case Builtin::BI__builtin_bitreverse8:
12620 case Builtin::BI__builtin_bitreverse16:
12621 case Builtin::BI__builtin_bitreverse32:
12622 case Builtin::BI__builtin_bitreverse64: {
12623 APSInt Val;
12624 if (!EvaluateInteger(E->getArg(0), Val, Info))
12625 return false;
12626
12627 return Success(Val.reverseBits(), E);
12628 }
12629
12630 case Builtin::BI__builtin_bswap16:
12631 case Builtin::BI__builtin_bswap32:
12632 case Builtin::BI__builtin_bswap64: {
12633 APSInt Val;
12634 if (!EvaluateInteger(E->getArg(0), Val, Info))
12635 return false;
12636
12637 return Success(Val.byteSwap(), E);
12638 }
12639
12640 case Builtin::BI__builtin_classify_type:
12641 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
12642
12643 case Builtin::BI__builtin_clrsb:
12644 case Builtin::BI__builtin_clrsbl:
12645 case Builtin::BI__builtin_clrsbll: {
12646 APSInt Val;
12647 if (!EvaluateInteger(E->getArg(0), Val, Info))
12648 return false;
12649
12650 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
12651 }
12652
12653 case Builtin::BI__builtin_clz:
12654 case Builtin::BI__builtin_clzl:
12655 case Builtin::BI__builtin_clzll:
12656 case Builtin::BI__builtin_clzs:
12657 case Builtin::BI__builtin_clzg:
12658 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
12659 case Builtin::BI__lzcnt:
12660 case Builtin::BI__lzcnt64: {
12661 APSInt Val;
12662 if (!EvaluateInteger(E->getArg(0), Val, Info))
12663 return false;
12664
12665 std::optional<APSInt> Fallback;
12666 if (BuiltinOp == Builtin::BI__builtin_clzg && E->getNumArgs() > 1) {
12667 APSInt FallbackTemp;
12668 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
12669 return false;
12670 Fallback = FallbackTemp;
12671 }
12672
12673 if (!Val) {
12674 if (Fallback)
12675 return Success(*Fallback, E);
12676
12677 // When the argument is 0, the result of GCC builtins is undefined,
12678 // whereas for Microsoft intrinsics, the result is the bit-width of the
12679 // argument.
12680 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
12681 BuiltinOp != Builtin::BI__lzcnt &&
12682 BuiltinOp != Builtin::BI__lzcnt64;
12683
12684 if (ZeroIsUndefined)
12685 return Error(E);
12686 }
12687
12688 return Success(Val.countl_zero(), E);
12689 }
12690
12691 case Builtin::BI__builtin_constant_p: {
12692 const Expr *Arg = E->getArg(0);
12693 if (EvaluateBuiltinConstantP(Info, Arg))
12694 return Success(true, E);
12695 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
12696 // Outside a constant context, eagerly evaluate to false in the presence
12697 // of side-effects in order to avoid -Wunsequenced false-positives in
12698 // a branch on __builtin_constant_p(expr).
12699 return Success(false, E);
12700 }
12701 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12702 return false;
12703 }
12704
12705 case Builtin::BI__builtin_is_constant_evaluated: {
12706 const auto *Callee = Info.CurrentCall->getCallee();
12707 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
12708 (Info.CallStackDepth == 1 ||
12709 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
12710 Callee->getIdentifier() &&
12711 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
12712 // FIXME: Find a better way to avoid duplicated diagnostics.
12713 if (Info.EvalStatus.Diag)
12714 Info.report((Info.CallStackDepth == 1)
12715 ? E->getExprLoc()
12716 : Info.CurrentCall->getCallRange().getBegin(),
12717 diag::warn_is_constant_evaluated_always_true_constexpr)
12718 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
12719 : "std::is_constant_evaluated");
12720 }
12721
12722 return Success(Info.InConstantContext, E);
12723 }
12724
12725 case Builtin::BI__builtin_ctz:
12726 case Builtin::BI__builtin_ctzl:
12727 case Builtin::BI__builtin_ctzll:
12728 case Builtin::BI__builtin_ctzs:
12729 case Builtin::BI__builtin_ctzg: {
12730 APSInt Val;
12731 if (!EvaluateInteger(E->getArg(0), Val, Info))
12732 return false;
12733
12734 std::optional<APSInt> Fallback;
12735 if (BuiltinOp == Builtin::BI__builtin_ctzg && E->getNumArgs() > 1) {
12736 APSInt FallbackTemp;
12737 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
12738 return false;
12739 Fallback = FallbackTemp;
12740 }
12741
12742 if (!Val) {
12743 if (Fallback)
12744 return Success(*Fallback, E);
12745
12746 return Error(E);
12747 }
12748
12749 return Success(Val.countr_zero(), E);
12750 }
12751
12752 case Builtin::BI__builtin_eh_return_data_regno: {
12753 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12754 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
12755 return Success(Operand, E);
12756 }
12757
12758 case Builtin::BI__builtin_expect:
12759 case Builtin::BI__builtin_expect_with_probability:
12760 return Visit(E->getArg(0));
12761
12762 case Builtin::BI__builtin_ptrauth_string_discriminator: {
12763 const auto *Literal =
12764 cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts());
12765 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
12766 return Success(Result, E);
12767 }
12768
12769 case Builtin::BI__builtin_ffs:
12770 case Builtin::BI__builtin_ffsl:
12771 case Builtin::BI__builtin_ffsll: {
12772 APSInt Val;
12773 if (!EvaluateInteger(E->getArg(0), Val, Info))
12774 return false;
12775
12776 unsigned N = Val.countr_zero();
12777 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
12778 }
12779
12780 case Builtin::BI__builtin_fpclassify: {
12781 APFloat Val(0.0);
12782 if (!EvaluateFloat(E->getArg(5), Val, Info))
12783 return false;
12784 unsigned Arg;
12785 switch (Val.getCategory()) {
12786 case APFloat::fcNaN: Arg = 0; break;
12787 case APFloat::fcInfinity: Arg = 1; break;
12788 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
12789 case APFloat::fcZero: Arg = 4; break;
12790 }
12791 return Visit(E->getArg(Arg));
12792 }
12793
12794 case Builtin::BI__builtin_isinf_sign: {
12795 APFloat Val(0.0);
12796 return EvaluateFloat(E->getArg(0), Val, Info) &&
12797 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
12798 }
12799
12800 case Builtin::BI__builtin_isinf: {
12801 APFloat Val(0.0);
12802 return EvaluateFloat(E->getArg(0), Val, Info) &&
12803 Success(Val.isInfinity() ? 1 : 0, E);
12804 }
12805
12806 case Builtin::BI__builtin_isfinite: {
12807 APFloat Val(0.0);
12808 return EvaluateFloat(E->getArg(0), Val, Info) &&
12809 Success(Val.isFinite() ? 1 : 0, E);
12810 }
12811
12812 case Builtin::BI__builtin_isnan: {
12813 APFloat Val(0.0);
12814 return EvaluateFloat(E->getArg(0), Val, Info) &&
12815 Success(Val.isNaN() ? 1 : 0, E);
12816 }
12817
12818 case Builtin::BI__builtin_isnormal: {
12819 APFloat Val(0.0);
12820 return EvaluateFloat(E->getArg(0), Val, Info) &&
12821 Success(Val.isNormal() ? 1 : 0, E);
12822 }
12823
12824 case Builtin::BI__builtin_issubnormal: {
12825 APFloat Val(0.0);
12826 return EvaluateFloat(E->getArg(0), Val, Info) &&
12827 Success(Val.isDenormal() ? 1 : 0, E);
12828 }
12829
12830 case Builtin::BI__builtin_iszero: {
12831 APFloat Val(0.0);
12832 return EvaluateFloat(E->getArg(0), Val, Info) &&
12833 Success(Val.isZero() ? 1 : 0, E);
12834 }
12835
12836 case Builtin::BI__builtin_signbit:
12837 case Builtin::BI__builtin_signbitf:
12838 case Builtin::BI__builtin_signbitl: {
12839 APFloat Val(0.0);
12840 return EvaluateFloat(E->getArg(0), Val, Info) &&
12841 Success(Val.isNegative() ? 1 : 0, E);
12842 }
12843
12844 case Builtin::BI__builtin_isgreater:
12845 case Builtin::BI__builtin_isgreaterequal:
12846 case Builtin::BI__builtin_isless:
12847 case Builtin::BI__builtin_islessequal:
12848 case Builtin::BI__builtin_islessgreater:
12849 case Builtin::BI__builtin_isunordered: {
12850 APFloat LHS(0.0);
12851 APFloat RHS(0.0);
12852 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
12853 !EvaluateFloat(E->getArg(1), RHS, Info))
12854 return false;
12855
12856 return Success(
12857 [&] {
12858 switch (BuiltinOp) {
12859 case Builtin::BI__builtin_isgreater:
12860 return LHS > RHS;
12861 case Builtin::BI__builtin_isgreaterequal:
12862 return LHS >= RHS;
12863 case Builtin::BI__builtin_isless:
12864 return LHS < RHS;
12865 case Builtin::BI__builtin_islessequal:
12866 return LHS <= RHS;
12867 case Builtin::BI__builtin_islessgreater: {
12868 APFloat::cmpResult cmp = LHS.compare(RHS);
12869 return cmp == APFloat::cmpResult::cmpLessThan ||
12870 cmp == APFloat::cmpResult::cmpGreaterThan;
12871 }
12872 case Builtin::BI__builtin_isunordered:
12873 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
12874 default:
12875 llvm_unreachable("Unexpected builtin ID: Should be a floating "
12876 "point comparison function");
12877 }
12878 }()
12879 ? 1
12880 : 0,
12881 E);
12882 }
12883
12884 case Builtin::BI__builtin_issignaling: {
12885 APFloat Val(0.0);
12886 return EvaluateFloat(E->getArg(0), Val, Info) &&
12887 Success(Val.isSignaling() ? 1 : 0, E);
12888 }
12889
12890 case Builtin::BI__builtin_isfpclass: {
12891 APSInt MaskVal;
12892 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
12893 return false;
12894 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
12895 APFloat Val(0.0);
12896 return EvaluateFloat(E->getArg(0), Val, Info) &&
12897 Success((Val.classify() & Test) ? 1 : 0, E);
12898 }
12899
12900 case Builtin::BI__builtin_parity:
12901 case Builtin::BI__builtin_parityl:
12902 case Builtin::BI__builtin_parityll: {
12903 APSInt Val;
12904 if (!EvaluateInteger(E->getArg(0), Val, Info))
12905 return false;
12906
12907 return Success(Val.popcount() % 2, E);
12908 }
12909
12910 case Builtin::BI__builtin_popcount:
12911 case Builtin::BI__builtin_popcountl:
12912 case Builtin::BI__builtin_popcountll:
12913 case Builtin::BI__builtin_popcountg:
12914 case Builtin::BI__popcnt16: // Microsoft variants of popcount
12915 case Builtin::BI__popcnt:
12916 case Builtin::BI__popcnt64: {
12917 APSInt Val;
12918 if (!EvaluateInteger(E->getArg(0), Val, Info))
12919 return false;
12920
12921 return Success(Val.popcount(), E);
12922 }
12923
12924 case Builtin::BI__builtin_rotateleft8:
12925 case Builtin::BI__builtin_rotateleft16:
12926 case Builtin::BI__builtin_rotateleft32:
12927 case Builtin::BI__builtin_rotateleft64:
12928 case Builtin::BI_rotl8: // Microsoft variants of rotate right
12929 case Builtin::BI_rotl16:
12930 case Builtin::BI_rotl:
12931 case Builtin::BI_lrotl:
12932 case Builtin::BI_rotl64: {
12933 APSInt Val, Amt;
12934 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12935 !EvaluateInteger(E->getArg(1), Amt, Info))
12936 return false;
12937
12938 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
12939 }
12940
12941 case Builtin::BI__builtin_rotateright8:
12942 case Builtin::BI__builtin_rotateright16:
12943 case Builtin::BI__builtin_rotateright32:
12944 case Builtin::BI__builtin_rotateright64:
12945 case Builtin::BI_rotr8: // Microsoft variants of rotate right
12946 case Builtin::BI_rotr16:
12947 case Builtin::BI_rotr:
12948 case Builtin::BI_lrotr:
12949 case Builtin::BI_rotr64: {
12950 APSInt Val, Amt;
12951 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12952 !EvaluateInteger(E->getArg(1), Amt, Info))
12953 return false;
12954
12955 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
12956 }
12957
12958 case Builtin::BIstrlen:
12959 case Builtin::BIwcslen:
12960 // A call to strlen is not a constant expression.
12961 if (Info.getLangOpts().CPlusPlus11)
12962 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12963 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12964 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12965 else
12966 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12967 [[fallthrough]];
12968 case Builtin::BI__builtin_strlen:
12969 case Builtin::BI__builtin_wcslen: {
12970 // As an extension, we support __builtin_strlen() as a constant expression,
12971 // and support folding strlen() to a constant.
12972 uint64_t StrLen;
12973 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12974 return Success(StrLen, E);
12975 return false;
12976 }
12977
12978 case Builtin::BIstrcmp:
12979 case Builtin::BIwcscmp:
12980 case Builtin::BIstrncmp:
12981 case Builtin::BIwcsncmp:
12982 case Builtin::BImemcmp:
12983 case Builtin::BIbcmp:
12984 case Builtin::BIwmemcmp:
12985 // A call to strlen is not a constant expression.
12986 if (Info.getLangOpts().CPlusPlus11)
12987 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12988 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12989 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12990 else
12991 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12992 [[fallthrough]];
12993 case Builtin::BI__builtin_strcmp:
12994 case Builtin::BI__builtin_wcscmp:
12995 case Builtin::BI__builtin_strncmp:
12996 case Builtin::BI__builtin_wcsncmp:
12997 case Builtin::BI__builtin_memcmp:
12998 case Builtin::BI__builtin_bcmp:
12999 case Builtin::BI__builtin_wmemcmp: {
13000 LValue String1, String2;
13001 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
13002 !EvaluatePointer(E->getArg(1), String2, Info))
13003 return false;
13004
13005 uint64_t MaxLength = uint64_t(-1);
13006 if (BuiltinOp != Builtin::BIstrcmp &&
13007 BuiltinOp != Builtin::BIwcscmp &&
13008 BuiltinOp != Builtin::BI__builtin_strcmp &&
13009 BuiltinOp != Builtin::BI__builtin_wcscmp) {
13010 APSInt N;
13011 if (!EvaluateInteger(E->getArg(2), N, Info))
13012 return false;
13013 MaxLength = N.getZExtValue();
13014 }
13015
13016 // Empty substrings compare equal by definition.
13017 if (MaxLength == 0u)
13018 return Success(0, E);
13019
13020 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
13021 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
13022 String1.Designator.Invalid || String2.Designator.Invalid)
13023 return false;
13024
13025 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
13026 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
13027
13028 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
13029 BuiltinOp == Builtin::BIbcmp ||
13030 BuiltinOp == Builtin::BI__builtin_memcmp ||
13031 BuiltinOp == Builtin::BI__builtin_bcmp;
13032
13033 assert(IsRawByte ||
13034 (Info.Ctx.hasSameUnqualifiedType(
13035 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
13036 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
13037
13038 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
13039 // 'char8_t', but no other types.
13040 if (IsRawByte &&
13041 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
13042 // FIXME: Consider using our bit_cast implementation to support this.
13043 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
13044 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
13045 << CharTy1 << CharTy2;
13046 return false;
13047 }
13048
13049 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
13050 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
13051 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
13052 Char1.isInt() && Char2.isInt();
13053 };
13054 const auto &AdvanceElems = [&] {
13055 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
13056 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
13057 };
13058
13059 bool StopAtNull =
13060 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
13061 BuiltinOp != Builtin::BIwmemcmp &&
13062 BuiltinOp != Builtin::BI__builtin_memcmp &&
13063 BuiltinOp != Builtin::BI__builtin_bcmp &&
13064 BuiltinOp != Builtin::BI__builtin_wmemcmp);
13065 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
13066 BuiltinOp == Builtin::BIwcsncmp ||
13067 BuiltinOp == Builtin::BIwmemcmp ||
13068 BuiltinOp == Builtin::BI__builtin_wcscmp ||
13069 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
13070 BuiltinOp == Builtin::BI__builtin_wmemcmp;
13071
13072 for (; MaxLength; --MaxLength) {
13073 APValue Char1, Char2;
13074 if (!ReadCurElems(Char1, Char2))
13075 return false;
13076 if (Char1.getInt().ne(Char2.getInt())) {
13077 if (IsWide) // wmemcmp compares with wchar_t signedness.
13078 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
13079 // memcmp always compares unsigned chars.
13080 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
13081 }
13082 if (StopAtNull && !Char1.getInt())
13083 return Success(0, E);
13084 assert(!(StopAtNull && !Char2.getInt()));
13085 if (!AdvanceElems())
13086 return false;
13087 }
13088 // We hit the strncmp / memcmp limit.
13089 return Success(0, E);
13090 }
13091
13092 case Builtin::BI__atomic_always_lock_free:
13093 case Builtin::BI__atomic_is_lock_free:
13094 case Builtin::BI__c11_atomic_is_lock_free: {
13095 APSInt SizeVal;
13096 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
13097 return false;
13098
13099 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
13100 // of two less than or equal to the maximum inline atomic width, we know it
13101 // is lock-free. If the size isn't a power of two, or greater than the
13102 // maximum alignment where we promote atomics, we know it is not lock-free
13103 // (at least not in the sense of atomic_is_lock_free). Otherwise,
13104 // the answer can only be determined at runtime; for example, 16-byte
13105 // atomics have lock-free implementations on some, but not all,
13106 // x86-64 processors.
13107
13108 // Check power-of-two.
13109 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
13110 if (Size.isPowerOfTwo()) {
13111 // Check against inlining width.
13112 unsigned InlineWidthBits =
13113 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
13114 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
13115 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
13116 Size == CharUnits::One())
13117 return Success(1, E);
13118
13119 // If the pointer argument can be evaluated to a compile-time constant
13120 // integer (or nullptr), check if that value is appropriately aligned.
13121 const Expr *PtrArg = E->getArg(1);
13123 APSInt IntResult;
13124 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
13125 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
13126 Info.Ctx) &&
13127 IntResult.isAligned(Size.getAsAlign()))
13128 return Success(1, E);
13129
13130 // Otherwise, check if the type's alignment against Size.
13131 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
13132 // Drop the potential implicit-cast to 'const volatile void*', getting
13133 // the underlying type.
13134 if (ICE->getCastKind() == CK_BitCast)
13135 PtrArg = ICE->getSubExpr();
13136 }
13137
13138 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
13139 QualType PointeeType = PtrTy->getPointeeType();
13140 if (!PointeeType->isIncompleteType() &&
13141 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
13142 // OK, we will inline operations on this object.
13143 return Success(1, E);
13144 }
13145 }
13146 }
13147 }
13148
13149 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
13150 Success(0, E) : Error(E);
13151 }
13152 case Builtin::BI__builtin_addcb:
13153 case Builtin::BI__builtin_addcs:
13154 case Builtin::BI__builtin_addc:
13155 case Builtin::BI__builtin_addcl:
13156 case Builtin::BI__builtin_addcll:
13157 case Builtin::BI__builtin_subcb:
13158 case Builtin::BI__builtin_subcs:
13159 case Builtin::BI__builtin_subc:
13160 case Builtin::BI__builtin_subcl:
13161 case Builtin::BI__builtin_subcll: {
13162 LValue CarryOutLValue;
13163 APSInt LHS, RHS, CarryIn, CarryOut, Result;
13164 QualType ResultType = E->getArg(0)->getType();
13165 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13166 !EvaluateInteger(E->getArg(1), RHS, Info) ||
13167 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
13168 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
13169 return false;
13170 // Copy the number of bits and sign.
13171 Result = LHS;
13172 CarryOut = LHS;
13173
13174 bool FirstOverflowed = false;
13175 bool SecondOverflowed = false;
13176 switch (BuiltinOp) {
13177 default:
13178 llvm_unreachable("Invalid value for BuiltinOp");
13179 case Builtin::BI__builtin_addcb:
13180 case Builtin::BI__builtin_addcs:
13181 case Builtin::BI__builtin_addc:
13182 case Builtin::BI__builtin_addcl:
13183 case Builtin::BI__builtin_addcll:
13184 Result =
13185 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
13186 break;
13187 case Builtin::BI__builtin_subcb:
13188 case Builtin::BI__builtin_subcs:
13189 case Builtin::BI__builtin_subc:
13190 case Builtin::BI__builtin_subcl:
13191 case Builtin::BI__builtin_subcll:
13192 Result =
13193 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
13194 break;
13195 }
13196
13197 // It is possible for both overflows to happen but CGBuiltin uses an OR so
13198 // this is consistent.
13199 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
13200 APValue APV{CarryOut};
13201 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
13202 return false;
13203 return Success(Result, E);
13204 }
13205 case Builtin::BI__builtin_add_overflow:
13206 case Builtin::BI__builtin_sub_overflow:
13207 case Builtin::BI__builtin_mul_overflow:
13208 case Builtin::BI__builtin_sadd_overflow:
13209 case Builtin::BI__builtin_uadd_overflow:
13210 case Builtin::BI__builtin_uaddl_overflow:
13211 case Builtin::BI__builtin_uaddll_overflow:
13212 case Builtin::BI__builtin_usub_overflow:
13213 case Builtin::BI__builtin_usubl_overflow:
13214 case Builtin::BI__builtin_usubll_overflow:
13215 case Builtin::BI__builtin_umul_overflow:
13216 case Builtin::BI__builtin_umull_overflow:
13217 case Builtin::BI__builtin_umulll_overflow:
13218 case Builtin::BI__builtin_saddl_overflow:
13219 case Builtin::BI__builtin_saddll_overflow:
13220 case Builtin::BI__builtin_ssub_overflow:
13221 case Builtin::BI__builtin_ssubl_overflow:
13222 case Builtin::BI__builtin_ssubll_overflow:
13223 case Builtin::BI__builtin_smul_overflow:
13224 case Builtin::BI__builtin_smull_overflow:
13225 case Builtin::BI__builtin_smulll_overflow: {
13226 LValue ResultLValue;
13227 APSInt LHS, RHS;
13228
13229 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
13230 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13231 !EvaluateInteger(E->getArg(1), RHS, Info) ||
13232 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
13233 return false;
13234
13235 APSInt Result;
13236 bool DidOverflow = false;
13237
13238 // If the types don't have to match, enlarge all 3 to the largest of them.
13239 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
13240 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
13241 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
13242 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
13244 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
13246 uint64_t LHSSize = LHS.getBitWidth();
13247 uint64_t RHSSize = RHS.getBitWidth();
13248 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
13249 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
13250
13251 // Add an additional bit if the signedness isn't uniformly agreed to. We
13252 // could do this ONLY if there is a signed and an unsigned that both have
13253 // MaxBits, but the code to check that is pretty nasty. The issue will be
13254 // caught in the shrink-to-result later anyway.
13255 if (IsSigned && !AllSigned)
13256 ++MaxBits;
13257
13258 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
13259 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
13260 Result = APSInt(MaxBits, !IsSigned);
13261 }
13262
13263 // Find largest int.
13264 switch (BuiltinOp) {
13265 default:
13266 llvm_unreachable("Invalid value for BuiltinOp");
13267 case Builtin::BI__builtin_add_overflow:
13268 case Builtin::BI__builtin_sadd_overflow:
13269 case Builtin::BI__builtin_saddl_overflow:
13270 case Builtin::BI__builtin_saddll_overflow:
13271 case Builtin::BI__builtin_uadd_overflow:
13272 case Builtin::BI__builtin_uaddl_overflow:
13273 case Builtin::BI__builtin_uaddll_overflow:
13274 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
13275 : LHS.uadd_ov(RHS, DidOverflow);
13276 break;
13277 case Builtin::BI__builtin_sub_overflow:
13278 case Builtin::BI__builtin_ssub_overflow:
13279 case Builtin::BI__builtin_ssubl_overflow:
13280 case Builtin::BI__builtin_ssubll_overflow:
13281 case Builtin::BI__builtin_usub_overflow:
13282 case Builtin::BI__builtin_usubl_overflow:
13283 case Builtin::BI__builtin_usubll_overflow:
13284 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
13285 : LHS.usub_ov(RHS, DidOverflow);
13286 break;
13287 case Builtin::BI__builtin_mul_overflow:
13288 case Builtin::BI__builtin_smul_overflow:
13289 case Builtin::BI__builtin_smull_overflow:
13290 case Builtin::BI__builtin_smulll_overflow:
13291 case Builtin::BI__builtin_umul_overflow:
13292 case Builtin::BI__builtin_umull_overflow:
13293 case Builtin::BI__builtin_umulll_overflow:
13294 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
13295 : LHS.umul_ov(RHS, DidOverflow);
13296 break;
13297 }
13298
13299 // In the case where multiple sizes are allowed, truncate and see if
13300 // the values are the same.
13301 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
13302 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
13303 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
13304 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
13305 // since it will give us the behavior of a TruncOrSelf in the case where
13306 // its parameter <= its size. We previously set Result to be at least the
13307 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
13308 // will work exactly like TruncOrSelf.
13309 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
13310 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
13311
13312 if (!APSInt::isSameValue(Temp, Result))
13313 DidOverflow = true;
13314 Result = Temp;
13315 }
13316
13317 APValue APV{Result};
13318 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
13319 return false;
13320 return Success(DidOverflow, E);
13321 }
13322 }
13323}
13324
13325/// Determine whether this is a pointer past the end of the complete
13326/// object referred to by the lvalue.
13328 const LValue &LV) {
13329 // A null pointer can be viewed as being "past the end" but we don't
13330 // choose to look at it that way here.
13331 if (!LV.getLValueBase())
13332 return false;
13333
13334 // If the designator is valid and refers to a subobject, we're not pointing
13335 // past the end.
13336 if (!LV.getLValueDesignator().Invalid &&
13337 !LV.getLValueDesignator().isOnePastTheEnd())
13338 return false;
13339
13340 // A pointer to an incomplete type might be past-the-end if the type's size is
13341 // zero. We cannot tell because the type is incomplete.
13342 QualType Ty = getType(LV.getLValueBase());
13343 if (Ty->isIncompleteType())
13344 return true;
13345
13346 // Can't be past the end of an invalid object.
13347 if (LV.getLValueDesignator().Invalid)
13348 return false;
13349
13350 // We're a past-the-end pointer if we point to the byte after the object,
13351 // no matter what our type or path is.
13352 auto Size = Ctx.getTypeSizeInChars(Ty);
13353 return LV.getLValueOffset() == Size;
13354}
13355
13356namespace {
13357
13358/// Data recursive integer evaluator of certain binary operators.
13359///
13360/// We use a data recursive algorithm for binary operators so that we are able
13361/// to handle extreme cases of chained binary operators without causing stack
13362/// overflow.
13363class DataRecursiveIntBinOpEvaluator {
13364 struct EvalResult {
13365 APValue Val;
13366 bool Failed = false;
13367
13368 EvalResult() = default;
13369
13370 void swap(EvalResult &RHS) {
13371 Val.swap(RHS.Val);
13372 Failed = RHS.Failed;
13373 RHS.Failed = false;
13374 }
13375 };
13376
13377 struct Job {
13378 const Expr *E;
13379 EvalResult LHSResult; // meaningful only for binary operator expression.
13380 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
13381
13382 Job() = default;
13383 Job(Job &&) = default;
13384
13385 void startSpeculativeEval(EvalInfo &Info) {
13386 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
13387 }
13388
13389 private:
13390 SpeculativeEvaluationRAII SpecEvalRAII;
13391 };
13392
13394
13395 IntExprEvaluator &IntEval;
13396 EvalInfo &Info;
13397 APValue &FinalResult;
13398
13399public:
13400 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
13401 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
13402
13403 /// True if \param E is a binary operator that we are going to handle
13404 /// data recursively.
13405 /// We handle binary operators that are comma, logical, or that have operands
13406 /// with integral or enumeration type.
13407 static bool shouldEnqueue(const BinaryOperator *E) {
13408 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
13410 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13411 E->getRHS()->getType()->isIntegralOrEnumerationType());
13412 }
13413
13414 bool Traverse(const BinaryOperator *E) {
13415 enqueue(E);
13416 EvalResult PrevResult;
13417 while (!Queue.empty())
13418 process(PrevResult);
13419
13420 if (PrevResult.Failed) return false;
13421
13422 FinalResult.swap(PrevResult.Val);
13423 return true;
13424 }
13425
13426private:
13427 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
13428 return IntEval.Success(Value, E, Result);
13429 }
13430 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
13431 return IntEval.Success(Value, E, Result);
13432 }
13433 bool Error(const Expr *E) {
13434 return IntEval.Error(E);
13435 }
13436 bool Error(const Expr *E, diag::kind D) {
13437 return IntEval.Error(E, D);
13438 }
13439
13440 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
13441 return Info.CCEDiag(E, D);
13442 }
13443
13444 // Returns true if visiting the RHS is necessary, false otherwise.
13445 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
13446 bool &SuppressRHSDiags);
13447
13448 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
13449 const BinaryOperator *E, APValue &Result);
13450
13451 void EvaluateExpr(const Expr *E, EvalResult &Result) {
13452 Result.Failed = !Evaluate(Result.Val, Info, E);
13453 if (Result.Failed)
13454 Result.Val = APValue();
13455 }
13456
13457 void process(EvalResult &Result);
13458
13459 void enqueue(const Expr *E) {
13460 E = E->IgnoreParens();
13461 Queue.resize(Queue.size()+1);
13462 Queue.back().E = E;
13463 Queue.back().Kind = Job::AnyExprKind;
13464 }
13465};
13466
13467}
13468
13469bool DataRecursiveIntBinOpEvaluator::
13470 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
13471 bool &SuppressRHSDiags) {
13472 if (E->getOpcode() == BO_Comma) {
13473 // Ignore LHS but note if we could not evaluate it.
13474 if (LHSResult.Failed)
13475 return Info.noteSideEffect();
13476 return true;
13477 }
13478
13479 if (E->isLogicalOp()) {
13480 bool LHSAsBool;
13481 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
13482 // We were able to evaluate the LHS, see if we can get away with not
13483 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
13484 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
13485 Success(LHSAsBool, E, LHSResult.Val);
13486 return false; // Ignore RHS
13487 }
13488 } else {
13489 LHSResult.Failed = true;
13490
13491 // Since we weren't able to evaluate the left hand side, it
13492 // might have had side effects.
13493 if (!Info.noteSideEffect())
13494 return false;
13495
13496 // We can't evaluate the LHS; however, sometimes the result
13497 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
13498 // Don't ignore RHS and suppress diagnostics from this arm.
13499 SuppressRHSDiags = true;
13500 }
13501
13502 return true;
13503 }
13504
13505 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13506 E->getRHS()->getType()->isIntegralOrEnumerationType());
13507
13508 if (LHSResult.Failed && !Info.noteFailure())
13509 return false; // Ignore RHS;
13510
13511 return true;
13512}
13513
13514static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
13515 bool IsSub) {
13516 // Compute the new offset in the appropriate width, wrapping at 64 bits.
13517 // FIXME: When compiling for a 32-bit target, we should use 32-bit
13518 // offsets.
13519 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
13520 CharUnits &Offset = LVal.getLValueOffset();
13521 uint64_t Offset64 = Offset.getQuantity();
13522 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
13523 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
13524 : Offset64 + Index64);
13525}
13526
13527bool DataRecursiveIntBinOpEvaluator::
13528 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
13529 const BinaryOperator *E, APValue &Result) {
13530 if (E->getOpcode() == BO_Comma) {
13531 if (RHSResult.Failed)
13532 return false;
13533 Result = RHSResult.Val;
13534 return true;
13535 }
13536
13537 if (E->isLogicalOp()) {
13538 bool lhsResult, rhsResult;
13539 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
13540 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
13541
13542 if (LHSIsOK) {
13543 if (RHSIsOK) {
13544 if (E->getOpcode() == BO_LOr)
13545 return Success(lhsResult || rhsResult, E, Result);
13546 else
13547 return Success(lhsResult && rhsResult, E, Result);
13548 }
13549 } else {
13550 if (RHSIsOK) {
13551 // We can't evaluate the LHS; however, sometimes the result
13552 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
13553 if (rhsResult == (E->getOpcode() == BO_LOr))
13554 return Success(rhsResult, E, Result);
13555 }
13556 }
13557
13558 return false;
13559 }
13560
13561 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13562 E->getRHS()->getType()->isIntegralOrEnumerationType());
13563
13564 if (LHSResult.Failed || RHSResult.Failed)
13565 return false;
13566
13567 const APValue &LHSVal = LHSResult.Val;
13568 const APValue &RHSVal = RHSResult.Val;
13569
13570 // Handle cases like (unsigned long)&a + 4.
13571 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
13572 Result = LHSVal;
13573 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
13574 return true;
13575 }
13576
13577 // Handle cases like 4 + (unsigned long)&a
13578 if (E->getOpcode() == BO_Add &&
13579 RHSVal.isLValue() && LHSVal.isInt()) {
13580 Result = RHSVal;
13581 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
13582 return true;
13583 }
13584
13585 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
13586 // Handle (intptr_t)&&A - (intptr_t)&&B.
13587 if (!LHSVal.getLValueOffset().isZero() ||
13588 !RHSVal.getLValueOffset().isZero())
13589 return false;
13590 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
13591 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
13592 if (!LHSExpr || !RHSExpr)
13593 return false;
13594 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13595 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13596 if (!LHSAddrExpr || !RHSAddrExpr)
13597 return false;
13598 // Make sure both labels come from the same function.
13599 if (LHSAddrExpr->getLabel()->getDeclContext() !=
13600 RHSAddrExpr->getLabel()->getDeclContext())
13601 return false;
13602 Result = APValue(LHSAddrExpr, RHSAddrExpr);
13603 return true;
13604 }
13605
13606 // All the remaining cases expect both operands to be an integer
13607 if (!LHSVal.isInt() || !RHSVal.isInt())
13608 return Error(E);
13609
13610 // Set up the width and signedness manually, in case it can't be deduced
13611 // from the operation we're performing.
13612 // FIXME: Don't do this in the cases where we can deduce it.
13613 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
13615 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
13616 RHSVal.getInt(), Value))
13617 return false;
13618 return Success(Value, E, Result);
13619}
13620
13621void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
13622 Job &job = Queue.back();
13623
13624 switch (job.Kind) {
13625 case Job::AnyExprKind: {
13626 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
13627 if (shouldEnqueue(Bop)) {
13628 job.Kind = Job::BinOpKind;
13629 enqueue(Bop->getLHS());
13630 return;
13631 }
13632 }
13633
13634 EvaluateExpr(job.E, Result);
13635 Queue.pop_back();
13636 return;
13637 }
13638
13639 case Job::BinOpKind: {
13640 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
13641 bool SuppressRHSDiags = false;
13642 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
13643 Queue.pop_back();
13644 return;
13645 }
13646 if (SuppressRHSDiags)
13647 job.startSpeculativeEval(Info);
13648 job.LHSResult.swap(Result);
13649 job.Kind = Job::BinOpVisitedLHSKind;
13650 enqueue(Bop->getRHS());
13651 return;
13652 }
13653
13654 case Job::BinOpVisitedLHSKind: {
13655 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
13656 EvalResult RHS;
13657 RHS.swap(Result);
13658 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
13659 Queue.pop_back();
13660 return;
13661 }
13662 }
13663
13664 llvm_unreachable("Invalid Job::Kind!");
13665}
13666
13667namespace {
13668enum class CmpResult {
13669 Unequal,
13670 Less,
13671 Equal,
13672 Greater,
13673 Unordered,
13674};
13675}
13676
13677template <class SuccessCB, class AfterCB>
13678static bool
13680 SuccessCB &&Success, AfterCB &&DoAfter) {
13681 assert(!E->isValueDependent());
13682 assert(E->isComparisonOp() && "expected comparison operator");
13683 assert((E->getOpcode() == BO_Cmp ||
13685 "unsupported binary expression evaluation");
13686 auto Error = [&](const Expr *E) {
13687 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13688 return false;
13689 };
13690
13691 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
13692 bool IsEquality = E->isEqualityOp();
13693
13694 QualType LHSTy = E->getLHS()->getType();
13695 QualType RHSTy = E->getRHS()->getType();
13696
13697 if (LHSTy->isIntegralOrEnumerationType() &&
13698 RHSTy->isIntegralOrEnumerationType()) {
13699 APSInt LHS, RHS;
13700 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
13701 if (!LHSOK && !Info.noteFailure())
13702 return false;
13703 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
13704 return false;
13705 if (LHS < RHS)
13706 return Success(CmpResult::Less, E);
13707 if (LHS > RHS)
13708 return Success(CmpResult::Greater, E);
13709 return Success(CmpResult::Equal, E);
13710 }
13711
13712 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
13713 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
13714 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
13715
13716 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
13717 if (!LHSOK && !Info.noteFailure())
13718 return false;
13719 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
13720 return false;
13721 if (LHSFX < RHSFX)
13722 return Success(CmpResult::Less, E);
13723 if (LHSFX > RHSFX)
13724 return Success(CmpResult::Greater, E);
13725 return Success(CmpResult::Equal, E);
13726 }
13727
13728 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
13729 ComplexValue LHS, RHS;
13730 bool LHSOK;
13731 if (E->isAssignmentOp()) {
13732 LValue LV;
13733 EvaluateLValue(E->getLHS(), LV, Info);
13734 LHSOK = false;
13735 } else if (LHSTy->isRealFloatingType()) {
13736 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
13737 if (LHSOK) {
13738 LHS.makeComplexFloat();
13739 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
13740 }
13741 } else {
13742 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
13743 }
13744 if (!LHSOK && !Info.noteFailure())
13745 return false;
13746
13747 if (E->getRHS()->getType()->isRealFloatingType()) {
13748 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
13749 return false;
13750 RHS.makeComplexFloat();
13751 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
13752 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13753 return false;
13754
13755 if (LHS.isComplexFloat()) {
13756 APFloat::cmpResult CR_r =
13757 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
13758 APFloat::cmpResult CR_i =
13759 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
13760 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
13761 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
13762 } else {
13763 assert(IsEquality && "invalid complex comparison");
13764 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
13765 LHS.getComplexIntImag() == RHS.getComplexIntImag();
13766 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
13767 }
13768 }
13769
13770 if (LHSTy->isRealFloatingType() &&
13771 RHSTy->isRealFloatingType()) {
13772 APFloat RHS(0.0), LHS(0.0);
13773
13774 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
13775 if (!LHSOK && !Info.noteFailure())
13776 return false;
13777
13778 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
13779 return false;
13780
13781 assert(E->isComparisonOp() && "Invalid binary operator!");
13782 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
13783 if (!Info.InConstantContext &&
13784 APFloatCmpResult == APFloat::cmpUnordered &&
13785 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
13786 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
13787 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
13788 return false;
13789 }
13790 auto GetCmpRes = [&]() {
13791 switch (APFloatCmpResult) {
13792 case APFloat::cmpEqual:
13793 return CmpResult::Equal;
13794 case APFloat::cmpLessThan:
13795 return CmpResult::Less;
13796 case APFloat::cmpGreaterThan:
13797 return CmpResult::Greater;
13798 case APFloat::cmpUnordered:
13799 return CmpResult::Unordered;
13800 }
13801 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
13802 };
13803 return Success(GetCmpRes(), E);
13804 }
13805
13806 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
13807 LValue LHSValue, RHSValue;
13808
13809 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13810 if (!LHSOK && !Info.noteFailure())
13811 return false;
13812
13813 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13814 return false;
13815
13816 // Reject differing bases from the normal codepath; we special-case
13817 // comparisons to null.
13818 if (!HasSameBase(LHSValue, RHSValue)) {
13819 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
13820 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
13821 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
13822 Info.FFDiag(E, DiagID)
13823 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
13824 return false;
13825 };
13826 // Inequalities and subtractions between unrelated pointers have
13827 // unspecified or undefined behavior.
13828 if (!IsEquality)
13829 return DiagComparison(
13830 diag::note_constexpr_pointer_comparison_unspecified);
13831 // A constant address may compare equal to the address of a symbol.
13832 // The one exception is that address of an object cannot compare equal
13833 // to a null pointer constant.
13834 // TODO: Should we restrict this to actual null pointers, and exclude the
13835 // case of zero cast to pointer type?
13836 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
13837 (!RHSValue.Base && !RHSValue.Offset.isZero()))
13838 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
13839 !RHSValue.Base);
13840 // It's implementation-defined whether distinct literals will have
13841 // distinct addresses. In clang, the result of such a comparison is
13842 // unspecified, so it is not a constant expression. However, we do know
13843 // that the address of a literal will be non-null.
13844 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
13845 LHSValue.Base && RHSValue.Base)
13846 return DiagComparison(diag::note_constexpr_literal_comparison);
13847 // We can't tell whether weak symbols will end up pointing to the same
13848 // object.
13849 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
13850 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
13851 !IsWeakLValue(LHSValue));
13852 // We can't compare the address of the start of one object with the
13853 // past-the-end address of another object, per C++ DR1652.
13854 if (LHSValue.Base && LHSValue.Offset.isZero() &&
13855 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
13856 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13857 true);
13858 if (RHSValue.Base && RHSValue.Offset.isZero() &&
13859 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
13860 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13861 false);
13862 // We can't tell whether an object is at the same address as another
13863 // zero sized object.
13864 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
13865 (LHSValue.Base && isZeroSized(RHSValue)))
13866 return DiagComparison(
13867 diag::note_constexpr_pointer_comparison_zero_sized);
13868 return Success(CmpResult::Unequal, E);
13869 }
13870
13871 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13872 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13873
13874 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13875 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13876
13877 // C++11 [expr.rel]p3:
13878 // Pointers to void (after pointer conversions) can be compared, with a
13879 // result defined as follows: If both pointers represent the same
13880 // address or are both the null pointer value, the result is true if the
13881 // operator is <= or >= and false otherwise; otherwise the result is
13882 // unspecified.
13883 // We interpret this as applying to pointers to *cv* void.
13884 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
13885 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
13886
13887 // C++11 [expr.rel]p2:
13888 // - If two pointers point to non-static data members of the same object,
13889 // or to subobjects or array elements fo such members, recursively, the
13890 // pointer to the later declared member compares greater provided the
13891 // two members have the same access control and provided their class is
13892 // not a union.
13893 // [...]
13894 // - Otherwise pointer comparisons are unspecified.
13895 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
13896 bool WasArrayIndex;
13897 unsigned Mismatch = FindDesignatorMismatch(
13898 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
13899 // At the point where the designators diverge, the comparison has a
13900 // specified value if:
13901 // - we are comparing array indices
13902 // - we are comparing fields of a union, or fields with the same access
13903 // Otherwise, the result is unspecified and thus the comparison is not a
13904 // constant expression.
13905 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
13906 Mismatch < RHSDesignator.Entries.size()) {
13907 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
13908 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
13909 if (!LF && !RF)
13910 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
13911 else if (!LF)
13912 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13913 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
13914 << RF->getParent() << RF;
13915 else if (!RF)
13916 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13917 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
13918 << LF->getParent() << LF;
13919 else if (!LF->getParent()->isUnion() &&
13920 LF->getAccess() != RF->getAccess())
13921 Info.CCEDiag(E,
13922 diag::note_constexpr_pointer_comparison_differing_access)
13923 << LF << LF->getAccess() << RF << RF->getAccess()
13924 << LF->getParent();
13925 }
13926 }
13927
13928 // The comparison here must be unsigned, and performed with the same
13929 // width as the pointer.
13930 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
13931 uint64_t CompareLHS = LHSOffset.getQuantity();
13932 uint64_t CompareRHS = RHSOffset.getQuantity();
13933 assert(PtrSize <= 64 && "Unexpected pointer width");
13934 uint64_t Mask = ~0ULL >> (64 - PtrSize);
13935 CompareLHS &= Mask;
13936 CompareRHS &= Mask;
13937
13938 // If there is a base and this is a relational operator, we can only
13939 // compare pointers within the object in question; otherwise, the result
13940 // depends on where the object is located in memory.
13941 if (!LHSValue.Base.isNull() && IsRelational) {
13942 QualType BaseTy = getType(LHSValue.Base);
13943 if (BaseTy->isIncompleteType())
13944 return Error(E);
13945 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
13946 uint64_t OffsetLimit = Size.getQuantity();
13947 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
13948 return Error(E);
13949 }
13950
13951 if (CompareLHS < CompareRHS)
13952 return Success(CmpResult::Less, E);
13953 if (CompareLHS > CompareRHS)
13954 return Success(CmpResult::Greater, E);
13955 return Success(CmpResult::Equal, E);
13956 }
13957
13958 if (LHSTy->isMemberPointerType()) {
13959 assert(IsEquality && "unexpected member pointer operation");
13960 assert(RHSTy->isMemberPointerType() && "invalid comparison");
13961
13962 MemberPtr LHSValue, RHSValue;
13963
13964 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
13965 if (!LHSOK && !Info.noteFailure())
13966 return false;
13967
13968 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13969 return false;
13970
13971 // If either operand is a pointer to a weak function, the comparison is not
13972 // constant.
13973 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
13974 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13975 << LHSValue.getDecl();
13976 return false;
13977 }
13978 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
13979 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13980 << RHSValue.getDecl();
13981 return false;
13982 }
13983
13984 // C++11 [expr.eq]p2:
13985 // If both operands are null, they compare equal. Otherwise if only one is
13986 // null, they compare unequal.
13987 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
13988 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
13989 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13990 }
13991
13992 // Otherwise if either is a pointer to a virtual member function, the
13993 // result is unspecified.
13994 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
13995 if (MD->isVirtual())
13996 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13997 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
13998 if (MD->isVirtual())
13999 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
14000
14001 // Otherwise they compare equal if and only if they would refer to the
14002 // same member of the same most derived object or the same subobject if
14003 // they were dereferenced with a hypothetical object of the associated
14004 // class type.
14005 bool Equal = LHSValue == RHSValue;
14006 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
14007 }
14008
14009 if (LHSTy->isNullPtrType()) {
14010 assert(E->isComparisonOp() && "unexpected nullptr operation");
14011 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
14012 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
14013 // are compared, the result is true of the operator is <=, >= or ==, and
14014 // false otherwise.
14015 LValue Res;
14016 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
14017 !EvaluatePointer(E->getRHS(), Res, Info))
14018 return false;
14019 return Success(CmpResult::Equal, E);
14020 }
14021
14022 return DoAfter();
14023}
14024
14025bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
14026 if (!CheckLiteralType(Info, E))
14027 return false;
14028
14029 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
14031 switch (CR) {
14032 case CmpResult::Unequal:
14033 llvm_unreachable("should never produce Unequal for three-way comparison");
14034 case CmpResult::Less:
14035 CCR = ComparisonCategoryResult::Less;
14036 break;
14037 case CmpResult::Equal:
14038 CCR = ComparisonCategoryResult::Equal;
14039 break;
14040 case CmpResult::Greater:
14041 CCR = ComparisonCategoryResult::Greater;
14042 break;
14043 case CmpResult::Unordered:
14044 CCR = ComparisonCategoryResult::Unordered;
14045 break;
14046 }
14047 // Evaluation succeeded. Lookup the information for the comparison category
14048 // type and fetch the VarDecl for the result.
14049 const ComparisonCategoryInfo &CmpInfo =
14051 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
14052 // Check and evaluate the result as a constant expression.
14053 LValue LV;
14054 LV.set(VD);
14055 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14056 return false;
14057 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14058 ConstantExprKind::Normal);
14059 };
14060 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
14061 return ExprEvaluatorBaseTy::VisitBinCmp(E);
14062 });
14063}
14064
14065bool RecordExprEvaluator::VisitCXXParenListInitExpr(
14066 const CXXParenListInitExpr *E) {
14067 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
14068}
14069
14070bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14071 // We don't support assignment in C. C++ assignments don't get here because
14072 // assignment is an lvalue in C++.
14073 if (E->isAssignmentOp()) {
14074 Error(E);
14075 if (!Info.noteFailure())
14076 return false;
14077 }
14078
14079 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
14080 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
14081
14082 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
14083 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
14084 "DataRecursiveIntBinOpEvaluator should have handled integral types");
14085
14086 if (E->isComparisonOp()) {
14087 // Evaluate builtin binary comparisons by evaluating them as three-way
14088 // comparisons and then translating the result.
14089 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
14090 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
14091 "should only produce Unequal for equality comparisons");
14092 bool IsEqual = CR == CmpResult::Equal,
14093 IsLess = CR == CmpResult::Less,
14094 IsGreater = CR == CmpResult::Greater;
14095 auto Op = E->getOpcode();
14096 switch (Op) {
14097 default:
14098 llvm_unreachable("unsupported binary operator");
14099 case BO_EQ:
14100 case BO_NE:
14101 return Success(IsEqual == (Op == BO_EQ), E);
14102 case BO_LT:
14103 return Success(IsLess, E);
14104 case BO_GT:
14105 return Success(IsGreater, E);
14106 case BO_LE:
14107 return Success(IsEqual || IsLess, E);
14108 case BO_GE:
14109 return Success(IsEqual || IsGreater, E);
14110 }
14111 };
14112 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
14113 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14114 });
14115 }
14116
14117 QualType LHSTy = E->getLHS()->getType();
14118 QualType RHSTy = E->getRHS()->getType();
14119
14120 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
14121 E->getOpcode() == BO_Sub) {
14122 LValue LHSValue, RHSValue;
14123
14124 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
14125 if (!LHSOK && !Info.noteFailure())
14126 return false;
14127
14128 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
14129 return false;
14130
14131 // Reject differing bases from the normal codepath; we special-case
14132 // comparisons to null.
14133 if (!HasSameBase(LHSValue, RHSValue)) {
14134 // Handle &&A - &&B.
14135 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
14136 return Error(E);
14137 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
14138 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
14139 if (!LHSExpr || !RHSExpr)
14140 return Error(E);
14141 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
14142 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
14143 if (!LHSAddrExpr || !RHSAddrExpr)
14144 return Error(E);
14145 // Make sure both labels come from the same function.
14146 if (LHSAddrExpr->getLabel()->getDeclContext() !=
14147 RHSAddrExpr->getLabel()->getDeclContext())
14148 return Error(E);
14149 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
14150 }
14151 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
14152 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
14153
14154 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
14155 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
14156
14157 // C++11 [expr.add]p6:
14158 // Unless both pointers point to elements of the same array object, or
14159 // one past the last element of the array object, the behavior is
14160 // undefined.
14161 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
14162 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
14163 RHSDesignator))
14164 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
14165
14166 QualType Type = E->getLHS()->getType();
14167 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
14168
14169 CharUnits ElementSize;
14170 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
14171 return false;
14172
14173 // As an extension, a type may have zero size (empty struct or union in
14174 // C, array of zero length). Pointer subtraction in such cases has
14175 // undefined behavior, so is not constant.
14176 if (ElementSize.isZero()) {
14177 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
14178 << ElementType;
14179 return false;
14180 }
14181
14182 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
14183 // and produce incorrect results when it overflows. Such behavior
14184 // appears to be non-conforming, but is common, so perhaps we should
14185 // assume the standard intended for such cases to be undefined behavior
14186 // and check for them.
14187
14188 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
14189 // overflow in the final conversion to ptrdiff_t.
14190 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
14191 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
14192 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
14193 false);
14194 APSInt TrueResult = (LHS - RHS) / ElemSize;
14195 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
14196
14197 if (Result.extend(65) != TrueResult &&
14198 !HandleOverflow(Info, E, TrueResult, E->getType()))
14199 return false;
14200 return Success(Result, E);
14201 }
14202
14203 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14204}
14205
14206/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
14207/// a result as the expression's type.
14208bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
14209 const UnaryExprOrTypeTraitExpr *E) {
14210 switch(E->getKind()) {
14211 case UETT_PreferredAlignOf:
14212 case UETT_AlignOf: {
14213 if (E->isArgumentType())
14214 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
14215 E);
14216 else
14217 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
14218 E);
14219 }
14220
14221 case UETT_PtrAuthTypeDiscriminator: {
14222 if (E->getArgumentType()->isDependentType())
14223 return false;
14224 return Success(
14225 Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
14226 }
14227 case UETT_VecStep: {
14228 QualType Ty = E->getTypeOfArgument();
14229
14230 if (Ty->isVectorType()) {
14231 unsigned n = Ty->castAs<VectorType>()->getNumElements();
14232
14233 // The vec_step built-in functions that take a 3-component
14234 // vector return 4. (OpenCL 1.1 spec 6.11.12)
14235 if (n == 3)
14236 n = 4;
14237
14238 return Success(n, E);
14239 } else
14240 return Success(1, E);
14241 }
14242
14243 case UETT_DataSizeOf:
14244 case UETT_SizeOf: {
14245 QualType SrcTy = E->getTypeOfArgument();
14246 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
14247 // the result is the size of the referenced type."
14248 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
14249 SrcTy = Ref->getPointeeType();
14250
14251 CharUnits Sizeof;
14252 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
14253 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
14254 : SizeOfType::SizeOf)) {
14255 return false;
14256 }
14257 return Success(Sizeof, E);
14258 }
14259 case UETT_OpenMPRequiredSimdAlign:
14260 assert(E->isArgumentType());
14261 return Success(
14262 Info.Ctx.toCharUnitsFromBits(
14263 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
14264 .getQuantity(),
14265 E);
14266 case UETT_VectorElements: {
14267 QualType Ty = E->getTypeOfArgument();
14268 // If the vector has a fixed size, we can determine the number of elements
14269 // at compile time.
14270 if (const auto *VT = Ty->getAs<VectorType>())
14271 return Success(VT->getNumElements(), E);
14272
14273 assert(Ty->isSizelessVectorType());
14274 if (Info.InConstantContext)
14275 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
14276 << E->getSourceRange();
14277
14278 return false;
14279 }
14280 }
14281
14282 llvm_unreachable("unknown expr/type trait");
14283}
14284
14285bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
14286 CharUnits Result;
14287 unsigned n = OOE->getNumComponents();
14288 if (n == 0)
14289 return Error(OOE);
14290 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
14291 for (unsigned i = 0; i != n; ++i) {
14292 OffsetOfNode ON = OOE->getComponent(i);
14293 switch (ON.getKind()) {
14294 case OffsetOfNode::Array: {
14295 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
14296 APSInt IdxResult;
14297 if (!EvaluateInteger(Idx, IdxResult, Info))
14298 return false;
14299 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
14300 if (!AT)
14301 return Error(OOE);
14302 CurrentType = AT->getElementType();
14303 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
14304 Result += IdxResult.getSExtValue() * ElementSize;
14305 break;
14306 }
14307
14308 case OffsetOfNode::Field: {
14309 FieldDecl *MemberDecl = ON.getField();
14310 const RecordType *RT = CurrentType->getAs<RecordType>();
14311 if (!RT)
14312 return Error(OOE);
14313 RecordDecl *RD = RT->getDecl();
14314 if (RD->isInvalidDecl()) return false;
14315 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
14316 unsigned i = MemberDecl->getFieldIndex();
14317 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
14318 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
14319 CurrentType = MemberDecl->getType().getNonReferenceType();
14320 break;
14321 }
14322
14324 llvm_unreachable("dependent __builtin_offsetof");
14325
14326 case OffsetOfNode::Base: {
14327 CXXBaseSpecifier *BaseSpec = ON.getBase();
14328 if (BaseSpec->isVirtual())
14329 return Error(OOE);
14330
14331 // Find the layout of the class whose base we are looking into.
14332 const RecordType *RT = CurrentType->getAs<RecordType>();
14333 if (!RT)
14334 return Error(OOE);
14335 RecordDecl *RD = RT->getDecl();
14336 if (RD->isInvalidDecl()) return false;
14337 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
14338
14339 // Find the base class itself.
14340 CurrentType = BaseSpec->getType();
14341 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
14342 if (!BaseRT)
14343 return Error(OOE);
14344
14345 // Add the offset to the base.
14346 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
14347 break;
14348 }
14349 }
14350 }
14351 return Success(Result, OOE);
14352}
14353
14354bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14355 switch (E->getOpcode()) {
14356 default:
14357 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
14358 // See C99 6.6p3.
14359 return Error(E);
14360 case UO_Extension:
14361 // FIXME: Should extension allow i-c-e extension expressions in its scope?
14362 // If so, we could clear the diagnostic ID.
14363 return Visit(E->getSubExpr());
14364 case UO_Plus:
14365 // The result is just the value.
14366 return Visit(E->getSubExpr());
14367 case UO_Minus: {
14368 if (!Visit(E->getSubExpr()))
14369 return false;
14370 if (!Result.isInt()) return Error(E);
14371 const APSInt &Value = Result.getInt();
14372 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
14373 if (Info.checkingForUndefinedBehavior())
14374 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14375 diag::warn_integer_constant_overflow)
14376 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
14377 /*UpperCase=*/true, /*InsertSeparators=*/true)
14378 << E->getType() << E->getSourceRange();
14379
14380 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
14381 E->getType()))
14382 return false;
14383 }
14384 return Success(-Value, E);
14385 }
14386 case UO_Not: {
14387 if (!Visit(E->getSubExpr()))
14388 return false;
14389 if (!Result.isInt()) return Error(E);
14390 return Success(~Result.getInt(), E);
14391 }
14392 case UO_LNot: {
14393 bool bres;
14394 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
14395 return false;
14396 return Success(!bres, E);
14397 }
14398 }
14399}
14400
14401/// HandleCast - This is used to evaluate implicit or explicit casts where the
14402/// result type is integer.
14403bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
14404 const Expr *SubExpr = E->getSubExpr();
14405 QualType DestType = E->getType();
14406 QualType SrcType = SubExpr->getType();
14407
14408 switch (E->getCastKind()) {
14409 case CK_BaseToDerived:
14410 case CK_DerivedToBase:
14411 case CK_UncheckedDerivedToBase:
14412 case CK_Dynamic:
14413 case CK_ToUnion:
14414 case CK_ArrayToPointerDecay:
14415 case CK_FunctionToPointerDecay:
14416 case CK_NullToPointer:
14417 case CK_NullToMemberPointer:
14418 case CK_BaseToDerivedMemberPointer:
14419 case CK_DerivedToBaseMemberPointer:
14420 case CK_ReinterpretMemberPointer:
14421 case CK_ConstructorConversion:
14422 case CK_IntegralToPointer:
14423 case CK_ToVoid:
14424 case CK_VectorSplat:
14425 case CK_IntegralToFloating:
14426 case CK_FloatingCast:
14427 case CK_CPointerToObjCPointerCast:
14428 case CK_BlockPointerToObjCPointerCast:
14429 case CK_AnyPointerToBlockPointerCast:
14430 case CK_ObjCObjectLValueCast:
14431 case CK_FloatingRealToComplex:
14432 case CK_FloatingComplexToReal:
14433 case CK_FloatingComplexCast:
14434 case CK_FloatingComplexToIntegralComplex:
14435 case CK_IntegralRealToComplex:
14436 case CK_IntegralComplexCast:
14437 case CK_IntegralComplexToFloatingComplex:
14438 case CK_BuiltinFnToFnPtr:
14439 case CK_ZeroToOCLOpaqueType:
14440 case CK_NonAtomicToAtomic:
14441 case CK_AddressSpaceConversion:
14442 case CK_IntToOCLSampler:
14443 case CK_FloatingToFixedPoint:
14444 case CK_FixedPointToFloating:
14445 case CK_FixedPointCast:
14446 case CK_IntegralToFixedPoint:
14447 case CK_MatrixCast:
14448 case CK_HLSLVectorTruncation:
14449 llvm_unreachable("invalid cast kind for integral value");
14450
14451 case CK_BitCast:
14452 case CK_Dependent:
14453 case CK_LValueBitCast:
14454 case CK_ARCProduceObject:
14455 case CK_ARCConsumeObject:
14456 case CK_ARCReclaimReturnedObject:
14457 case CK_ARCExtendBlockObject:
14458 case CK_CopyAndAutoreleaseBlockObject:
14459 return Error(E);
14460
14461 case CK_UserDefinedConversion:
14462 case CK_LValueToRValue:
14463 case CK_AtomicToNonAtomic:
14464 case CK_NoOp:
14465 case CK_LValueToRValueBitCast:
14466 case CK_HLSLArrayRValue:
14467 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14468
14469 case CK_MemberPointerToBoolean:
14470 case CK_PointerToBoolean:
14471 case CK_IntegralToBoolean:
14472 case CK_FloatingToBoolean:
14473 case CK_BooleanToSignedIntegral:
14474 case CK_FloatingComplexToBoolean:
14475 case CK_IntegralComplexToBoolean: {
14476 bool BoolResult;
14477 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
14478 return false;
14479 uint64_t IntResult = BoolResult;
14480 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
14481 IntResult = (uint64_t)-1;
14482 return Success(IntResult, E);
14483 }
14484
14485 case CK_FixedPointToIntegral: {
14486 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
14487 if (!EvaluateFixedPoint(SubExpr, Src, Info))
14488 return false;
14489 bool Overflowed;
14490 llvm::APSInt Result = Src.convertToInt(
14491 Info.Ctx.getIntWidth(DestType),
14492 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
14493 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
14494 return false;
14495 return Success(Result, E);
14496 }
14497
14498 case CK_FixedPointToBoolean: {
14499 // Unsigned padding does not affect this.
14500 APValue Val;
14501 if (!Evaluate(Val, Info, SubExpr))
14502 return false;
14503 return Success(Val.getFixedPoint().getBoolValue(), E);
14504 }
14505
14506 case CK_IntegralCast: {
14507 if (!Visit(SubExpr))
14508 return false;
14509
14510 if (!Result.isInt()) {
14511 // Allow casts of address-of-label differences if they are no-ops
14512 // or narrowing. (The narrowing case isn't actually guaranteed to
14513 // be constant-evaluatable except in some narrow cases which are hard
14514 // to detect here. We let it through on the assumption the user knows
14515 // what they are doing.)
14516 if (Result.isAddrLabelDiff())
14517 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
14518 // Only allow casts of lvalues if they are lossless.
14519 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
14520 }
14521
14522 if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
14523 Info.EvalMode == EvalInfo::EM_ConstantExpression &&
14524 DestType->isEnumeralType()) {
14525
14526 bool ConstexprVar = true;
14527
14528 // We know if we are here that we are in a context that we might require
14529 // a constant expression or a context that requires a constant
14530 // value. But if we are initializing a value we don't know if it is a
14531 // constexpr variable or not. We can check the EvaluatingDecl to determine
14532 // if it constexpr or not. If not then we don't want to emit a diagnostic.
14533 if (const auto *VD = dyn_cast_or_null<VarDecl>(
14534 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
14535 ConstexprVar = VD->isConstexpr();
14536
14537 const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());
14538 const EnumDecl *ED = ET->getDecl();
14539 // Check that the value is within the range of the enumeration values.
14540 //
14541 // This corressponds to [expr.static.cast]p10 which says:
14542 // A value of integral or enumeration type can be explicitly converted
14543 // to a complete enumeration type ... If the enumeration type does not
14544 // have a fixed underlying type, the value is unchanged if the original
14545 // value is within the range of the enumeration values ([dcl.enum]), and
14546 // otherwise, the behavior is undefined.
14547 //
14548 // This was resolved as part of DR2338 which has CD5 status.
14549 if (!ED->isFixed()) {
14550 llvm::APInt Min;
14551 llvm::APInt Max;
14552
14553 ED->getValueRange(Max, Min);
14554 --Max;
14555
14556 if (ED->getNumNegativeBits() && ConstexprVar &&
14557 (Max.slt(Result.getInt().getSExtValue()) ||
14558 Min.sgt(Result.getInt().getSExtValue())))
14559 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
14560 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
14561 << Max.getSExtValue() << ED;
14562 else if (!ED->getNumNegativeBits() && ConstexprVar &&
14563 Max.ult(Result.getInt().getZExtValue()))
14564 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
14565 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
14566 << Max.getZExtValue() << ED;
14567 }
14568 }
14569
14570 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
14571 Result.getInt()), E);
14572 }
14573
14574 case CK_PointerToIntegral: {
14575 CCEDiag(E, diag::note_constexpr_invalid_cast)
14576 << 2 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
14577
14578 LValue LV;
14579 if (!EvaluatePointer(SubExpr, LV, Info))
14580 return false;
14581
14582 if (LV.getLValueBase()) {
14583 // Only allow based lvalue casts if they are lossless.
14584 // FIXME: Allow a larger integer size than the pointer size, and allow
14585 // narrowing back down to pointer width in subsequent integral casts.
14586 // FIXME: Check integer type's active bits, not its type size.
14587 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
14588 return Error(E);
14589
14590 LV.Designator.setInvalid();
14591 LV.moveInto(Result);
14592 return true;
14593 }
14594
14595 APSInt AsInt;
14596 APValue V;
14597 LV.moveInto(V);
14598 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
14599 llvm_unreachable("Can't cast this!");
14600
14601 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
14602 }
14603
14604 case CK_IntegralComplexToReal: {
14605 ComplexValue C;
14606 if (!EvaluateComplex(SubExpr, C, Info))
14607 return false;
14608 return Success(C.getComplexIntReal(), E);
14609 }
14610
14611 case CK_FloatingToIntegral: {
14612 APFloat F(0.0);
14613 if (!EvaluateFloat(SubExpr, F, Info))
14614 return false;
14615
14616 APSInt Value;
14617 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
14618 return false;
14619 return Success(Value, E);
14620 }
14621 }
14622
14623 llvm_unreachable("unknown cast resulting in integral value");
14624}
14625
14626bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
14627 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14628 ComplexValue LV;
14629 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
14630 return false;
14631 if (!LV.isComplexInt())
14632 return Error(E);
14633 return Success(LV.getComplexIntReal(), E);
14634 }
14635
14636 return Visit(E->getSubExpr());
14637}
14638
14639bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
14640 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
14641 ComplexValue LV;
14642 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
14643 return false;
14644 if (!LV.isComplexInt())
14645 return Error(E);
14646 return Success(LV.getComplexIntImag(), E);
14647 }
14648
14649 VisitIgnoredValue(E->getSubExpr());
14650 return Success(0, E);
14651}
14652
14653bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
14654 return Success(E->getPackLength(), E);
14655}
14656
14657bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
14658 return Success(E->getValue(), E);
14659}
14660
14661bool IntExprEvaluator::VisitConceptSpecializationExpr(
14663 return Success(E->isSatisfied(), E);
14664}
14665
14666bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
14667 return Success(E->isSatisfied(), E);
14668}
14669
14670bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14671 switch (E->getOpcode()) {
14672 default:
14673 // Invalid unary operators
14674 return Error(E);
14675 case UO_Plus:
14676 // The result is just the value.
14677 return Visit(E->getSubExpr());
14678 case UO_Minus: {
14679 if (!Visit(E->getSubExpr())) return false;
14680 if (!Result.isFixedPoint())
14681 return Error(E);
14682 bool Overflowed;
14683 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
14684 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
14685 return false;
14686 return Success(Negated, E);
14687 }
14688 case UO_LNot: {
14689 bool bres;
14690 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
14691 return false;
14692 return Success(!bres, E);
14693 }
14694 }
14695}
14696
14697bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
14698 const Expr *SubExpr = E->getSubExpr();
14699 QualType DestType = E->getType();
14700 assert(DestType->isFixedPointType() &&
14701 "Expected destination type to be a fixed point type");
14702 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
14703
14704 switch (E->getCastKind()) {
14705 case CK_FixedPointCast: {
14706 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14707 if (!EvaluateFixedPoint(SubExpr, Src, Info))
14708 return false;
14709 bool Overflowed;
14710 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
14711 if (Overflowed) {
14712 if (Info.checkingForUndefinedBehavior())
14713 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14714 diag::warn_fixedpoint_constant_overflow)
14715 << Result.toString() << E->getType();
14716 if (!HandleOverflow(Info, E, Result, E->getType()))
14717 return false;
14718 }
14719 return Success(Result, E);
14720 }
14721 case CK_IntegralToFixedPoint: {
14722 APSInt Src;
14723 if (!EvaluateInteger(SubExpr, Src, Info))
14724 return false;
14725
14726 bool Overflowed;
14727 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
14728 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
14729
14730 if (Overflowed) {
14731 if (Info.checkingForUndefinedBehavior())
14732 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14733 diag::warn_fixedpoint_constant_overflow)
14734 << IntResult.toString() << E->getType();
14735 if (!HandleOverflow(Info, E, IntResult, E->getType()))
14736 return false;
14737 }
14738
14739 return Success(IntResult, E);
14740 }
14741 case CK_FloatingToFixedPoint: {
14742 APFloat Src(0.0);
14743 if (!EvaluateFloat(SubExpr, Src, Info))
14744 return false;
14745
14746 bool Overflowed;
14747 APFixedPoint Result = APFixedPoint::getFromFloatValue(
14748 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
14749
14750 if (Overflowed) {
14751 if (Info.checkingForUndefinedBehavior())
14752 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14753 diag::warn_fixedpoint_constant_overflow)
14754 << Result.toString() << E->getType();
14755 if (!HandleOverflow(Info, E, Result, E->getType()))
14756 return false;
14757 }
14758
14759 return Success(Result, E);
14760 }
14761 case CK_NoOp:
14762 case CK_LValueToRValue:
14763 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14764 default:
14765 return Error(E);
14766 }
14767}
14768
14769bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14770 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14771 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14772
14773 const Expr *LHS = E->getLHS();
14774 const Expr *RHS = E->getRHS();
14775 FixedPointSemantics ResultFXSema =
14776 Info.Ctx.getFixedPointSemantics(E->getType());
14777
14778 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
14779 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
14780 return false;
14781 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
14782 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
14783 return false;
14784
14785 bool OpOverflow = false, ConversionOverflow = false;
14786 APFixedPoint Result(LHSFX.getSemantics());
14787 switch (E->getOpcode()) {
14788 case BO_Add: {
14789 Result = LHSFX.add(RHSFX, &OpOverflow)
14790 .convert(ResultFXSema, &ConversionOverflow);
14791 break;
14792 }
14793 case BO_Sub: {
14794 Result = LHSFX.sub(RHSFX, &OpOverflow)
14795 .convert(ResultFXSema, &ConversionOverflow);
14796 break;
14797 }
14798 case BO_Mul: {
14799 Result = LHSFX.mul(RHSFX, &OpOverflow)
14800 .convert(ResultFXSema, &ConversionOverflow);
14801 break;
14802 }
14803 case BO_Div: {
14804 if (RHSFX.getValue() == 0) {
14805 Info.FFDiag(E, diag::note_expr_divide_by_zero);
14806 return false;
14807 }
14808 Result = LHSFX.div(RHSFX, &OpOverflow)
14809 .convert(ResultFXSema, &ConversionOverflow);
14810 break;
14811 }
14812 case BO_Shl:
14813 case BO_Shr: {
14814 FixedPointSemantics LHSSema = LHSFX.getSemantics();
14815 llvm::APSInt RHSVal = RHSFX.getValue();
14816
14817 unsigned ShiftBW =
14818 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
14819 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
14820 // Embedded-C 4.1.6.2.2:
14821 // The right operand must be nonnegative and less than the total number
14822 // of (nonpadding) bits of the fixed-point operand ...
14823 if (RHSVal.isNegative())
14824 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
14825 else if (Amt != RHSVal)
14826 Info.CCEDiag(E, diag::note_constexpr_large_shift)
14827 << RHSVal << E->getType() << ShiftBW;
14828
14829 if (E->getOpcode() == BO_Shl)
14830 Result = LHSFX.shl(Amt, &OpOverflow);
14831 else
14832 Result = LHSFX.shr(Amt, &OpOverflow);
14833 break;
14834 }
14835 default:
14836 return false;
14837 }
14838 if (OpOverflow || ConversionOverflow) {
14839 if (Info.checkingForUndefinedBehavior())
14840 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14841 diag::warn_fixedpoint_constant_overflow)
14842 << Result.toString() << E->getType();
14843 if (!HandleOverflow(Info, E, Result, E->getType()))
14844 return false;
14845 }
14846 return Success(Result, E);
14847}
14848
14849//===----------------------------------------------------------------------===//
14850// Float Evaluation
14851//===----------------------------------------------------------------------===//
14852
14853namespace {
14854class FloatExprEvaluator
14855 : public ExprEvaluatorBase<FloatExprEvaluator> {
14856 APFloat &Result;
14857public:
14858 FloatExprEvaluator(EvalInfo &info, APFloat &result)
14859 : ExprEvaluatorBaseTy(info), Result(result) {}
14860
14861 bool Success(const APValue &V, const Expr *e) {
14862 Result = V.getFloat();
14863 return true;
14864 }
14865
14866 bool ZeroInitialization(const Expr *E) {
14867 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
14868 return true;
14869 }
14870
14871 bool VisitCallExpr(const CallExpr *E);
14872
14873 bool VisitUnaryOperator(const UnaryOperator *E);
14874 bool VisitBinaryOperator(const BinaryOperator *E);
14875 bool VisitFloatingLiteral(const FloatingLiteral *E);
14876 bool VisitCastExpr(const CastExpr *E);
14877
14878 bool VisitUnaryReal(const UnaryOperator *E);
14879 bool VisitUnaryImag(const UnaryOperator *E);
14880
14881 // FIXME: Missing: array subscript of vector, member of vector
14882};
14883} // end anonymous namespace
14884
14885static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
14886 assert(!E->isValueDependent());
14887 assert(E->isPRValue() && E->getType()->isRealFloatingType());
14888 return FloatExprEvaluator(Info, Result).Visit(E);
14889}
14890
14891static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
14892 QualType ResultTy,
14893 const Expr *Arg,
14894 bool SNaN,
14895 llvm::APFloat &Result) {
14896 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
14897 if (!S) return false;
14898
14899 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
14900
14901 llvm::APInt fill;
14902
14903 // Treat empty strings as if they were zero.
14904 if (S->getString().empty())
14905 fill = llvm::APInt(32, 0);
14906 else if (S->getString().getAsInteger(0, fill))
14907 return false;
14908
14909 if (Context.getTargetInfo().isNan2008()) {
14910 if (SNaN)
14911 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14912 else
14913 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14914 } else {
14915 // Prior to IEEE 754-2008, architectures were allowed to choose whether
14916 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
14917 // a different encoding to what became a standard in 2008, and for pre-
14918 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
14919 // sNaN. This is now known as "legacy NaN" encoding.
14920 if (SNaN)
14921 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14922 else
14923 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14924 }
14925
14926 return true;
14927}
14928
14929bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
14930 if (!IsConstantEvaluatedBuiltinCall(E))
14931 return ExprEvaluatorBaseTy::VisitCallExpr(E);
14932
14933 switch (E->getBuiltinCallee()) {
14934 default:
14935 return false;
14936
14937 case Builtin::BI__builtin_huge_val:
14938 case Builtin::BI__builtin_huge_valf:
14939 case Builtin::BI__builtin_huge_vall:
14940 case Builtin::BI__builtin_huge_valf16:
14941 case Builtin::BI__builtin_huge_valf128:
14942 case Builtin::BI__builtin_inf:
14943 case Builtin::BI__builtin_inff:
14944 case Builtin::BI__builtin_infl:
14945 case Builtin::BI__builtin_inff16:
14946 case Builtin::BI__builtin_inff128: {
14947 const llvm::fltSemantics &Sem =
14948 Info.Ctx.getFloatTypeSemantics(E->getType());
14949 Result = llvm::APFloat::getInf(Sem);
14950 return true;
14951 }
14952
14953 case Builtin::BI__builtin_nans:
14954 case Builtin::BI__builtin_nansf:
14955 case Builtin::BI__builtin_nansl:
14956 case Builtin::BI__builtin_nansf16:
14957 case Builtin::BI__builtin_nansf128:
14958 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14959 true, Result))
14960 return Error(E);
14961 return true;
14962
14963 case Builtin::BI__builtin_nan:
14964 case Builtin::BI__builtin_nanf:
14965 case Builtin::BI__builtin_nanl:
14966 case Builtin::BI__builtin_nanf16:
14967 case Builtin::BI__builtin_nanf128:
14968 // If this is __builtin_nan() turn this into a nan, otherwise we
14969 // can't constant fold it.
14970 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14971 false, Result))
14972 return Error(E);
14973 return true;
14974
14975 case Builtin::BI__builtin_fabs:
14976 case Builtin::BI__builtin_fabsf:
14977 case Builtin::BI__builtin_fabsl:
14978 case Builtin::BI__builtin_fabsf128:
14979 // The C standard says "fabs raises no floating-point exceptions,
14980 // even if x is a signaling NaN. The returned value is independent of
14981 // the current rounding direction mode." Therefore constant folding can
14982 // proceed without regard to the floating point settings.
14983 // Reference, WG14 N2478 F.10.4.3
14984 if (!EvaluateFloat(E->getArg(0), Result, Info))
14985 return false;
14986
14987 if (Result.isNegative())
14988 Result.changeSign();
14989 return true;
14990
14991 case Builtin::BI__arithmetic_fence:
14992 return EvaluateFloat(E->getArg(0), Result, Info);
14993
14994 // FIXME: Builtin::BI__builtin_powi
14995 // FIXME: Builtin::BI__builtin_powif
14996 // FIXME: Builtin::BI__builtin_powil
14997
14998 case Builtin::BI__builtin_copysign:
14999 case Builtin::BI__builtin_copysignf:
15000 case Builtin::BI__builtin_copysignl:
15001 case Builtin::BI__builtin_copysignf128: {
15002 APFloat RHS(0.);
15003 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15004 !EvaluateFloat(E->getArg(1), RHS, Info))
15005 return false;
15006 Result.copySign(RHS);
15007 return true;
15008 }
15009
15010 case Builtin::BI__builtin_fmax:
15011 case Builtin::BI__builtin_fmaxf:
15012 case Builtin::BI__builtin_fmaxl:
15013 case Builtin::BI__builtin_fmaxf16:
15014 case Builtin::BI__builtin_fmaxf128: {
15015 // TODO: Handle sNaN.
15016 APFloat RHS(0.);
15017 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15018 !EvaluateFloat(E->getArg(1), RHS, Info))
15019 return false;
15020 // When comparing zeroes, return +0.0 if one of the zeroes is positive.
15021 if (Result.isZero() && RHS.isZero() && Result.isNegative())
15022 Result = RHS;
15023 else if (Result.isNaN() || RHS > Result)
15024 Result = RHS;
15025 return true;
15026 }
15027
15028 case Builtin::BI__builtin_fmin:
15029 case Builtin::BI__builtin_fminf:
15030 case Builtin::BI__builtin_fminl:
15031 case Builtin::BI__builtin_fminf16:
15032 case Builtin::BI__builtin_fminf128: {
15033 // TODO: Handle sNaN.
15034 APFloat RHS(0.);
15035 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15036 !EvaluateFloat(E->getArg(1), RHS, Info))
15037 return false;
15038 // When comparing zeroes, return -0.0 if one of the zeroes is negative.
15039 if (Result.isZero() && RHS.isZero() && RHS.isNegative())
15040 Result = RHS;
15041 else if (Result.isNaN() || RHS < Result)
15042 Result = RHS;
15043 return true;
15044 }
15045 }
15046}
15047
15048bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
15049 if (E->getSubExpr()->getType()->isAnyComplexType()) {
15050 ComplexValue CV;
15051 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
15052 return false;
15053 Result = CV.FloatReal;
15054 return true;
15055 }
15056
15057 return Visit(E->getSubExpr());
15058}
15059
15060bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
15061 if (E->getSubExpr()->getType()->isAnyComplexType()) {
15062 ComplexValue CV;
15063 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
15064 return false;
15065 Result = CV.FloatImag;
15066 return true;
15067 }
15068
15069 VisitIgnoredValue(E->getSubExpr());
15070 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
15071 Result = llvm::APFloat::getZero(Sem);
15072 return true;
15073}
15074
15075bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15076 switch (E->getOpcode()) {
15077 default: return Error(E);
15078 case UO_Plus:
15079 return EvaluateFloat(E->getSubExpr(), Result, Info);
15080 case UO_Minus:
15081 // In C standard, WG14 N2478 F.3 p4
15082 // "the unary - raises no floating point exceptions,
15083 // even if the operand is signalling."
15084 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
15085 return false;
15086 Result.changeSign();
15087 return true;
15088 }
15089}
15090
15091bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15092 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15093 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15094
15095 APFloat RHS(0.0);
15096 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
15097 if (!LHSOK && !Info.noteFailure())
15098 return false;
15099 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
15100 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
15101}
15102
15103bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
15104 Result = E->getValue();
15105 return true;
15106}
15107
15108bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
15109 const Expr* SubExpr = E->getSubExpr();
15110
15111 switch (E->getCastKind()) {
15112 default:
15113 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15114
15115 case CK_IntegralToFloating: {
15116 APSInt IntResult;
15117 const FPOptions FPO = E->getFPFeaturesInEffect(
15118 Info.Ctx.getLangOpts());
15119 return EvaluateInteger(SubExpr, IntResult, Info) &&
15120 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
15121 IntResult, E->getType(), Result);
15122 }
15123
15124 case CK_FixedPointToFloating: {
15125 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
15126 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
15127 return false;
15128 Result =
15129 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
15130 return true;
15131 }
15132
15133 case CK_FloatingCast: {
15134 if (!Visit(SubExpr))
15135 return false;
15136 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
15137 Result);
15138 }
15139
15140 case CK_FloatingComplexToReal: {
15141 ComplexValue V;
15142 if (!EvaluateComplex(SubExpr, V, Info))
15143 return false;
15144 Result = V.getComplexFloatReal();
15145 return true;
15146 }
15147 }
15148}
15149
15150//===----------------------------------------------------------------------===//
15151// Complex Evaluation (for float and integer)
15152//===----------------------------------------------------------------------===//
15153
15154namespace {
15155class ComplexExprEvaluator
15156 : public ExprEvaluatorBase<ComplexExprEvaluator> {
15157 ComplexValue &Result;
15158
15159public:
15160 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
15161 : ExprEvaluatorBaseTy(info), Result(Result) {}
15162
15163 bool Success(const APValue &V, const Expr *e) {
15164 Result.setFrom(V);
15165 return true;
15166 }
15167
15168 bool ZeroInitialization(const Expr *E);
15169
15170 //===--------------------------------------------------------------------===//
15171 // Visitor Methods
15172 //===--------------------------------------------------------------------===//
15173
15174 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
15175 bool VisitCastExpr(const CastExpr *E);
15176 bool VisitBinaryOperator(const BinaryOperator *E);
15177 bool VisitUnaryOperator(const UnaryOperator *E);
15178 bool VisitInitListExpr(const InitListExpr *E);
15179 bool VisitCallExpr(const CallExpr *E);
15180};
15181} // end anonymous namespace
15182
15183static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
15184 EvalInfo &Info) {
15185 assert(!E->isValueDependent());
15186 assert(E->isPRValue() && E->getType()->isAnyComplexType());
15187 return ComplexExprEvaluator(Info, Result).Visit(E);
15188}
15189
15190bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
15191 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
15192 if (ElemTy->isRealFloatingType()) {
15193 Result.makeComplexFloat();
15194 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
15195 Result.FloatReal = Zero;
15196 Result.FloatImag = Zero;
15197 } else {
15198 Result.makeComplexInt();
15199 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
15200 Result.IntReal = Zero;
15201 Result.IntImag = Zero;
15202 }
15203 return true;
15204}
15205
15206bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
15207 const Expr* SubExpr = E->getSubExpr();
15208
15209 if (SubExpr->getType()->isRealFloatingType()) {
15210 Result.makeComplexFloat();
15211 APFloat &Imag = Result.FloatImag;
15212 if (!EvaluateFloat(SubExpr, Imag, Info))
15213 return false;
15214
15215 Result.FloatReal = APFloat(Imag.getSemantics());
15216 return true;
15217 } else {
15218 assert(SubExpr->getType()->isIntegerType() &&
15219 "Unexpected imaginary literal.");
15220
15221 Result.makeComplexInt();
15222 APSInt &Imag = Result.IntImag;
15223 if (!EvaluateInteger(SubExpr, Imag, Info))
15224 return false;
15225
15226 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
15227 return true;
15228 }
15229}
15230
15231bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
15232
15233 switch (E->getCastKind()) {
15234 case CK_BitCast:
15235 case CK_BaseToDerived:
15236 case CK_DerivedToBase:
15237 case CK_UncheckedDerivedToBase:
15238 case CK_Dynamic:
15239 case CK_ToUnion:
15240 case CK_ArrayToPointerDecay:
15241 case CK_FunctionToPointerDecay:
15242 case CK_NullToPointer:
15243 case CK_NullToMemberPointer:
15244 case CK_BaseToDerivedMemberPointer:
15245 case CK_DerivedToBaseMemberPointer:
15246 case CK_MemberPointerToBoolean:
15247 case CK_ReinterpretMemberPointer:
15248 case CK_ConstructorConversion:
15249 case CK_IntegralToPointer:
15250 case CK_PointerToIntegral:
15251 case CK_PointerToBoolean:
15252 case CK_ToVoid:
15253 case CK_VectorSplat:
15254 case CK_IntegralCast:
15255 case CK_BooleanToSignedIntegral:
15256 case CK_IntegralToBoolean:
15257 case CK_IntegralToFloating:
15258 case CK_FloatingToIntegral:
15259 case CK_FloatingToBoolean:
15260 case CK_FloatingCast:
15261 case CK_CPointerToObjCPointerCast:
15262 case CK_BlockPointerToObjCPointerCast:
15263 case CK_AnyPointerToBlockPointerCast:
15264 case CK_ObjCObjectLValueCast:
15265 case CK_FloatingComplexToReal:
15266 case CK_FloatingComplexToBoolean:
15267 case CK_IntegralComplexToReal:
15268 case CK_IntegralComplexToBoolean:
15269 case CK_ARCProduceObject:
15270 case CK_ARCConsumeObject:
15271 case CK_ARCReclaimReturnedObject:
15272 case CK_ARCExtendBlockObject:
15273 case CK_CopyAndAutoreleaseBlockObject:
15274 case CK_BuiltinFnToFnPtr:
15275 case CK_ZeroToOCLOpaqueType:
15276 case CK_NonAtomicToAtomic:
15277 case CK_AddressSpaceConversion:
15278 case CK_IntToOCLSampler:
15279 case CK_FloatingToFixedPoint:
15280 case CK_FixedPointToFloating:
15281 case CK_FixedPointCast:
15282 case CK_FixedPointToBoolean:
15283 case CK_FixedPointToIntegral:
15284 case CK_IntegralToFixedPoint:
15285 case CK_MatrixCast:
15286 case CK_HLSLVectorTruncation:
15287 llvm_unreachable("invalid cast kind for complex value");
15288
15289 case CK_LValueToRValue:
15290 case CK_AtomicToNonAtomic:
15291 case CK_NoOp:
15292 case CK_LValueToRValueBitCast:
15293 case CK_HLSLArrayRValue:
15294 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15295
15296 case CK_Dependent:
15297 case CK_LValueBitCast:
15298 case CK_UserDefinedConversion:
15299 return Error(E);
15300
15301 case CK_FloatingRealToComplex: {
15302 APFloat &Real = Result.FloatReal;
15303 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
15304 return false;
15305
15306 Result.makeComplexFloat();
15307 Result.FloatImag = APFloat(Real.getSemantics());
15308 return true;
15309 }
15310
15311 case CK_FloatingComplexCast: {
15312 if (!Visit(E->getSubExpr()))
15313 return false;
15314
15315 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15316 QualType From
15317 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15318
15319 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
15320 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
15321 }
15322
15323 case CK_FloatingComplexToIntegralComplex: {
15324 if (!Visit(E->getSubExpr()))
15325 return false;
15326
15327 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15328 QualType From
15329 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15330 Result.makeComplexInt();
15331 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
15332 To, Result.IntReal) &&
15333 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
15334 To, Result.IntImag);
15335 }
15336
15337 case CK_IntegralRealToComplex: {
15338 APSInt &Real = Result.IntReal;
15339 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
15340 return false;
15341
15342 Result.makeComplexInt();
15343 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
15344 return true;
15345 }
15346
15347 case CK_IntegralComplexCast: {
15348 if (!Visit(E->getSubExpr()))
15349 return false;
15350
15351 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15352 QualType From
15353 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15354
15355 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
15356 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
15357 return true;
15358 }
15359
15360 case CK_IntegralComplexToFloatingComplex: {
15361 if (!Visit(E->getSubExpr()))
15362 return false;
15363
15364 const FPOptions FPO = E->getFPFeaturesInEffect(
15365 Info.Ctx.getLangOpts());
15366 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15367 QualType From
15368 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15369 Result.makeComplexFloat();
15370 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
15371 To, Result.FloatReal) &&
15372 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
15373 To, Result.FloatImag);
15374 }
15375 }
15376
15377 llvm_unreachable("unknown cast resulting in complex value");
15378}
15379
15380void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
15381 APFloat &ResR, APFloat &ResI) {
15382 // This is an implementation of complex multiplication according to the
15383 // constraints laid out in C11 Annex G. The implementation uses the
15384 // following naming scheme:
15385 // (a + ib) * (c + id)
15386
15387 APFloat AC = A * C;
15388 APFloat BD = B * D;
15389 APFloat AD = A * D;
15390 APFloat BC = B * C;
15391 ResR = AC - BD;
15392 ResI = AD + BC;
15393 if (ResR.isNaN() && ResI.isNaN()) {
15394 bool Recalc = false;
15395 if (A.isInfinity() || B.isInfinity()) {
15396 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
15397 A);
15398 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
15399 B);
15400 if (C.isNaN())
15401 C = APFloat::copySign(APFloat(C.getSemantics()), C);
15402 if (D.isNaN())
15403 D = APFloat::copySign(APFloat(D.getSemantics()), D);
15404 Recalc = true;
15405 }
15406 if (C.isInfinity() || D.isInfinity()) {
15407 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
15408 C);
15409 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
15410 D);
15411 if (A.isNaN())
15412 A = APFloat::copySign(APFloat(A.getSemantics()), A);
15413 if (B.isNaN())
15414 B = APFloat::copySign(APFloat(B.getSemantics()), B);
15415 Recalc = true;
15416 }
15417 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
15418 BC.isInfinity())) {
15419 if (A.isNaN())
15420 A = APFloat::copySign(APFloat(A.getSemantics()), A);
15421 if (B.isNaN())
15422 B = APFloat::copySign(APFloat(B.getSemantics()), B);
15423 if (C.isNaN())
15424 C = APFloat::copySign(APFloat(C.getSemantics()), C);
15425 if (D.isNaN())
15426 D = APFloat::copySign(APFloat(D.getSemantics()), D);
15427 Recalc = true;
15428 }
15429 if (Recalc) {
15430 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
15431 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
15432 }
15433 }
15434}
15435
15436void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
15437 APFloat &ResR, APFloat &ResI) {
15438 // This is an implementation of complex division according to the
15439 // constraints laid out in C11 Annex G. The implementation uses the
15440 // following naming scheme:
15441 // (a + ib) / (c + id)
15442
15443 int DenomLogB = 0;
15444 APFloat MaxCD = maxnum(abs(C), abs(D));
15445 if (MaxCD.isFinite()) {
15446 DenomLogB = ilogb(MaxCD);
15447 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
15448 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
15449 }
15450 APFloat Denom = C * C + D * D;
15451 ResR =
15452 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
15453 ResI =
15454 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
15455 if (ResR.isNaN() && ResI.isNaN()) {
15456 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
15457 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
15458 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
15459 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
15460 D.isFinite()) {
15461 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
15462 A);
15463 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
15464 B);
15465 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
15466 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
15467 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
15468 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
15469 C);
15470 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
15471 D);
15472 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
15473 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
15474 }
15475 }
15476}
15477
15478bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15479 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15480 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15481
15482 // Track whether the LHS or RHS is real at the type system level. When this is
15483 // the case we can simplify our evaluation strategy.
15484 bool LHSReal = false, RHSReal = false;
15485
15486 bool LHSOK;
15487 if (E->getLHS()->getType()->isRealFloatingType()) {
15488 LHSReal = true;
15489 APFloat &Real = Result.FloatReal;
15490 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
15491 if (LHSOK) {
15492 Result.makeComplexFloat();
15493 Result.FloatImag = APFloat(Real.getSemantics());
15494 }
15495 } else {
15496 LHSOK = Visit(E->getLHS());
15497 }
15498 if (!LHSOK && !Info.noteFailure())
15499 return false;
15500
15501 ComplexValue RHS;
15502 if (E->getRHS()->getType()->isRealFloatingType()) {
15503 RHSReal = true;
15504 APFloat &Real = RHS.FloatReal;
15505 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
15506 return false;
15507 RHS.makeComplexFloat();
15508 RHS.FloatImag = APFloat(Real.getSemantics());
15509 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
15510 return false;
15511
15512 assert(!(LHSReal && RHSReal) &&
15513 "Cannot have both operands of a complex operation be real.");
15514 switch (E->getOpcode()) {
15515 default: return Error(E);
15516 case BO_Add:
15517 if (Result.isComplexFloat()) {
15518 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
15519 APFloat::rmNearestTiesToEven);
15520 if (LHSReal)
15521 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
15522 else if (!RHSReal)
15523 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
15524 APFloat::rmNearestTiesToEven);
15525 } else {
15526 Result.getComplexIntReal() += RHS.getComplexIntReal();
15527 Result.getComplexIntImag() += RHS.getComplexIntImag();
15528 }
15529 break;
15530 case BO_Sub:
15531 if (Result.isComplexFloat()) {
15532 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
15533 APFloat::rmNearestTiesToEven);
15534 if (LHSReal) {
15535 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
15536 Result.getComplexFloatImag().changeSign();
15537 } else if (!RHSReal) {
15538 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
15539 APFloat::rmNearestTiesToEven);
15540 }
15541 } else {
15542 Result.getComplexIntReal() -= RHS.getComplexIntReal();
15543 Result.getComplexIntImag() -= RHS.getComplexIntImag();
15544 }
15545 break;
15546 case BO_Mul:
15547 if (Result.isComplexFloat()) {
15548 // This is an implementation of complex multiplication according to the
15549 // constraints laid out in C11 Annex G. The implementation uses the
15550 // following naming scheme:
15551 // (a + ib) * (c + id)
15552 ComplexValue LHS = Result;
15553 APFloat &A = LHS.getComplexFloatReal();
15554 APFloat &B = LHS.getComplexFloatImag();
15555 APFloat &C = RHS.getComplexFloatReal();
15556 APFloat &D = RHS.getComplexFloatImag();
15557 APFloat &ResR = Result.getComplexFloatReal();
15558 APFloat &ResI = Result.getComplexFloatImag();
15559 if (LHSReal) {
15560 assert(!RHSReal && "Cannot have two real operands for a complex op!");
15561 ResR = A;
15562 ResI = A;
15563 // ResR = A * C;
15564 // ResI = A * D;
15565 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
15566 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
15567 return false;
15568 } else if (RHSReal) {
15569 // ResR = C * A;
15570 // ResI = C * B;
15571 ResR = C;
15572 ResI = C;
15573 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
15574 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
15575 return false;
15576 } else {
15577 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
15578 }
15579 } else {
15580 ComplexValue LHS = Result;
15581 Result.getComplexIntReal() =
15582 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
15583 LHS.getComplexIntImag() * RHS.getComplexIntImag());
15584 Result.getComplexIntImag() =
15585 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
15586 LHS.getComplexIntImag() * RHS.getComplexIntReal());
15587 }
15588 break;
15589 case BO_Div:
15590 if (Result.isComplexFloat()) {
15591 // This is an implementation of complex division according to the
15592 // constraints laid out in C11 Annex G. The implementation uses the
15593 // following naming scheme:
15594 // (a + ib) / (c + id)
15595 ComplexValue LHS = Result;
15596 APFloat &A = LHS.getComplexFloatReal();
15597 APFloat &B = LHS.getComplexFloatImag();
15598 APFloat &C = RHS.getComplexFloatReal();
15599 APFloat &D = RHS.getComplexFloatImag();
15600 APFloat &ResR = Result.getComplexFloatReal();
15601 APFloat &ResI = Result.getComplexFloatImag();
15602 if (RHSReal) {
15603 ResR = A;
15604 ResI = B;
15605 // ResR = A / C;
15606 // ResI = B / C;
15607 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
15608 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
15609 return false;
15610 } else {
15611 if (LHSReal) {
15612 // No real optimizations we can do here, stub out with zero.
15613 B = APFloat::getZero(A.getSemantics());
15614 }
15615 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
15616 }
15617 } else {
15618 ComplexValue LHS = Result;
15619 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
15620 RHS.getComplexIntImag() * RHS.getComplexIntImag();
15621 if (Den.isZero())
15622 return Error(E, diag::note_expr_divide_by_zero);
15623
15624 Result.getComplexIntReal() =
15625 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
15626 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
15627 Result.getComplexIntImag() =
15628 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
15629 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
15630 }
15631 break;
15632 }
15633
15634 return true;
15635}
15636
15637bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15638 // Get the operand value into 'Result'.
15639 if (!Visit(E->getSubExpr()))
15640 return false;
15641
15642 switch (E->getOpcode()) {
15643 default:
15644 return Error(E);
15645 case UO_Extension:
15646 return true;
15647 case UO_Plus:
15648 // The result is always just the subexpr.
15649 return true;
15650 case UO_Minus:
15651 if (Result.isComplexFloat()) {
15652 Result.getComplexFloatReal().changeSign();
15653 Result.getComplexFloatImag().changeSign();
15654 }
15655 else {
15656 Result.getComplexIntReal() = -Result.getComplexIntReal();
15657 Result.getComplexIntImag() = -Result.getComplexIntImag();
15658 }
15659 return true;
15660 case UO_Not:
15661 if (Result.isComplexFloat())
15662 Result.getComplexFloatImag().changeSign();
15663 else
15664 Result.getComplexIntImag() = -Result.getComplexIntImag();
15665 return true;
15666 }
15667}
15668
15669bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
15670 if (E->getNumInits() == 2) {
15671 if (E->getType()->isComplexType()) {
15672 Result.makeComplexFloat();
15673 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
15674 return false;
15675 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
15676 return false;
15677 } else {
15678 Result.makeComplexInt();
15679 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
15680 return false;
15681 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
15682 return false;
15683 }
15684 return true;
15685 }
15686 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
15687}
15688
15689bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
15690 if (!IsConstantEvaluatedBuiltinCall(E))
15691 return ExprEvaluatorBaseTy::VisitCallExpr(E);
15692
15693 switch (E->getBuiltinCallee()) {
15694 case Builtin::BI__builtin_complex:
15695 Result.makeComplexFloat();
15696 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
15697 return false;
15698 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
15699 return false;
15700 return true;
15701
15702 default:
15703 return false;
15704 }
15705}
15706
15707//===----------------------------------------------------------------------===//
15708// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
15709// implicit conversion.
15710//===----------------------------------------------------------------------===//
15711
15712namespace {
15713class AtomicExprEvaluator :
15714 public ExprEvaluatorBase<AtomicExprEvaluator> {
15715 const LValue *This;
15716 APValue &Result;
15717public:
15718 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
15719 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
15720
15721 bool Success(const APValue &V, const Expr *E) {
15722 Result = V;
15723 return true;
15724 }
15725
15726 bool ZeroInitialization(const Expr *E) {
15729 // For atomic-qualified class (and array) types in C++, initialize the
15730 // _Atomic-wrapped subobject directly, in-place.
15731 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
15732 : Evaluate(Result, Info, &VIE);
15733 }
15734
15735 bool VisitCastExpr(const CastExpr *E) {
15736 switch (E->getCastKind()) {
15737 default:
15738 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15739 case CK_NullToPointer:
15740 VisitIgnoredValue(E->getSubExpr());
15741 return ZeroInitialization(E);
15742 case CK_NonAtomicToAtomic:
15743 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
15744 : Evaluate(Result, Info, E->getSubExpr());
15745 }
15746 }
15747};
15748} // end anonymous namespace
15749
15750static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
15751 EvalInfo &Info) {
15752 assert(!E->isValueDependent());
15753 assert(E->isPRValue() && E->getType()->isAtomicType());
15754 return AtomicExprEvaluator(Info, This, Result).Visit(E);
15755}
15756
15757//===----------------------------------------------------------------------===//
15758// Void expression evaluation, primarily for a cast to void on the LHS of a
15759// comma operator
15760//===----------------------------------------------------------------------===//
15761
15762namespace {
15763class VoidExprEvaluator
15764 : public ExprEvaluatorBase<VoidExprEvaluator> {
15765public:
15766 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
15767
15768 bool Success(const APValue &V, const Expr *e) { return true; }
15769
15770 bool ZeroInitialization(const Expr *E) { return true; }
15771
15772 bool VisitCastExpr(const CastExpr *E) {
15773 switch (E->getCastKind()) {
15774 default:
15775 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15776 case CK_ToVoid:
15777 VisitIgnoredValue(E->getSubExpr());
15778 return true;
15779 }
15780 }
15781
15782 bool VisitCallExpr(const CallExpr *E) {
15783 if (!IsConstantEvaluatedBuiltinCall(E))
15784 return ExprEvaluatorBaseTy::VisitCallExpr(E);
15785
15786 switch (E->getBuiltinCallee()) {
15787 case Builtin::BI__assume:
15788 case Builtin::BI__builtin_assume:
15789 // The argument is not evaluated!
15790 return true;
15791
15792 case Builtin::BI__builtin_operator_delete:
15793 return HandleOperatorDeleteCall(Info, E);
15794
15795 default:
15796 return false;
15797 }
15798 }
15799
15800 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
15801};
15802} // end anonymous namespace
15803
15804bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
15805 // We cannot speculatively evaluate a delete expression.
15806 if (Info.SpeculativeEvaluationDepth)
15807 return false;
15808
15809 FunctionDecl *OperatorDelete = E->getOperatorDelete();
15810 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
15811 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
15812 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
15813 return false;
15814 }
15815
15816 const Expr *Arg = E->getArgument();
15817
15818 LValue Pointer;
15819 if (!EvaluatePointer(Arg, Pointer, Info))
15820 return false;
15821 if (Pointer.Designator.Invalid)
15822 return false;
15823
15824 // Deleting a null pointer has no effect.
15825 if (Pointer.isNullPointer()) {
15826 // This is the only case where we need to produce an extension warning:
15827 // the only other way we can succeed is if we find a dynamic allocation,
15828 // and we will have warned when we allocated it in that case.
15829 if (!Info.getLangOpts().CPlusPlus20)
15830 Info.CCEDiag(E, diag::note_constexpr_new);
15831 return true;
15832 }
15833
15834 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
15835 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
15836 if (!Alloc)
15837 return false;
15838 QualType AllocType = Pointer.Base.getDynamicAllocType();
15839
15840 // For the non-array case, the designator must be empty if the static type
15841 // does not have a virtual destructor.
15842 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
15844 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
15845 << Arg->getType()->getPointeeType() << AllocType;
15846 return false;
15847 }
15848
15849 // For a class type with a virtual destructor, the selected operator delete
15850 // is the one looked up when building the destructor.
15851 if (!E->isArrayForm() && !E->isGlobalDelete()) {
15852 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
15853 if (VirtualDelete &&
15854 !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
15855 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
15856 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
15857 return false;
15858 }
15859 }
15860
15861 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
15862 (*Alloc)->Value, AllocType))
15863 return false;
15864
15865 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
15866 // The element was already erased. This means the destructor call also
15867 // deleted the object.
15868 // FIXME: This probably results in undefined behavior before we get this
15869 // far, and should be diagnosed elsewhere first.
15870 Info.FFDiag(E, diag::note_constexpr_double_delete);
15871 return false;
15872 }
15873
15874 return true;
15875}
15876
15877static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
15878 assert(!E->isValueDependent());
15879 assert(E->isPRValue() && E->getType()->isVoidType());
15880 return VoidExprEvaluator(Info).Visit(E);
15881}
15882
15883//===----------------------------------------------------------------------===//
15884// Top level Expr::EvaluateAsRValue method.
15885//===----------------------------------------------------------------------===//
15886
15887static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
15888 assert(!E->isValueDependent());
15889 // In C, function designators are not lvalues, but we evaluate them as if they
15890 // are.
15891 QualType T = E->getType();
15892 if (E->isGLValue() || T->isFunctionType()) {
15893 LValue LV;
15894 if (!EvaluateLValue(E, LV, Info))
15895 return false;
15896 LV.moveInto(Result);
15897 } else if (T->isVectorType()) {
15898 if (!EvaluateVector(E, Result, Info))
15899 return false;
15900 } else if (T->isIntegralOrEnumerationType()) {
15901 if (!IntExprEvaluator(Info, Result).Visit(E))
15902 return false;
15903 } else if (T->hasPointerRepresentation()) {
15904 LValue LV;
15905 if (!EvaluatePointer(E, LV, Info))
15906 return false;
15907 LV.moveInto(Result);
15908 } else if (T->isRealFloatingType()) {
15909 llvm::APFloat F(0.0);
15910 if (!EvaluateFloat(E, F, Info))
15911 return false;
15912 Result = APValue(F);
15913 } else if (T->isAnyComplexType()) {
15914 ComplexValue C;
15915 if (!EvaluateComplex(E, C, Info))
15916 return false;
15917 C.moveInto(Result);
15918 } else if (T->isFixedPointType()) {
15919 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
15920 } else if (T->isMemberPointerType()) {
15921 MemberPtr P;
15922 if (!EvaluateMemberPointer(E, P, Info))
15923 return false;
15924 P.moveInto(Result);
15925 return true;
15926 } else if (T->isArrayType()) {
15927 LValue LV;
15928 APValue &Value =
15929 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15930 if (!EvaluateArray(E, LV, Value, Info))
15931 return false;
15932 Result = Value;
15933 } else if (T->isRecordType()) {
15934 LValue LV;
15935 APValue &Value =
15936 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15937 if (!EvaluateRecord(E, LV, Value, Info))
15938 return false;
15939 Result = Value;
15940 } else if (T->isVoidType()) {
15941 if (!Info.getLangOpts().CPlusPlus11)
15942 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
15943 << E->getType();
15944 if (!EvaluateVoid(E, Info))
15945 return false;
15946 } else if (T->isAtomicType()) {
15947 QualType Unqual = T.getAtomicUnqualifiedType();
15948 if (Unqual->isArrayType() || Unqual->isRecordType()) {
15949 LValue LV;
15950 APValue &Value = Info.CurrentCall->createTemporary(
15951 E, Unqual, ScopeKind::FullExpression, LV);
15952 if (!EvaluateAtomic(E, &LV, Value, Info))
15953 return false;
15954 Result = Value;
15955 } else {
15956 if (!EvaluateAtomic(E, nullptr, Result, Info))
15957 return false;
15958 }
15959 } else if (Info.getLangOpts().CPlusPlus11) {
15960 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
15961 return false;
15962 } else {
15963 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15964 return false;
15965 }
15966
15967 return true;
15968}
15969
15970/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
15971/// cases, the in-place evaluation is essential, since later initializers for
15972/// an object can indirectly refer to subobjects which were initialized earlier.
15973static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
15974 const Expr *E, bool AllowNonLiteralTypes) {
15975 assert(!E->isValueDependent());
15976
15977 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
15978 return false;
15979
15980 if (E->isPRValue()) {
15981 // Evaluate arrays and record types in-place, so that later initializers can
15982 // refer to earlier-initialized members of the object.
15983 QualType T = E->getType();
15984 if (T->isArrayType())
15985 return EvaluateArray(E, This, Result, Info);
15986 else if (T->isRecordType())
15987 return EvaluateRecord(E, This, Result, Info);
15988 else if (T->isAtomicType()) {
15989 QualType Unqual = T.getAtomicUnqualifiedType();
15990 if (Unqual->isArrayType() || Unqual->isRecordType())
15991 return EvaluateAtomic(E, &This, Result, Info);
15992 }
15993 }
15994
15995 // For any other type, in-place evaluation is unimportant.
15996 return Evaluate(Result, Info, E);
15997}
15998
15999/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
16000/// lvalue-to-rvalue cast if it is an lvalue.
16001static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
16002 assert(!E->isValueDependent());
16003
16004 if (E->getType().isNull())
16005 return false;
16006
16007 if (!CheckLiteralType(Info, E))
16008 return false;
16009
16010 if (Info.EnableNewConstInterp) {
16011 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
16012 return false;
16013 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
16014 ConstantExprKind::Normal);
16015 }
16016
16017 if (!::Evaluate(Result, Info, E))
16018 return false;
16019
16020 // Implicit lvalue-to-rvalue cast.
16021 if (E->isGLValue()) {
16022 LValue LV;
16023 LV.setFrom(Info.Ctx, Result);
16024 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
16025 return false;
16026 }
16027
16028 // Check this core constant expression is a constant expression.
16029 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
16030 ConstantExprKind::Normal) &&
16031 CheckMemoryLeaks(Info);
16032}
16033
16034static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
16035 const ASTContext &Ctx, bool &IsConst) {
16036 // Fast-path evaluations of integer literals, since we sometimes see files
16037 // containing vast quantities of these.
16038 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
16039 Result.Val = APValue(APSInt(L->getValue(),
16040 L->getType()->isUnsignedIntegerType()));
16041 IsConst = true;
16042 return true;
16043 }
16044
16045 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
16046 Result.Val = APValue(APSInt(APInt(1, L->getValue())));
16047 IsConst = true;
16048 return true;
16049 }
16050
16051 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
16052 if (CE->hasAPValueResult()) {
16053 APValue APV = CE->getAPValueResult();
16054 if (!APV.isLValue()) {
16055 Result.Val = std::move(APV);
16056 IsConst = true;
16057 return true;
16058 }
16059 }
16060
16061 // The SubExpr is usually just an IntegerLiteral.
16062 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
16063 }
16064
16065 // This case should be rare, but we need to check it before we check on
16066 // the type below.
16067 if (Exp->getType().isNull()) {
16068 IsConst = false;
16069 return true;
16070 }
16071
16072 return false;
16073}
16074
16077 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
16078 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
16079}
16080
16081static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
16082 const ASTContext &Ctx, EvalInfo &Info) {
16083 assert(!E->isValueDependent());
16084 bool IsConst;
16085 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
16086 return IsConst;
16087
16088 return EvaluateAsRValue(Info, E, Result.Val);
16089}
16090
16092 const ASTContext &Ctx,
16093 Expr::SideEffectsKind AllowSideEffects,
16094 EvalInfo &Info) {
16095 assert(!E->isValueDependent());
16097 return false;
16098
16099 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
16100 !ExprResult.Val.isInt() ||
16101 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16102 return false;
16103
16104 return true;
16105}
16106
16108 const ASTContext &Ctx,
16109 Expr::SideEffectsKind AllowSideEffects,
16110 EvalInfo &Info) {
16111 assert(!E->isValueDependent());
16112 if (!E->getType()->isFixedPointType())
16113 return false;
16114
16115 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
16116 return false;
16117
16118 if (!ExprResult.Val.isFixedPoint() ||
16119 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16120 return false;
16121
16122 return true;
16123}
16124
16125/// EvaluateAsRValue - Return true if this is a constant which we can fold using
16126/// any crazy technique (that has nothing to do with language standards) that
16127/// we want to. If this function returns true, it returns the folded constant
16128/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
16129/// will be applied to the result.
16131 bool InConstantContext) const {
16132 assert(!isValueDependent() &&
16133 "Expression evaluator can't be called on a dependent expression.");
16134 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
16135 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16136 Info.InConstantContext = InConstantContext;
16137 return ::EvaluateAsRValue(this, Result, Ctx, Info);
16138}
16139
16140bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
16141 bool InConstantContext) const {
16142 assert(!isValueDependent() &&
16143 "Expression evaluator can't be called on a dependent expression.");
16144 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
16145 EvalResult Scratch;
16146 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
16147 HandleConversionToBool(Scratch.Val, Result);
16148}
16149
16151 SideEffectsKind AllowSideEffects,
16152 bool InConstantContext) const {
16153 assert(!isValueDependent() &&
16154 "Expression evaluator can't be called on a dependent expression.");
16155 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
16156 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16157 Info.InConstantContext = InConstantContext;
16158 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
16159}
16160
16162 SideEffectsKind AllowSideEffects,
16163 bool InConstantContext) const {
16164 assert(!isValueDependent() &&
16165 "Expression evaluator can't be called on a dependent expression.");
16166 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
16167 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16168 Info.InConstantContext = InConstantContext;
16169 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
16170}
16171
16172bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
16173 SideEffectsKind AllowSideEffects,
16174 bool InConstantContext) const {
16175 assert(!isValueDependent() &&
16176 "Expression evaluator can't be called on a dependent expression.");
16177
16178 if (!getType()->isRealFloatingType())
16179 return false;
16180
16181 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
16183 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
16184 !ExprResult.Val.isFloat() ||
16185 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16186 return false;
16187
16188 Result = ExprResult.Val.getFloat();
16189 return true;
16190}
16191
16193 bool InConstantContext) const {
16194 assert(!isValueDependent() &&
16195 "Expression evaluator can't be called on a dependent expression.");
16196
16197 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
16198 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
16199 Info.InConstantContext = InConstantContext;
16200 LValue LV;
16201 CheckedTemporaries CheckedTemps;
16202 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
16203 Result.HasSideEffects ||
16204 !CheckLValueConstantExpression(Info, getExprLoc(),
16205 Ctx.getLValueReferenceType(getType()), LV,
16206 ConstantExprKind::Normal, CheckedTemps))
16207 return false;
16208
16209 LV.moveInto(Result.Val);
16210 return true;
16211}
16212
16214 APValue DestroyedValue, QualType Type,
16216 bool IsConstantDestruction) {
16217 EvalInfo Info(Ctx, EStatus,
16218 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
16219 : EvalInfo::EM_ConstantFold);
16220 Info.setEvaluatingDecl(Base, DestroyedValue,
16221 EvalInfo::EvaluatingDeclKind::Dtor);
16222 Info.InConstantContext = IsConstantDestruction;
16223
16224 LValue LVal;
16225 LVal.set(Base);
16226
16227 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
16228 EStatus.HasSideEffects)
16229 return false;
16230
16231 if (!Info.discardCleanups())
16232 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16233
16234 return true;
16235}
16236
16238 ConstantExprKind Kind) const {
16239 assert(!isValueDependent() &&
16240 "Expression evaluator can't be called on a dependent expression.");
16241 bool IsConst;
16242 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue())
16243 return true;
16244
16245 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
16246 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
16247 EvalInfo Info(Ctx, Result, EM);
16248 Info.InConstantContext = true;
16249
16250 if (Info.EnableNewConstInterp) {
16251 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val))
16252 return false;
16253 return CheckConstantExpression(Info, getExprLoc(),
16254 getStorageType(Ctx, this), Result.Val, Kind);
16255 }
16256
16257 // The type of the object we're initializing is 'const T' for a class NTTP.
16258 QualType T = getType();
16259 if (Kind == ConstantExprKind::ClassTemplateArgument)
16260 T.addConst();
16261
16262 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
16263 // represent the result of the evaluation. CheckConstantExpression ensures
16264 // this doesn't escape.
16265 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
16266 APValue::LValueBase Base(&BaseMTE);
16267 Info.setEvaluatingDecl(Base, Result.Val);
16268
16269 if (Info.EnableNewConstInterp) {
16270 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, this, Result.Val))
16271 return false;
16272 } else {
16273 LValue LVal;
16274 LVal.set(Base);
16275 // C++23 [intro.execution]/p5
16276 // A full-expression is [...] a constant-expression
16277 // So we need to make sure temporary objects are destroyed after having
16278 // evaluating the expression (per C++23 [class.temporary]/p4).
16279 FullExpressionRAII Scope(Info);
16280 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
16281 Result.HasSideEffects || !Scope.destroy())
16282 return false;
16283
16284 if (!Info.discardCleanups())
16285 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16286 }
16287
16288 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
16289 Result.Val, Kind))
16290 return false;
16291 if (!CheckMemoryLeaks(Info))
16292 return false;
16293
16294 // If this is a class template argument, it's required to have constant
16295 // destruction too.
16296 if (Kind == ConstantExprKind::ClassTemplateArgument &&
16297 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
16298 true) ||
16299 Result.HasSideEffects)) {
16300 // FIXME: Prefix a note to indicate that the problem is lack of constant
16301 // destruction.
16302 return false;
16303 }
16304
16305 return true;
16306}
16307
16309 const VarDecl *VD,
16311 bool IsConstantInitialization) const {
16312 assert(!isValueDependent() &&
16313 "Expression evaluator can't be called on a dependent expression.");
16314
16315 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
16316 std::string Name;
16317 llvm::raw_string_ostream OS(Name);
16318 VD->printQualifiedName(OS);
16319 return Name;
16320 });
16321
16322 Expr::EvalStatus EStatus;
16323 EStatus.Diag = &Notes;
16324
16325 EvalInfo Info(Ctx, EStatus,
16326 (IsConstantInitialization &&
16327 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
16328 ? EvalInfo::EM_ConstantExpression
16329 : EvalInfo::EM_ConstantFold);
16330 Info.setEvaluatingDecl(VD, Value);
16331 Info.InConstantContext = IsConstantInitialization;
16332
16333 SourceLocation DeclLoc = VD->getLocation();
16334 QualType DeclTy = VD->getType();
16335
16336 if (Info.EnableNewConstInterp) {
16337 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
16338 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
16339 return false;
16340
16341 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
16342 ConstantExprKind::Normal);
16343 } else {
16344 LValue LVal;
16345 LVal.set(VD);
16346
16347 {
16348 // C++23 [intro.execution]/p5
16349 // A full-expression is ... an init-declarator ([dcl.decl]) or a
16350 // mem-initializer.
16351 // So we need to make sure temporary objects are destroyed after having
16352 // evaluated the expression (per C++23 [class.temporary]/p4).
16353 //
16354 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
16355 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
16356 // outermost FullExpr, such as ExprWithCleanups.
16357 FullExpressionRAII Scope(Info);
16358 if (!EvaluateInPlace(Value, Info, LVal, this,
16359 /*AllowNonLiteralTypes=*/true) ||
16360 EStatus.HasSideEffects)
16361 return false;
16362 }
16363
16364 // At this point, any lifetime-extended temporaries are completely
16365 // initialized.
16366 Info.performLifetimeExtension();
16367
16368 if (!Info.discardCleanups())
16369 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16370 }
16371
16372 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
16373 ConstantExprKind::Normal) &&
16374 CheckMemoryLeaks(Info);
16375}
16376
16379 Expr::EvalStatus EStatus;
16380 EStatus.Diag = &Notes;
16381
16382 // Only treat the destruction as constant destruction if we formally have
16383 // constant initialization (or are usable in a constant expression).
16384 bool IsConstantDestruction = hasConstantInitialization();
16385
16386 // Make a copy of the value for the destructor to mutate, if we know it.
16387 // Otherwise, treat the value as default-initialized; if the destructor works
16388 // anyway, then the destruction is constant (and must be essentially empty).
16389 APValue DestroyedValue;
16390 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
16391 DestroyedValue = *getEvaluatedValue();
16392 else if (!handleDefaultInitValue(getType(), DestroyedValue))
16393 return false;
16394
16395 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
16396 getType(), getLocation(), EStatus,
16397 IsConstantDestruction) ||
16398 EStatus.HasSideEffects)
16399 return false;
16400
16401 ensureEvaluatedStmt()->HasConstantDestruction = true;
16402 return true;
16403}
16404
16405/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
16406/// constant folded, but discard the result.
16408 assert(!isValueDependent() &&
16409 "Expression evaluator can't be called on a dependent expression.");
16410
16411 EvalResult Result;
16412 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
16413 !hasUnacceptableSideEffect(Result, SEK);
16414}
16415
16418 assert(!isValueDependent() &&
16419 "Expression evaluator can't be called on a dependent expression.");
16420
16421 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
16422 EvalResult EVResult;
16423 EVResult.Diag = Diag;
16424 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16425 Info.InConstantContext = true;
16426
16427 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
16428 (void)Result;
16429 assert(Result && "Could not evaluate expression");
16430 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
16431
16432 return EVResult.Val.getInt();
16433}
16434
16437 assert(!isValueDependent() &&
16438 "Expression evaluator can't be called on a dependent expression.");
16439
16440 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
16441 EvalResult EVResult;
16442 EVResult.Diag = Diag;
16443 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16444 Info.InConstantContext = true;
16445 Info.CheckingForUndefinedBehavior = true;
16446
16447 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
16448 (void)Result;
16449 assert(Result && "Could not evaluate expression");
16450 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
16451
16452 return EVResult.Val.getInt();
16453}
16454
16456 assert(!isValueDependent() &&
16457 "Expression evaluator can't be called on a dependent expression.");
16458
16459 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
16460 bool IsConst;
16461 EvalResult EVResult;
16462 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
16463 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16464 Info.CheckingForUndefinedBehavior = true;
16465 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
16466 }
16467}
16468
16470 assert(Val.isLValue());
16471 return IsGlobalLValue(Val.getLValueBase());
16472}
16473
16474/// isIntegerConstantExpr - this recursive routine will test if an expression is
16475/// an integer constant expression.
16476
16477/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
16478/// comma, etc
16479
16480// CheckICE - This function does the fundamental ICE checking: the returned
16481// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
16482// and a (possibly null) SourceLocation indicating the location of the problem.
16483//
16484// Note that to reduce code duplication, this helper does no evaluation
16485// itself; the caller checks whether the expression is evaluatable, and
16486// in the rare cases where CheckICE actually cares about the evaluated
16487// value, it calls into Evaluate.
16488
16489namespace {
16490
16491enum ICEKind {
16492 /// This expression is an ICE.
16493 IK_ICE,
16494 /// This expression is not an ICE, but if it isn't evaluated, it's
16495 /// a legal subexpression for an ICE. This return value is used to handle
16496 /// the comma operator in C99 mode, and non-constant subexpressions.
16497 IK_ICEIfUnevaluated,
16498 /// This expression is not an ICE, and is not a legal subexpression for one.
16499 IK_NotICE
16500};
16501
16502struct ICEDiag {
16503 ICEKind Kind;
16505
16506 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
16507};
16508
16509}
16510
16511static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
16512
16513static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
16514
16515static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
16516 Expr::EvalResult EVResult;
16517 Expr::EvalStatus Status;
16518 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16519
16520 Info.InConstantContext = true;
16521 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
16522 !EVResult.Val.isInt())
16523 return ICEDiag(IK_NotICE, E->getBeginLoc());
16524
16525 return NoDiag();
16526}
16527
16528static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
16529 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
16531 return ICEDiag(IK_NotICE, E->getBeginLoc());
16532
16533 switch (E->getStmtClass()) {
16534#define ABSTRACT_STMT(Node)
16535#define STMT(Node, Base) case Expr::Node##Class:
16536#define EXPR(Node, Base)
16537#include "clang/AST/StmtNodes.inc"
16538 case Expr::PredefinedExprClass:
16539 case Expr::FloatingLiteralClass:
16540 case Expr::ImaginaryLiteralClass:
16541 case Expr::StringLiteralClass:
16542 case Expr::ArraySubscriptExprClass:
16543 case Expr::MatrixSubscriptExprClass:
16544 case Expr::ArraySectionExprClass:
16545 case Expr::OMPArrayShapingExprClass:
16546 case Expr::OMPIteratorExprClass:
16547 case Expr::MemberExprClass:
16548 case Expr::CompoundAssignOperatorClass:
16549 case Expr::CompoundLiteralExprClass:
16550 case Expr::ExtVectorElementExprClass:
16551 case Expr::DesignatedInitExprClass:
16552 case Expr::ArrayInitLoopExprClass:
16553 case Expr::ArrayInitIndexExprClass:
16554 case Expr::NoInitExprClass:
16555 case Expr::DesignatedInitUpdateExprClass:
16556 case Expr::ImplicitValueInitExprClass:
16557 case Expr::ParenListExprClass:
16558 case Expr::VAArgExprClass:
16559 case Expr::AddrLabelExprClass:
16560 case Expr::StmtExprClass:
16561 case Expr::CXXMemberCallExprClass:
16562 case Expr::CUDAKernelCallExprClass:
16563 case Expr::CXXAddrspaceCastExprClass:
16564 case Expr::CXXDynamicCastExprClass:
16565 case Expr::CXXTypeidExprClass:
16566 case Expr::CXXUuidofExprClass:
16567 case Expr::MSPropertyRefExprClass:
16568 case Expr::MSPropertySubscriptExprClass:
16569 case Expr::CXXNullPtrLiteralExprClass:
16570 case Expr::UserDefinedLiteralClass:
16571 case Expr::CXXThisExprClass:
16572 case Expr::CXXThrowExprClass:
16573 case Expr::CXXNewExprClass:
16574 case Expr::CXXDeleteExprClass:
16575 case Expr::CXXPseudoDestructorExprClass:
16576 case Expr::UnresolvedLookupExprClass:
16577 case Expr::TypoExprClass:
16578 case Expr::RecoveryExprClass:
16579 case Expr::DependentScopeDeclRefExprClass:
16580 case Expr::CXXConstructExprClass:
16581 case Expr::CXXInheritedCtorInitExprClass:
16582 case Expr::CXXStdInitializerListExprClass:
16583 case Expr::CXXBindTemporaryExprClass:
16584 case Expr::ExprWithCleanupsClass:
16585 case Expr::CXXTemporaryObjectExprClass:
16586 case Expr::CXXUnresolvedConstructExprClass:
16587 case Expr::CXXDependentScopeMemberExprClass:
16588 case Expr::UnresolvedMemberExprClass:
16589 case Expr::ObjCStringLiteralClass:
16590 case Expr::ObjCBoxedExprClass:
16591 case Expr::ObjCArrayLiteralClass:
16592 case Expr::ObjCDictionaryLiteralClass:
16593 case Expr::ObjCEncodeExprClass:
16594 case Expr::ObjCMessageExprClass:
16595 case Expr::ObjCSelectorExprClass:
16596 case Expr::ObjCProtocolExprClass:
16597 case Expr::ObjCIvarRefExprClass:
16598 case Expr::ObjCPropertyRefExprClass:
16599 case Expr::ObjCSubscriptRefExprClass:
16600 case Expr::ObjCIsaExprClass:
16601 case Expr::ObjCAvailabilityCheckExprClass:
16602 case Expr::ShuffleVectorExprClass:
16603 case Expr::ConvertVectorExprClass:
16604 case Expr::BlockExprClass:
16605 case Expr::NoStmtClass:
16606 case Expr::OpaqueValueExprClass:
16607 case Expr::PackExpansionExprClass:
16608 case Expr::SubstNonTypeTemplateParmPackExprClass:
16609 case Expr::FunctionParmPackExprClass:
16610 case Expr::AsTypeExprClass:
16611 case Expr::ObjCIndirectCopyRestoreExprClass:
16612 case Expr::MaterializeTemporaryExprClass:
16613 case Expr::PseudoObjectExprClass:
16614 case Expr::AtomicExprClass:
16615 case Expr::LambdaExprClass:
16616 case Expr::CXXFoldExprClass:
16617 case Expr::CoawaitExprClass:
16618 case Expr::DependentCoawaitExprClass:
16619 case Expr::CoyieldExprClass:
16620 case Expr::SYCLUniqueStableNameExprClass:
16621 case Expr::CXXParenListInitExprClass:
16622 return ICEDiag(IK_NotICE, E->getBeginLoc());
16623
16624 case Expr::InitListExprClass: {
16625 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
16626 // form "T x = { a };" is equivalent to "T x = a;".
16627 // Unless we're initializing a reference, T is a scalar as it is known to be
16628 // of integral or enumeration type.
16629 if (E->isPRValue())
16630 if (cast<InitListExpr>(E)->getNumInits() == 1)
16631 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
16632 return ICEDiag(IK_NotICE, E->getBeginLoc());
16633 }
16634
16635 case Expr::SizeOfPackExprClass:
16636 case Expr::GNUNullExprClass:
16637 case Expr::SourceLocExprClass:
16638 case Expr::EmbedExprClass:
16639 return NoDiag();
16640
16641 case Expr::PackIndexingExprClass:
16642 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
16643
16644 case Expr::SubstNonTypeTemplateParmExprClass:
16645 return
16646 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
16647
16648 case Expr::ConstantExprClass:
16649 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
16650
16651 case Expr::ParenExprClass:
16652 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
16653 case Expr::GenericSelectionExprClass:
16654 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
16655 case Expr::IntegerLiteralClass:
16656 case Expr::FixedPointLiteralClass:
16657 case Expr::CharacterLiteralClass:
16658 case Expr::ObjCBoolLiteralExprClass:
16659 case Expr::CXXBoolLiteralExprClass:
16660 case Expr::CXXScalarValueInitExprClass:
16661 case Expr::TypeTraitExprClass:
16662 case Expr::ConceptSpecializationExprClass:
16663 case Expr::RequiresExprClass:
16664 case Expr::ArrayTypeTraitExprClass:
16665 case Expr::ExpressionTraitExprClass:
16666 case Expr::CXXNoexceptExprClass:
16667 return NoDiag();
16668 case Expr::CallExprClass:
16669 case Expr::CXXOperatorCallExprClass: {
16670 // C99 6.6/3 allows function calls within unevaluated subexpressions of
16671 // constant expressions, but they can never be ICEs because an ICE cannot
16672 // contain an operand of (pointer to) function type.
16673 const CallExpr *CE = cast<CallExpr>(E);
16674 if (CE->getBuiltinCallee())
16675 return CheckEvalInICE(E, Ctx);
16676 return ICEDiag(IK_NotICE, E->getBeginLoc());
16677 }
16678 case Expr::CXXRewrittenBinaryOperatorClass:
16679 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
16680 Ctx);
16681 case Expr::DeclRefExprClass: {
16682 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
16683 if (isa<EnumConstantDecl>(D))
16684 return NoDiag();
16685
16686 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
16687 // integer variables in constant expressions:
16688 //
16689 // C++ 7.1.5.1p2
16690 // A variable of non-volatile const-qualified integral or enumeration
16691 // type initialized by an ICE can be used in ICEs.
16692 //
16693 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
16694 // that mode, use of reference variables should not be allowed.
16695 const VarDecl *VD = dyn_cast<VarDecl>(D);
16696 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
16697 !VD->getType()->isReferenceType())
16698 return NoDiag();
16699
16700 return ICEDiag(IK_NotICE, E->getBeginLoc());
16701 }
16702 case Expr::UnaryOperatorClass: {
16703 const UnaryOperator *Exp = cast<UnaryOperator>(E);
16704 switch (Exp->getOpcode()) {
16705 case UO_PostInc:
16706 case UO_PostDec:
16707 case UO_PreInc:
16708 case UO_PreDec:
16709 case UO_AddrOf:
16710 case UO_Deref:
16711 case UO_Coawait:
16712 // C99 6.6/3 allows increment and decrement within unevaluated
16713 // subexpressions of constant expressions, but they can never be ICEs
16714 // because an ICE cannot contain an lvalue operand.
16715 return ICEDiag(IK_NotICE, E->getBeginLoc());
16716 case UO_Extension:
16717 case UO_LNot:
16718 case UO_Plus:
16719 case UO_Minus:
16720 case UO_Not:
16721 case UO_Real:
16722 case UO_Imag:
16723 return CheckICE(Exp->getSubExpr(), Ctx);
16724 }
16725 llvm_unreachable("invalid unary operator class");
16726 }
16727 case Expr::OffsetOfExprClass: {
16728 // Note that per C99, offsetof must be an ICE. And AFAIK, using
16729 // EvaluateAsRValue matches the proposed gcc behavior for cases like
16730 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
16731 // compliance: we should warn earlier for offsetof expressions with
16732 // array subscripts that aren't ICEs, and if the array subscripts
16733 // are ICEs, the value of the offsetof must be an integer constant.
16734 return CheckEvalInICE(E, Ctx);
16735 }
16736 case Expr::UnaryExprOrTypeTraitExprClass: {
16737 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
16738 if ((Exp->getKind() == UETT_SizeOf) &&
16740 return ICEDiag(IK_NotICE, E->getBeginLoc());
16741 return NoDiag();
16742 }
16743 case Expr::BinaryOperatorClass: {
16744 const BinaryOperator *Exp = cast<BinaryOperator>(E);
16745 switch (Exp->getOpcode()) {
16746 case BO_PtrMemD:
16747 case BO_PtrMemI:
16748 case BO_Assign:
16749 case BO_MulAssign:
16750 case BO_DivAssign:
16751 case BO_RemAssign:
16752 case BO_AddAssign:
16753 case BO_SubAssign:
16754 case BO_ShlAssign:
16755 case BO_ShrAssign:
16756 case BO_AndAssign:
16757 case BO_XorAssign:
16758 case BO_OrAssign:
16759 // C99 6.6/3 allows assignments within unevaluated subexpressions of
16760 // constant expressions, but they can never be ICEs because an ICE cannot
16761 // contain an lvalue operand.
16762 return ICEDiag(IK_NotICE, E->getBeginLoc());
16763
16764 case BO_Mul:
16765 case BO_Div:
16766 case BO_Rem:
16767 case BO_Add:
16768 case BO_Sub:
16769 case BO_Shl:
16770 case BO_Shr:
16771 case BO_LT:
16772 case BO_GT:
16773 case BO_LE:
16774 case BO_GE:
16775 case BO_EQ:
16776 case BO_NE:
16777 case BO_And:
16778 case BO_Xor:
16779 case BO_Or:
16780 case BO_Comma:
16781 case BO_Cmp: {
16782 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
16783 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
16784 if (Exp->getOpcode() == BO_Div ||
16785 Exp->getOpcode() == BO_Rem) {
16786 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
16787 // we don't evaluate one.
16788 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
16789 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
16790 if (REval == 0)
16791 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16792 if (REval.isSigned() && REval.isAllOnes()) {
16793 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
16794 if (LEval.isMinSignedValue())
16795 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16796 }
16797 }
16798 }
16799 if (Exp->getOpcode() == BO_Comma) {
16800 if (Ctx.getLangOpts().C99) {
16801 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
16802 // if it isn't evaluated.
16803 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
16804 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16805 } else {
16806 // In both C89 and C++, commas in ICEs are illegal.
16807 return ICEDiag(IK_NotICE, E->getBeginLoc());
16808 }
16809 }
16810 return Worst(LHSResult, RHSResult);
16811 }
16812 case BO_LAnd:
16813 case BO_LOr: {
16814 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
16815 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
16816 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
16817 // Rare case where the RHS has a comma "side-effect"; we need
16818 // to actually check the condition to see whether the side
16819 // with the comma is evaluated.
16820 if ((Exp->getOpcode() == BO_LAnd) !=
16821 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
16822 return RHSResult;
16823 return NoDiag();
16824 }
16825
16826 return Worst(LHSResult, RHSResult);
16827 }
16828 }
16829 llvm_unreachable("invalid binary operator kind");
16830 }
16831 case Expr::ImplicitCastExprClass:
16832 case Expr::CStyleCastExprClass:
16833 case Expr::CXXFunctionalCastExprClass:
16834 case Expr::CXXStaticCastExprClass:
16835 case Expr::CXXReinterpretCastExprClass:
16836 case Expr::CXXConstCastExprClass:
16837 case Expr::ObjCBridgedCastExprClass: {
16838 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
16839 if (isa<ExplicitCastExpr>(E)) {
16840 if (const FloatingLiteral *FL
16841 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
16842 unsigned DestWidth = Ctx.getIntWidth(E->getType());
16843 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
16844 APSInt IgnoredVal(DestWidth, !DestSigned);
16845 bool Ignored;
16846 // If the value does not fit in the destination type, the behavior is
16847 // undefined, so we are not required to treat it as a constant
16848 // expression.
16849 if (FL->getValue().convertToInteger(IgnoredVal,
16850 llvm::APFloat::rmTowardZero,
16851 &Ignored) & APFloat::opInvalidOp)
16852 return ICEDiag(IK_NotICE, E->getBeginLoc());
16853 return NoDiag();
16854 }
16855 }
16856 switch (cast<CastExpr>(E)->getCastKind()) {
16857 case CK_LValueToRValue:
16858 case CK_AtomicToNonAtomic:
16859 case CK_NonAtomicToAtomic:
16860 case CK_NoOp:
16861 case CK_IntegralToBoolean:
16862 case CK_IntegralCast:
16863 return CheckICE(SubExpr, Ctx);
16864 default:
16865 return ICEDiag(IK_NotICE, E->getBeginLoc());
16866 }
16867 }
16868 case Expr::BinaryConditionalOperatorClass: {
16869 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
16870 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
16871 if (CommonResult.Kind == IK_NotICE) return CommonResult;
16872 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
16873 if (FalseResult.Kind == IK_NotICE) return FalseResult;
16874 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
16875 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
16876 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
16877 return FalseResult;
16878 }
16879 case Expr::ConditionalOperatorClass: {
16880 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
16881 // If the condition (ignoring parens) is a __builtin_constant_p call,
16882 // then only the true side is actually considered in an integer constant
16883 // expression, and it is fully evaluated. This is an important GNU
16884 // extension. See GCC PR38377 for discussion.
16885 if (const CallExpr *CallCE
16886 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
16887 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
16888 return CheckEvalInICE(E, Ctx);
16889 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
16890 if (CondResult.Kind == IK_NotICE)
16891 return CondResult;
16892
16893 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
16894 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
16895
16896 if (TrueResult.Kind == IK_NotICE)
16897 return TrueResult;
16898 if (FalseResult.Kind == IK_NotICE)
16899 return FalseResult;
16900 if (CondResult.Kind == IK_ICEIfUnevaluated)
16901 return CondResult;
16902 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
16903 return NoDiag();
16904 // Rare case where the diagnostics depend on which side is evaluated
16905 // Note that if we get here, CondResult is 0, and at least one of
16906 // TrueResult and FalseResult is non-zero.
16907 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
16908 return FalseResult;
16909 return TrueResult;
16910 }
16911 case Expr::CXXDefaultArgExprClass:
16912 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
16913 case Expr::CXXDefaultInitExprClass:
16914 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
16915 case Expr::ChooseExprClass: {
16916 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
16917 }
16918 case Expr::BuiltinBitCastExprClass: {
16919 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
16920 return ICEDiag(IK_NotICE, E->getBeginLoc());
16921 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
16922 }
16923 }
16924
16925 llvm_unreachable("Invalid StmtClass!");
16926}
16927
16928/// Evaluate an expression as a C++11 integral constant expression.
16930 const Expr *E,
16931 llvm::APSInt *Value,
16934 if (Loc) *Loc = E->getExprLoc();
16935 return false;
16936 }
16937
16938 APValue Result;
16939 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
16940 return false;
16941
16942 if (!Result.isInt()) {
16943 if (Loc) *Loc = E->getExprLoc();
16944 return false;
16945 }
16946
16947 if (Value) *Value = Result.getInt();
16948 return true;
16949}
16950
16952 SourceLocation *Loc) const {
16953 assert(!isValueDependent() &&
16954 "Expression evaluator can't be called on a dependent expression.");
16955
16956 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
16957
16958 if (Ctx.getLangOpts().CPlusPlus11)
16959 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
16960
16961 ICEDiag D = CheckICE(this, Ctx);
16962 if (D.Kind != IK_ICE) {
16963 if (Loc) *Loc = D.Loc;
16964 return false;
16965 }
16966 return true;
16967}
16968
16969std::optional<llvm::APSInt>
16971 if (isValueDependent()) {
16972 // Expression evaluator can't succeed on a dependent expression.
16973 return std::nullopt;
16974 }
16975
16976 APSInt Value;
16977
16978 if (Ctx.getLangOpts().CPlusPlus11) {
16980 return Value;
16981 return std::nullopt;
16982 }
16983
16984 if (!isIntegerConstantExpr(Ctx, Loc))
16985 return std::nullopt;
16986
16987 // The only possible side-effects here are due to UB discovered in the
16988 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
16989 // required to treat the expression as an ICE, so we produce the folded
16990 // value.
16992 Expr::EvalStatus Status;
16993 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
16994 Info.InConstantContext = true;
16995
16996 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
16997 llvm_unreachable("ICE cannot be evaluated!");
16998
16999 return ExprResult.Val.getInt();
17000}
17001
17003 assert(!isValueDependent() &&
17004 "Expression evaluator can't be called on a dependent expression.");
17005
17006 return CheckICE(this, Ctx).Kind == IK_ICE;
17007}
17008
17010 SourceLocation *Loc) const {
17011 assert(!isValueDependent() &&
17012 "Expression evaluator can't be called on a dependent expression.");
17013
17014 // We support this checking in C++98 mode in order to diagnose compatibility
17015 // issues.
17016 assert(Ctx.getLangOpts().CPlusPlus);
17017
17018 // Build evaluation settings.
17019 Expr::EvalStatus Status;
17021 Status.Diag = &Diags;
17022 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17023
17024 APValue Scratch;
17025 bool IsConstExpr =
17026 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
17027 // FIXME: We don't produce a diagnostic for this, but the callers that
17028 // call us on arbitrary full-expressions should generally not care.
17029 Info.discardCleanups() && !Status.HasSideEffects;
17030
17031 if (!Diags.empty()) {
17032 IsConstExpr = false;
17033 if (Loc) *Loc = Diags[0].first;
17034 } else if (!IsConstExpr) {
17035 // FIXME: This shouldn't happen.
17036 if (Loc) *Loc = getExprLoc();
17037 }
17038
17039 return IsConstExpr;
17040}
17041
17043 const FunctionDecl *Callee,
17045 const Expr *This) const {
17046 assert(!isValueDependent() &&
17047 "Expression evaluator can't be called on a dependent expression.");
17048
17049 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
17050 std::string Name;
17051 llvm::raw_string_ostream OS(Name);
17052 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
17053 /*Qualified=*/true);
17054 return Name;
17055 });
17056
17057 Expr::EvalStatus Status;
17058 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
17059 Info.InConstantContext = true;
17060
17061 LValue ThisVal;
17062 const LValue *ThisPtr = nullptr;
17063 if (This) {
17064#ifndef NDEBUG
17065 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
17066 assert(MD && "Don't provide `this` for non-methods.");
17067 assert(MD->isImplicitObjectMemberFunction() &&
17068 "Don't provide `this` for methods without an implicit object.");
17069#endif
17070 if (!This->isValueDependent() &&
17071 EvaluateObjectArgument(Info, This, ThisVal) &&
17072 !Info.EvalStatus.HasSideEffects)
17073 ThisPtr = &ThisVal;
17074
17075 // Ignore any side-effects from a failed evaluation. This is safe because
17076 // they can't interfere with any other argument evaluation.
17077 Info.EvalStatus.HasSideEffects = false;
17078 }
17079
17080 CallRef Call = Info.CurrentCall->createCall(Callee);
17081 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
17082 I != E; ++I) {
17083 unsigned Idx = I - Args.begin();
17084 if (Idx >= Callee->getNumParams())
17085 break;
17086 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
17087 if ((*I)->isValueDependent() ||
17088 !EvaluateCallArg(PVD, *I, Call, Info) ||
17089 Info.EvalStatus.HasSideEffects) {
17090 // If evaluation fails, throw away the argument entirely.
17091 if (APValue *Slot = Info.getParamSlot(Call, PVD))
17092 *Slot = APValue();
17093 }
17094
17095 // Ignore any side-effects from a failed evaluation. This is safe because
17096 // they can't interfere with any other argument evaluation.
17097 Info.EvalStatus.HasSideEffects = false;
17098 }
17099
17100 // Parameter cleanups happen in the caller and are not part of this
17101 // evaluation.
17102 Info.discardCleanups();
17103 Info.EvalStatus.HasSideEffects = false;
17104
17105 // Build fake call to Callee.
17106 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
17107 Call);
17108 // FIXME: Missing ExprWithCleanups in enable_if conditions?
17109 FullExpressionRAII Scope(Info);
17110 return Evaluate(Value, Info, this) && Scope.destroy() &&
17111 !Info.EvalStatus.HasSideEffects;
17112}
17113
17116 PartialDiagnosticAt> &Diags) {
17117 // FIXME: It would be useful to check constexpr function templates, but at the
17118 // moment the constant expression evaluator cannot cope with the non-rigorous
17119 // ASTs which we build for dependent expressions.
17120 if (FD->isDependentContext())
17121 return true;
17122
17123 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
17124 std::string Name;
17125 llvm::raw_string_ostream OS(Name);
17127 /*Qualified=*/true);
17128 return Name;
17129 });
17130
17131 Expr::EvalStatus Status;
17132 Status.Diag = &Diags;
17133
17134 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
17135 Info.InConstantContext = true;
17136 Info.CheckingPotentialConstantExpression = true;
17137
17138 // The constexpr VM attempts to compile all methods to bytecode here.
17139 if (Info.EnableNewConstInterp) {
17140 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
17141 return Diags.empty();
17142 }
17143
17144 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
17145 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
17146
17147 // Fabricate an arbitrary expression on the stack and pretend that it
17148 // is a temporary being used as the 'this' pointer.
17149 LValue This;
17150 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
17151 This.set({&VIE, Info.CurrentCall->Index});
17152
17154
17155 APValue Scratch;
17156 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
17157 // Evaluate the call as a constant initializer, to allow the construction
17158 // of objects of non-literal types.
17159 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
17160 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
17161 } else {
17164 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
17165 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
17166 /*ResultSlot=*/nullptr);
17167 }
17168
17169 return Diags.empty();
17170}
17171
17173 const FunctionDecl *FD,
17175 PartialDiagnosticAt> &Diags) {
17176 assert(!E->isValueDependent() &&
17177 "Expression evaluator can't be called on a dependent expression.");
17178
17179 Expr::EvalStatus Status;
17180 Status.Diag = &Diags;
17181
17182 EvalInfo Info(FD->getASTContext(), Status,
17183 EvalInfo::EM_ConstantExpressionUnevaluated);
17184 Info.InConstantContext = true;
17185 Info.CheckingPotentialConstantExpression = true;
17186
17187 // Fabricate a call stack frame to give the arguments a plausible cover story.
17188 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
17189 /*CallExpr=*/nullptr, CallRef());
17190
17191 APValue ResultScratch;
17192 Evaluate(ResultScratch, Info, E);
17193 return Diags.empty();
17194}
17195
17196bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
17197 unsigned Type) const {
17198 if (!getType()->isPointerType())
17199 return false;
17200
17201 Expr::EvalStatus Status;
17202 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17203 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
17204}
17205
17206static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
17207 EvalInfo &Info, std::string *StringResult) {
17208 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
17209 return false;
17210
17211 LValue String;
17212
17213 if (!EvaluatePointer(E, String, Info))
17214 return false;
17215
17216 QualType CharTy = E->getType()->getPointeeType();
17217
17218 // Fast path: if it's a string literal, search the string value.
17219 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
17220 String.getLValueBase().dyn_cast<const Expr *>())) {
17221 StringRef Str = S->getBytes();
17222 int64_t Off = String.Offset.getQuantity();
17223 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
17224 S->getCharByteWidth() == 1 &&
17225 // FIXME: Add fast-path for wchar_t too.
17226 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
17227 Str = Str.substr(Off);
17228
17229 StringRef::size_type Pos = Str.find(0);
17230 if (Pos != StringRef::npos)
17231 Str = Str.substr(0, Pos);
17232
17233 Result = Str.size();
17234 if (StringResult)
17235 *StringResult = Str;
17236 return true;
17237 }
17238
17239 // Fall through to slow path.
17240 }
17241
17242 // Slow path: scan the bytes of the string looking for the terminating 0.
17243 for (uint64_t Strlen = 0; /**/; ++Strlen) {
17244 APValue Char;
17245 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
17246 !Char.isInt())
17247 return false;
17248 if (!Char.getInt()) {
17249 Result = Strlen;
17250 return true;
17251 } else if (StringResult)
17252 StringResult->push_back(Char.getInt().getExtValue());
17253 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
17254 return false;
17255 }
17256}
17257
17258std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
17259 Expr::EvalStatus Status;
17260 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17261 uint64_t Result;
17262 std::string StringResult;
17263
17264 if (EvaluateBuiltinStrLen(this, Result, Info, &StringResult))
17265 return StringResult;
17266 return {};
17267}
17268
17269bool Expr::EvaluateCharRangeAsString(std::string &Result,
17270 const Expr *SizeExpression,
17271 const Expr *PtrExpression, ASTContext &Ctx,
17272 EvalResult &Status) const {
17273 LValue String;
17274 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17275 Info.InConstantContext = true;
17276
17277 FullExpressionRAII Scope(Info);
17278 APSInt SizeValue;
17279 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
17280 return false;
17281
17282 uint64_t Size = SizeValue.getZExtValue();
17283
17284 if (!::EvaluatePointer(PtrExpression, String, Info))
17285 return false;
17286
17287 QualType CharTy = PtrExpression->getType()->getPointeeType();
17288 for (uint64_t I = 0; I < Size; ++I) {
17289 APValue Char;
17290 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
17291 Char))
17292 return false;
17293
17294 APSInt C = Char.getInt();
17295 Result.push_back(static_cast<char>(C.getExtValue()));
17296 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
17297 return false;
17298 }
17299 if (!Scope.destroy())
17300 return false;
17301
17302 if (!CheckMemoryLeaks(Info))
17303 return false;
17304
17305 return true;
17306}
17307
17308bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
17309 Expr::EvalStatus Status;
17310 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17311 return EvaluateBuiltinStrLen(this, Result, Info);
17312}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3341
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
Defines enum values for all the target-independent builtin functions.
static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, Address OriginalBaseAddress, llvm::Value *Addr)
const Decl * D
IndirectLocalPath & Path
enum clang::sema::@1656::IndirectLocalPathEntry::EntryKind Kind
Expr * E
llvm::APSInt APSInt
Definition: Compiler.cpp:22
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1171
GCCTypeClass
Values returned by __builtin_classify_type, chosen to match the values produced by GCC's builtin.
static bool isRead(AccessKinds AK)
static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, EvalInfo &Info, std::string *StringResult=nullptr)
static bool isValidIndeterminateAccess(AccessKinds AK)
Is this kind of axcess 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 CharUnits GetAlignOfType(EvalInfo &Info, QualType T, UnaryExprOrTypeTrait ExprKind)
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 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 FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, const ASTContext &Ctx, bool &IsConst)
static bool HandleConstructorCall(const Expr *E, const LValue &This, CallRef Call, const CXXConstructorDecl *Definition, EvalInfo &Info, APValue &Result)
Evaluate a constructor call.
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.
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.
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 bool IsLiteralLValue(const LValue &Value)
static bool HandleFunctionCall(SourceLocation CallLoc, const FunctionDecl *Callee, const LValue *This, 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 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.
bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E)
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 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 CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, UnaryExprOrTypeTrait ExprKind)
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.
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 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 bool EvaluateArgs(ArrayRef< const Expr * > Args, CallRef Call, EvalInfo &Info, const FunctionDecl *Callee, bool RightToLeft=false)
Evaluate the arguments to a function call.
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)
static bool IsNoOpCall(const CallExpr *E)
Should this call expression be treated as a no-op?
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 getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, const CallExpr *Call, llvm::APInt &Result)
Attempts to compute the number of bytes available at the pointer returned by a function with the allo...
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 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 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 bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, const Expr *E, llvm::APSInt *Value, SourceLocation *Loc)
Evaluate an expression as a C++11 integral constant expression.
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.
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.
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.
static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, CallRef Call, EvalInfo &Info, bool NonNull=false)
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 EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, EvalInfo &Info)
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 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 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.
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 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 bool EvaluateDecl(EvalInfo &Info, const Decl *D)
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 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 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)
const CFGBlock * Block
Definition: HTMLLogger.cpp:153
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:22
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
SourceLocation Loc
Definition: SemaObjC.cpp:759
bool Indirect
Definition: SemaObjC.cpp:760
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
__DEVICE__ long long abs(long long __n)
__device__ int
do v
Definition: arm_acle.h:91
QualType getType() const
Definition: APValue.cpp:63
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:208
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition: APValue.h:216
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool hasArrayFiller() const
Definition: APValue.h:518
const LValueBase getLValueBase() const
Definition: APValue.cpp:974
APValue & getArrayInitializedElt(unsigned I)
Definition: APValue.h:510
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition: APValue.cpp:468
APSInt & getInt()
Definition: APValue.h:423
APValue & getStructField(unsigned i)
Definition: APValue.h:551
const FieldDecl * getUnionField() const
Definition: APValue.h:563
bool isVector() const
Definition: APValue.h:407
APSInt & getComplexIntImag()
Definition: APValue.h:461
bool isAbsent() const
Definition: APValue.h:397
bool isComplexInt() const
Definition: APValue.h:404
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:205
ValueKind getKind() const
Definition: APValue.h:395
unsigned getArrayInitializedElts() const
Definition: APValue.h:529
static APValue IndeterminateValue()
Definition: APValue.h:366
bool isFloat() const
Definition: APValue.h:402
APFixedPoint & getFixedPoint()
Definition: APValue.h:445
bool hasValue() const
Definition: APValue.h:399
bool hasLValuePath() const
Definition: APValue.cpp:989
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1057
APValue & getUnionValue()
Definition: APValue.h:567
CharUnits & getLValueOffset()
Definition: APValue.cpp:984
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:693
bool isComplexFloat() const
Definition: APValue.h:405
APValue & getVectorElt(unsigned I)
Definition: APValue.h:497
APValue & getArrayFiller()
Definition: APValue.h:521
unsigned getVectorLength() const
Definition: APValue.h:505
bool isLValue() const
Definition: APValue.h:406
void setUnion(const FieldDecl *Field, const APValue &Value)
Definition: APValue.cpp:1050
bool isIndeterminate() const
Definition: APValue.h:398
bool isInt() const
Definition: APValue.h:401
unsigned getArraySize() const
Definition: APValue.h:533
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
bool isFixedPoint() const
Definition: APValue.h:403
@ 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:409
APSInt & getComplexIntReal()
Definition: APValue.h:453
APFloat & getComplexFloatImag()
Definition: APValue.h:477
APFloat & getComplexFloatReal()
Definition: APValue.h:469
APFloat & getFloat()
Definition: APValue.h:437
APValue & getStructBase(unsigned i)
Definition: APValue.h:546
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
SourceManager & getSourceManager()
Definition: ASTContext.h:721
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
QualType getRecordType(const RecordDecl *Decl) const
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,...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:797
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<=>,...
Definition: ASTContext.h:2325
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:713
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.
Definition: ASTContext.h:2394
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
Definition: RecordLayout.h:196
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:259
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:4372
LabelDecl * getLabel() const
Definition: Expr.h:4395
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition: Expr.h:5756
Represents a loop initializing the elements of an array.
Definition: Expr.h:5703
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2674
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent.
Definition: ExprCXX.h:2853
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3571
QualType getElementType() const
Definition: Type.h:3583
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7585
Attr - This represents one attribute.
Definition: Attr.h:42
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4275
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition: Expr.h:4329
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition: Expr.h:4310
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3860
Expr * getLHS() const
Definition: Expr.h:3910
bool isComparisonOp() const
Definition: Expr.h:3961
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition: Expr.h:4007
bool isLogicalOp() const
Definition: Expr.h:3994
Expr * getRHS() const
Definition: Expr.h:3912
Opcode getOpcode() const
Definition: Expr.h:3905
A binding in a decomposition declaration.
Definition: DeclCXX.h:4111
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6365
Represents a C++2a __builtin_bit_cast(T, v) expression.
Definition: ExprCXX.h:5292
This class is used for builtin types like 'int'.
Definition: Type.h:3028
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
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
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1491
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:720
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2539
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2791
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Definition: DeclCXX.h:2624
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1268
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1375
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition: ExprCXX.h:2498
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2803
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition: ExprCXX.h:478
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition: StmtCXX.h:135
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition: ExprCXX.h:1737
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2064
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:2493
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:2500
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2190
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2603
bool isInstance() const
Definition: DeclCXX.h:2091
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2526
bool isStatic() const
Definition: DeclCXX.cpp:2224
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2504
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition: DeclCXX.cpp:2639
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition: ExprCXX.h:2241
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition: ExprCXX.h:4126
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
Represents a list-initialization with parenthesis.
Definition: ExprCXX.h:4954
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:1238
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition: DeclCXX.cpp:1603
base_class_iterator bases_end()
Definition: DeclCXX.h:629
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1371
base_class_range bases()
Definition: DeclCXX.h:620
capture_const_iterator captures_end() const
Definition: DeclCXX.h:1112
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:1680
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:614
base_class_iterator bases_begin()
Definition: DeclCXX.h:627
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1191
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:2014
capture_const_iterator captures_begin() const
Definition: DeclCXX.h:1106
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1633
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:524
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:635
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
A C++ reinterpret_cast expression (C++ [expr.reinterpret.cast]).
Definition: ExprCXX.h:523
A rewritten comparison expression that was originally written using operator syntax.
Definition: ExprCXX.h:283
An expression "T()" which creates an rvalue of a non-class type T.
Definition: ExprCXX.h:2182
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition: ExprCXX.h:797
Represents the this expression in C++.
Definition: ExprCXX.h:1152
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:845
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1066
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2830
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition: Expr.cpp:1579
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3000
Decl * getCalleeDecl()
Definition: Expr.h:2994
CaseStmt - Represent a case statement.
Definition: Stmt.h:1811
Expr * getLHS()
Definition: Stmt.h:1898
Expr * getRHS()
Definition: Stmt.h:1910
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3498
const CXXBaseSpecifier *const * path_const_iterator
Definition: Expr.h:3565
Expr * getSubExpr()
Definition: Expr.h:3548
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
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4592
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: Type.h:3139
QualType getElementType() const
Definition: Type.h:3149
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:4122
QualType getComputationLHSType() const
Definition: Expr.h:4156
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3428
bool isFileScope() const
Definition: Expr.h:3455
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1611
bool body_empty() const
Definition: Stmt.h:1655
Stmt *const * const_body_iterator
Definition: Stmt.h:1683
body_iterator body_end()
Definition: Stmt.h:1676
body_range body()
Definition: Stmt.h:1674
body_iterator body_begin()
Definition: Stmt.h:1675
Represents the specialization of a concept - evaluates to a prvalue of type bool.
Definition: ExprConcepts.h:42
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4213
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition: Expr.h:4245
Expr * getCond() const
getCond - Return the expression representing the condition for the ?: operator.
Definition: Expr.h:4236
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition: Expr.h:4240
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:195
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3609
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition: Type.h:3672
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:178
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:218
uint64_t getLimitedSize() const
Return the size zero-extended to uint64_t or UINT64_MAX if the value is larger than UINT64_MAX.
Definition: Type.h:3698
bool isZeroSize() const
Return true if the size is zero.
Definition: Type.h:3679
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition: Type.h:3705
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3665
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3685
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:1077
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:4533
Represents the current source location and context used to determine the value of the source location...
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2370
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2090
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1333
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1502
decl_range decls()
Definition: Stmt.h:1550
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isInStdNamespace() const
Definition: DeclBase.cpp:425
static void add(Kind k)
Definition: DeclBase.cpp:224
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:523
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
bool isInvalidDecl() const
Definition: DeclBase.h:595
SourceLocation getLocation() const
Definition: DeclBase.h:446
DeclContext * getDeclContext()
Definition: DeclBase.h:455
AccessSpecifier getAccess() const
Definition: DeclBase.h:514
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
A decomposition declaration.
Definition: DeclCXX.h:4170
Designator - A designator in a C99 designated initializer.
Definition: Designator.h:38
DoStmt - This represents a 'do/while' stmt.
Definition: Stmt.h:2735
Stmt * getBody()
Definition: Stmt.h:2760
Expr * getCond()
Definition: Stmt.h:2753
Symbolic representation of a dynamic allocation.
Definition: APValue.h:65
static unsigned getMaxIndex()
Definition: APValue.h:85
Represents a reference to #emded data.
Definition: Expr.h:4867
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3274
Represents an enum.
Definition: Decl.h:3844
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition: Decl.h:4041
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4058
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4004
void getValueRange(llvm::APInt &Max, llvm::APInt &Min) const
Calculates the [Min,Max) values the enum can store based on the NumPositiveBits and NumNegativeBits.
Definition: Decl.cpp:4972
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5996
EnumDecl * getDecl() const
Definition: Type.h:6003
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3750
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition: ExprCXX.h:3474
This represents one expression.
Definition: Expr.h:110
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:82
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...
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:280
SideEffectsKind
Definition: Expr.h:667
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition: Expr.h:671
@ SE_AllowUndefinedBehavior
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
Definition: Expr.h:669
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:3075
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
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...
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition: Expr.cpp:3864
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3070
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
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:3066
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...
bool isPRValue() const
Definition: Expr.h:278
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
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:3567
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 isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
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:3204
ConstantExprKind
Definition: Expr.h:748
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
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 isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result=nullptr, SourceLocation *Loc=nullptr) const
isCXX11ConstantExpr - Return true if this expression is a constant expression in C++11.
An expression trait intrinsic.
Definition: ExprCXX.h:2924
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:6305
bool isFPConstrained() const
Definition: LangOptions.h:875
LangOptions::FPExceptionModeKind getExceptionMode() const
Definition: LangOptions.h:893
RoundingMode getRoundingMode() const
Definition: LangOptions.h:881
Represents a member of a struct/union/class.
Definition: Decl.h:3030
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3121
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4630
unsigned getBitWidthValue(const ASTContext &Ctx) const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4578
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3247
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:3258
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:97
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition: Stmt.h:2791
Represents a function declaration or definition.
Definition: Decl.h:1932
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2669
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3224
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4040
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4028
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2302
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4164
ArrayRef< ParmVarDecl * >::const_iterator param_const_iterator
Definition: Decl.h:2655
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2395
bool isReservedGlobalPlacementOperator() const
Determines whether this operator new or delete is one of the reserved global placement operators: voi...
Definition: Decl.cpp:3327
bool isReplaceableGlobalAllocationFunction(std::optional< unsigned > *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:3352
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2310
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:3069
Declaration of a template function.
Definition: DeclTemplate.h:957
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4667
Represents a C11 generic selection.
Definition: Expr.h:5917
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:2148
Stmt * getThen()
Definition: Stmt.h:2237
Stmt * getInit()
Definition: Stmt.h:2298
bool isNonNegatedConsteval() const
Definition: Stmt.h:2333
Expr * getCond()
Definition: Stmt.h:2225
Stmt * getElse()
Definition: Stmt.h:2246
bool isConsteval() const
Definition: Stmt.h:2328
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition: Stmt.cpp:982
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1717
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5792
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3318
ArrayRef< NamedDecl * > chain() const
Definition: Decl.h:3340
Describes an C or C++ initializer list.
Definition: Expr.h:5039
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:476
A global _GUID constant.
Definition: DeclCXX.h:4293
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition: ExprCXX.h:4728
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3187
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3513
This represents a decl that may have a name.
Definition: Decl.h:249
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
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:1675
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:87
ObjCBoxedExpr - used for generalized expression boxing.
Definition: ExprObjC.h:127
ObjCEncodeExpr, used for @encode in Objective-C.
Definition: ExprObjC.h:410
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:51
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition: Expr.h:2475
Expr * getIndexExpr(unsigned Idx)
Definition: Expr.h:2536
const OffsetOfNode & getComponent(unsigned Idx) const
Definition: Expr.h:2522
TypeSourceInfo * getTypeSourceInfo() const
Definition: Expr.h:2515
unsigned getNumComponents() const
Definition: Expr.h:2532
Helper class for OffsetOfExpr.
Definition: Expr.h:2369
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition: Expr.h:2427
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition: Expr.h:2433
@ Array
An index into an array.
Definition: Expr.h:2374
@ Identifier
A field in a dependent type, known only by its name.
Definition: Expr.h:2378
@ Field
A field.
Definition: Expr.h:2376
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition: Expr.h:2381
Kind getKind() const
Determine what kind of offsetof node this is.
Definition: Expr.h:2423
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition: Expr.h:2443
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
A partial diagnostic which we might know in advance that we are not going to emit.
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2135
Represents a parameter to a function.
Definition: Decl.h:1722
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1782
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3192
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1991
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6497
A (possibly-)qualified type.
Definition: Type.h:941
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7839
QualType withConst() const
Definition: Type.h:1166
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1163
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7755
bool isConstant(const ASTContext &Ctx) const
Definition: Type.h:1101
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7956
QualType getCanonicalType() const
Definition: Type.h:7807
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7849
void removeLocalVolatile()
Definition: Type.h:7871
QualType withCVRQualifiers(unsigned CVR) const
Definition: Type.h:1186
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition: Type.h:1171
void removeLocalConst()
Definition: Type.h:7863
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7828
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1542
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7801
Represents a struct/union/class.
Definition: Decl.h:4145
bool hasFlexibleArrayMember() const
Definition: Decl.h:4178
field_iterator field_end() const
Definition: Decl.h:4354
field_range fields() const
Definition: Decl.h:4351
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4197
bool field_empty() const
Definition: Decl.h:4359
field_iterator field_begin() const
Definition: Decl.cpp:5068
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5970
RecordDecl * getDecl() const
Definition: Type.h:5980
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3433
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
Definition: ExprConcepts.h:510
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:4465
Represents an expression that computes the length of a parameter pack.
Definition: ExprCXX.h:4258
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition: Expr.h:4761
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4417
Stmt - This represents one statement.
Definition: Stmt.h:84
StmtClass getStmtClass() const
Definition: Stmt.h:1363
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1870
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1191
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4484
const SwitchCase * getNextSwitchCase() const
Definition: Stmt.h:1784
SwitchStmt - This represents a 'switch' stmt.
Definition: Stmt.h:2398
Expr * getCond()
Definition: Stmt.h:2461
Stmt * getBody()
Definition: Stmt.h:2473
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition: Stmt.cpp:1100
Stmt * getInit()
Definition: Stmt.h:2482
SwitchCase * getSwitchCaseList()
Definition: Stmt.h:2535
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4725
bool isUnion() const
Definition: Decl.h:3767
virtual bool isNan2008() const
Returns true if NaN encoding is IEEE 754-2008.
Definition: TargetInfo.h:1251
A template argument list.
Definition: DeclTemplate.h:244
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:280
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:274
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
A template parameter object.
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: Type.h:7737
A type trait used in the implementation of various C++11 and Library TR1 trait templates.
Definition: ExprCXX.h:2768
The base class of the type hierarchy.
Definition: Type.h:1829
bool isStructureType() const
Definition: Type.cpp:629
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isVoidType() const
Definition: Type.h:8324
bool isBooleanType() const
Definition: Type.h:8452
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2167
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2892
bool isIncompleteArrayType() const
Definition: Type.h:8088
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2146
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:677
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: Type.h:8621
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2217
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2071
bool isConstantArrayType() const
Definition: Type.h:8084
bool isNothrowT() const
Definition: Type.cpp:3061
bool isVoidPointerType() const
Definition: Type.cpp:665
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2352
bool isArrayType() const
Definition: Type.h:8080
bool isCharType() const
Definition: Type.cpp:2089
bool isFunctionPointerType() const
Definition: Type.h:8048
bool isPointerType() const
Definition: Type.h:8008
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8364
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8612
bool isReferenceType() const
Definition: Type.h:8026
bool isEnumeralType() const
Definition: Type.h:8112
bool isVariableArrayType() const
Definition: Type.h:8092
bool isChar8Type() const
Definition: Type.cpp:2105
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2510
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8439
bool isExtVectorBoolType() const
Definition: Type.h:8128
bool isMemberDataPointerType() const
Definition: Type.h:8073
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8293
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2700
bool isAnyComplexType() const
Definition: Type.h:8116
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8377
const RecordType * getAsStructureType() const
Definition: Type.cpp:721
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8495
bool isMemberPointerType() const
Definition: Type.h:8062
bool isAtomicType() const
Definition: Type.h:8163
bool isComplexIntegerType() const
Definition: Type.cpp:683
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8598
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
bool isFunctionType() const
Definition: Type.h:8004
bool isVectorType() const
Definition: Type.h:8120
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2266
bool isFloatingType() const
Definition: Type.cpp:2249
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:2196
bool isAnyPointerType() const
Definition: Type.h:8016
TypeClass getTypeClass() const
Definition: Type.h:2339
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8545
bool isNullPtrType() const
Definition: Type.h:8357
bool isRecordType() const
Definition: Type.h:8108
bool isUnionType() const
Definition: Type.cpp:671
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2479
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition: Type.h:8486
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1886
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2578
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition: Expr.h:2647
UnaryExprOrTypeTrait getKind() const
Definition: Expr.h:2610
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2188
Expr * getSubExpr() const
Definition: Expr.h:2233
Opcode getOpcode() const
Definition: Expr.h:2228
static bool isIncrementOp(Opcode Op)
Definition: Expr.h:2274
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4350
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
QualType getType() const
Definition: Decl.h:678
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5364
QualType getType() const
Definition: Value.cpp:234
bool hasValue() const
Definition: Value.h:134
Represents a variable declaration or definition.
Definition: Decl.h:879
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1510
bool hasInit() const
Definition: Decl.cpp:2380
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition: Decl.cpp:2600
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1519
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2539
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition: Decl.cpp:2834
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition: Decl.cpp:2612
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2348
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:2451
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:1156
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1125
const Expr * getInit() const
Definition: Decl.h:1316
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:2592
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1132
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2357
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1201
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:2493
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition: Decl.h:1306
Represents a GCC generic vector type.
Definition: Type.h:4026
unsigned getNumElements() const
Definition: Type.h:4041
QualType getElementType() const
Definition: Type.h:4040
WhileStmt - This represents a 'while' stmt.
Definition: Stmt.h:2594
Expr * getCond()
Definition: Stmt.h:2646
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition: Stmt.cpp:1161
Stmt * getBody()
Definition: Stmt.h:2658
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:56
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:181
uint32_t Literal
Literals are represented as positive integers.
Definition: CNFFormula.h:35
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.
Definition: Format.cpp:3844
llvm::APFloat APFloat
Definition: Floating.h:23
llvm::APInt APInt
Definition: Integral.h:29
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1090
bool This(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2289
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2263
bool Alloc(InterpState &S, CodePtr OpPC, const Descriptor *Desc)
Definition: Interp.h:2962
bool ReturnValue(const InterpState &S, const T &V, APValue &R)
Convert a value to an APValue.
Definition: Interp.h:43
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.
@ NonNull
Values of this type can never be null.
BinaryOperatorKind
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition: CallGraph.h:207
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition: ASTLambda.h:38
@ TSCS_unspecified
Definition: Specifiers.h:236
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:40
@ CSK_ArrayToPointer
Definition: State.h:44
@ CSK_Derived
Definition: State.h:42
@ CSK_Base
Definition: State.h:41
@ CSK_Real
Definition: State.h:46
@ CSK_ArrayIndex
Definition: State.h:45
@ CSK_Imag
Definition: State.h:47
@ CSK_VectorElement
Definition: State.h:48
@ CSK_Field
Definition: State.h:43
@ SD_Static
Static storage duration.
Definition: Specifiers.h:331
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition: Specifiers.h:328
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
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_MemberCall
Definition: State.h:32
@ AK_ReadObjectRepresentation
Definition: State.h:28
@ AK_Destroy
Definition: State.h:36
@ AK_Decrement
Definition: State.h:31
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
CastKind
CastKind - The kind of operation required for a conversion.
llvm::hash_code hash_value(const CustomizableOptional< T > &O)
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ Success
Template argument deduction was successful.
@ None
The alignment was not explicit in code.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Other
Other implicit parameter.
@ AS_public
Definition: Specifiers.h:124
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
#define bool
Definition: stdbool.h:24
unsigned PathLength
The corresponding path length in the lvalue.
const CXXRecordDecl * Type
The dynamic class type of the object.
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:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
EvalStatus is a struct with detailed info about an evaluation in progress.
Definition: Expr.h:606
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:630
bool HasUndefinedBehavior
Whether the evaluation hit undefined behavior.
Definition: Expr.h:614
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:609
static ObjectUnderConstruction getTombstoneKey()
DenseMapInfo< APValue::LValueBase > Base
static ObjectUnderConstruction getEmptyKey()
static unsigned getHashValue(const ObjectUnderConstruction &Object)
static bool isEqual(const ObjectUnderConstruction &LHS, const ObjectUnderConstruction &RHS)
#define ilogb(__x)
Definition: tgmath.h:851
#define scalbn(__x, __y)
Definition: tgmath.h:1165