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"
41#include "clang/AST/ASTLambda.h"
42#include "clang/AST/Attr.h"
44#include "clang/AST/CharUnits.h"
46#include "clang/AST/Expr.h"
47#include "clang/AST/OSLog.h"
51#include "clang/AST/TypeLoc.h"
56#include "llvm/ADT/APFixedPoint.h"
57#include "llvm/ADT/Sequence.h"
58#include "llvm/ADT/SmallBitVector.h"
59#include "llvm/ADT/StringExtras.h"
60#include "llvm/Support/Casting.h"
61#include "llvm/Support/Debug.h"
62#include "llvm/Support/SaveAndRestore.h"
63#include "llvm/Support/SipHash.h"
64#include "llvm/Support/TimeProfiler.h"
65#include "llvm/Support/raw_ostream.h"
66#include <cstring>
67#include <functional>
68#include <optional>
69
70#define DEBUG_TYPE "exprconstant"
71
72using namespace clang;
73using llvm::APFixedPoint;
74using llvm::APInt;
75using llvm::APSInt;
76using llvm::APFloat;
77using llvm::FixedPointSemantics;
78
79namespace {
80 struct LValue;
81 class CallStackFrame;
82 class EvalInfo;
83
84 using SourceLocExprScopeGuard =
86
87 static QualType getType(APValue::LValueBase B) {
88 return B.getType();
89 }
90
91 /// Get an LValue path entry, which is known to not be an array index, as a
92 /// field declaration.
93 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
94 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
95 }
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// base class declaration.
98 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
99 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
100 }
101 /// Determine whether this LValue path entry for a base class names a virtual
102 /// base class.
103 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
104 return E.getAsBaseOrMember().getInt();
105 }
106
107 /// Given an expression, determine the type used to store the result of
108 /// evaluating that expression.
109 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
110 if (E->isPRValue())
111 return E->getType();
112 return Ctx.getLValueReferenceType(E->getType());
113 }
114
115 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
116 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
117 if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
118 return DirectCallee->getAttr<AllocSizeAttr>();
119 if (const Decl *IndirectCallee = CE->getCalleeDecl())
120 return IndirectCallee->getAttr<AllocSizeAttr>();
121 return nullptr;
122 }
123
124 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
125 /// This will look through a single cast.
126 ///
127 /// Returns null if we couldn't unwrap a function with alloc_size.
128 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
129 if (!E->getType()->isPointerType())
130 return nullptr;
131
132 E = E->IgnoreParens();
133 // If we're doing a variable assignment from e.g. malloc(N), there will
134 // probably be a cast of some kind. In exotic cases, we might also see a
135 // top-level ExprWithCleanups. Ignore them either way.
136 if (const auto *FE = dyn_cast<FullExpr>(E))
137 E = FE->getSubExpr()->IgnoreParens();
138
139 if (const auto *Cast = dyn_cast<CastExpr>(E))
140 E = Cast->getSubExpr()->IgnoreParens();
141
142 if (const auto *CE = dyn_cast<CallExpr>(E))
143 return getAllocSizeAttr(CE) ? CE : nullptr;
144 return nullptr;
145 }
146
147 /// Determines whether or not the given Base contains a call to a function
148 /// with the alloc_size attribute.
149 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
150 const auto *E = Base.dyn_cast<const Expr *>();
151 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
152 }
153
154 /// Determines whether the given kind of constant expression is only ever
155 /// used for name mangling. If so, it's permitted to reference things that we
156 /// can't generate code for (in particular, dllimported functions).
157 static bool isForManglingOnly(ConstantExprKind Kind) {
158 switch (Kind) {
159 case ConstantExprKind::Normal:
160 case ConstantExprKind::ClassTemplateArgument:
161 case ConstantExprKind::ImmediateInvocation:
162 // Note that non-type template arguments of class type are emitted as
163 // template parameter objects.
164 return false;
165
166 case ConstantExprKind::NonClassTemplateArgument:
167 return true;
168 }
169 llvm_unreachable("unknown ConstantExprKind");
170 }
171
172 static bool isTemplateArgument(ConstantExprKind Kind) {
173 switch (Kind) {
174 case ConstantExprKind::Normal:
175 case ConstantExprKind::ImmediateInvocation:
176 return false;
177
178 case ConstantExprKind::ClassTemplateArgument:
179 case ConstantExprKind::NonClassTemplateArgument:
180 return true;
181 }
182 llvm_unreachable("unknown ConstantExprKind");
183 }
184
185 /// The bound to claim that an array of unknown bound has.
186 /// The value in MostDerivedArraySize is undefined in this case. So, set it
187 /// to an arbitrary value that's likely to loudly break things if it's used.
188 static const uint64_t AssumedSizeForUnsizedArray =
189 std::numeric_limits<uint64_t>::max() / 2;
190
191 /// Determines if an LValue with the given LValueBase will have an unsized
192 /// array in its designator.
193 /// Find the path length and type of the most-derived subobject in the given
194 /// path, and find the size of the containing array, if any.
195 static unsigned
196 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
198 uint64_t &ArraySize, QualType &Type, bool &IsArray,
199 bool &FirstEntryIsUnsizedArray) {
200 // This only accepts LValueBases from APValues, and APValues don't support
201 // arrays that lack size info.
202 assert(!isBaseAnAllocSizeCall(Base) &&
203 "Unsized arrays shouldn't appear here");
204 unsigned MostDerivedLength = 0;
205 Type = getType(Base);
206
207 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
208 if (Type->isArrayType()) {
209 const ArrayType *AT = Ctx.getAsArrayType(Type);
210 Type = AT->getElementType();
211 MostDerivedLength = I + 1;
212 IsArray = true;
213
214 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
215 ArraySize = CAT->getZExtSize();
216 } else {
217 assert(I == 0 && "unexpected unsized array designator");
218 FirstEntryIsUnsizedArray = true;
219 ArraySize = AssumedSizeForUnsizedArray;
220 }
221 } else if (Type->isAnyComplexType()) {
222 const ComplexType *CT = Type->castAs<ComplexType>();
223 Type = CT->getElementType();
224 ArraySize = 2;
225 MostDerivedLength = I + 1;
226 IsArray = true;
227 } else if (const auto *VT = Type->getAs<VectorType>()) {
228 Type = VT->getElementType();
229 ArraySize = VT->getNumElements();
230 MostDerivedLength = I + 1;
231 IsArray = true;
232 } else if (const FieldDecl *FD = getAsField(Path[I])) {
233 Type = FD->getType();
234 ArraySize = 0;
235 MostDerivedLength = I + 1;
236 IsArray = false;
237 } else {
238 // Path[I] describes a base class.
239 ArraySize = 0;
240 IsArray = false;
241 }
242 }
243 return MostDerivedLength;
244 }
245
246 /// A path from a glvalue to a subobject of that glvalue.
247 struct SubobjectDesignator {
248 /// True if the subobject was named in a manner not supported by C++11. Such
249 /// lvalues can still be folded, but they are not core constant expressions
250 /// and we cannot perform lvalue-to-rvalue conversions on them.
251 LLVM_PREFERRED_TYPE(bool)
252 unsigned Invalid : 1;
253
254 /// Is this a pointer one past the end of an object?
255 LLVM_PREFERRED_TYPE(bool)
256 unsigned IsOnePastTheEnd : 1;
257
258 /// Indicator of whether the first entry is an unsized array.
259 LLVM_PREFERRED_TYPE(bool)
260 unsigned FirstEntryIsAnUnsizedArray : 1;
261
262 /// Indicator of whether the most-derived object is an array element.
263 LLVM_PREFERRED_TYPE(bool)
264 unsigned MostDerivedIsArrayElement : 1;
265
266 /// The length of the path to the most-derived object of which this is a
267 /// subobject.
268 unsigned MostDerivedPathLength : 28;
269
270 /// The size of the array of which the most-derived object is an element.
271 /// This will always be 0 if the most-derived object is not an array
272 /// element. 0 is not an indicator of whether or not the most-derived object
273 /// is an array, however, because 0-length arrays are allowed.
274 ///
275 /// If the current array is an unsized array, the value of this is
276 /// undefined.
277 uint64_t MostDerivedArraySize;
278 /// The type of the most derived object referred to by this address.
279 QualType MostDerivedType;
280
281 typedef APValue::LValuePathEntry PathEntry;
282
283 /// The entries on the path from the glvalue to the designated subobject.
285
286 SubobjectDesignator() : Invalid(true) {}
287
288 explicit SubobjectDesignator(QualType T)
289 : Invalid(false), IsOnePastTheEnd(false),
290 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
291 MostDerivedPathLength(0), MostDerivedArraySize(0),
292 MostDerivedType(T) {}
293
294 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
295 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
296 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
297 MostDerivedPathLength(0), MostDerivedArraySize(0) {
298 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
299 if (!Invalid) {
300 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
301 ArrayRef<PathEntry> VEntries = V.getLValuePath();
302 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
303 if (V.getLValueBase()) {
304 bool IsArray = false;
305 bool FirstIsUnsizedArray = false;
306 MostDerivedPathLength = findMostDerivedSubobject(
307 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
308 MostDerivedType, IsArray, FirstIsUnsizedArray);
309 MostDerivedIsArrayElement = IsArray;
310 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
311 }
312 }
313 }
314
315 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
316 unsigned NewLength) {
317 if (Invalid)
318 return;
319
320 assert(Base && "cannot truncate path for null pointer");
321 assert(NewLength <= Entries.size() && "not a truncation");
322
323 if (NewLength == Entries.size())
324 return;
325 Entries.resize(NewLength);
326
327 bool IsArray = false;
328 bool FirstIsUnsizedArray = false;
329 MostDerivedPathLength = findMostDerivedSubobject(
330 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
331 FirstIsUnsizedArray);
332 MostDerivedIsArrayElement = IsArray;
333 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
334 }
335
336 void setInvalid() {
337 Invalid = true;
338 Entries.clear();
339 }
340
341 /// Determine whether the most derived subobject is an array without a
342 /// known bound.
343 bool isMostDerivedAnUnsizedArray() const {
344 assert(!Invalid && "Calling this makes no sense on invalid designators");
345 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
346 }
347
348 /// Determine what the most derived array's size is. Results in an assertion
349 /// failure if the most derived array lacks a size.
350 uint64_t getMostDerivedArraySize() const {
351 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
352 return MostDerivedArraySize;
353 }
354
355 /// Determine whether this is a one-past-the-end pointer.
356 bool isOnePastTheEnd() const {
357 assert(!Invalid);
358 if (IsOnePastTheEnd)
359 return true;
360 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
361 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
362 MostDerivedArraySize)
363 return true;
364 return false;
365 }
366
367 /// Get the range of valid index adjustments in the form
368 /// {maximum value that can be subtracted from this pointer,
369 /// maximum value that can be added to this pointer}
370 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
371 if (Invalid || isMostDerivedAnUnsizedArray())
372 return {0, 0};
373
374 // [expr.add]p4: For the purposes of these operators, a pointer to a
375 // nonarray object behaves the same as a pointer to the first element of
376 // an array of length one with the type of the object as its element type.
377 bool IsArray = MostDerivedPathLength == Entries.size() &&
378 MostDerivedIsArrayElement;
379 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
380 : (uint64_t)IsOnePastTheEnd;
381 uint64_t ArraySize =
382 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
383 return {ArrayIndex, ArraySize - ArrayIndex};
384 }
385
386 /// Check that this refers to a valid subobject.
387 bool isValidSubobject() const {
388 if (Invalid)
389 return false;
390 return !isOnePastTheEnd();
391 }
392 /// Check that this refers to a valid subobject, and if not, produce a
393 /// relevant diagnostic and set the designator as invalid.
394 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
395
396 /// Get the type of the designated object.
397 QualType getType(ASTContext &Ctx) const {
398 assert(!Invalid && "invalid designator has no subobject type");
399 return MostDerivedPathLength == Entries.size()
400 ? MostDerivedType
401 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
402 }
403
404 /// Update this designator to refer to the first element within this array.
405 void addArrayUnchecked(const ConstantArrayType *CAT) {
406 Entries.push_back(PathEntry::ArrayIndex(0));
407
408 // This is a most-derived object.
409 MostDerivedType = CAT->getElementType();
410 MostDerivedIsArrayElement = true;
411 MostDerivedArraySize = CAT->getZExtSize();
412 MostDerivedPathLength = Entries.size();
413 }
414 /// Update this designator to refer to the first element within the array of
415 /// elements of type T. This is an array of unknown size.
416 void addUnsizedArrayUnchecked(QualType ElemTy) {
417 Entries.push_back(PathEntry::ArrayIndex(0));
418
419 MostDerivedType = ElemTy;
420 MostDerivedIsArrayElement = true;
421 // The value in MostDerivedArraySize is undefined in this case. So, set it
422 // to an arbitrary value that's likely to loudly break things if it's
423 // used.
424 MostDerivedArraySize = AssumedSizeForUnsizedArray;
425 MostDerivedPathLength = Entries.size();
426 }
427 /// Update this designator to refer to the given base or member of this
428 /// object.
429 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
430 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
431
432 // If this isn't a base class, it's a new most-derived object.
433 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
434 MostDerivedType = FD->getType();
435 MostDerivedIsArrayElement = false;
436 MostDerivedArraySize = 0;
437 MostDerivedPathLength = Entries.size();
438 }
439 }
440 /// Update this designator to refer to the given complex component.
441 void addComplexUnchecked(QualType EltTy, bool Imag) {
442 Entries.push_back(PathEntry::ArrayIndex(Imag));
443
444 // This is technically a most-derived object, though in practice this
445 // is unlikely to matter.
446 MostDerivedType = EltTy;
447 MostDerivedIsArrayElement = true;
448 MostDerivedArraySize = 2;
449 MostDerivedPathLength = Entries.size();
450 }
451
452 void addVectorElementUnchecked(QualType EltTy, uint64_t Size,
453 uint64_t Idx) {
454 Entries.push_back(PathEntry::ArrayIndex(Idx));
455 MostDerivedType = EltTy;
456 MostDerivedPathLength = Entries.size();
457 MostDerivedArraySize = 0;
458 MostDerivedIsArrayElement = false;
459 }
460
461 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
462 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
463 const APSInt &N);
464 /// Add N to the address of this subobject.
465 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
466 if (Invalid || !N) return;
467 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
468 if (isMostDerivedAnUnsizedArray()) {
469 diagnoseUnsizedArrayPointerArithmetic(Info, E);
470 // Can't verify -- trust that the user is doing the right thing (or if
471 // not, trust that the caller will catch the bad behavior).
472 // FIXME: Should we reject if this overflows, at least?
473 Entries.back() = PathEntry::ArrayIndex(
474 Entries.back().getAsArrayIndex() + TruncatedN);
475 return;
476 }
477
478 // [expr.add]p4: For the purposes of these operators, a pointer to a
479 // nonarray object behaves the same as a pointer to the first element of
480 // an array of length one with the type of the object as its element type.
481 bool IsArray = MostDerivedPathLength == Entries.size() &&
482 MostDerivedIsArrayElement;
483 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
484 : (uint64_t)IsOnePastTheEnd;
485 uint64_t ArraySize =
486 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
487
488 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
489 // Calculate the actual index in a wide enough type, so we can include
490 // it in the note.
491 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
492 (llvm::APInt&)N += ArrayIndex;
493 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
494 diagnosePointerArithmetic(Info, E, N);
495 setInvalid();
496 return;
497 }
498
499 ArrayIndex += TruncatedN;
500 assert(ArrayIndex <= ArraySize &&
501 "bounds check succeeded for out-of-bounds index");
502
503 if (IsArray)
504 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
505 else
506 IsOnePastTheEnd = (ArrayIndex != 0);
507 }
508 };
509
510 /// A scope at the end of which an object can need to be destroyed.
511 enum class ScopeKind {
512 Block,
513 FullExpression,
514 Call
515 };
516
517 /// A reference to a particular call and its arguments.
518 struct CallRef {
519 CallRef() : OrigCallee(), CallIndex(0), Version() {}
520 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
521 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
522
523 explicit operator bool() const { return OrigCallee; }
524
525 /// Get the parameter that the caller initialized, corresponding to the
526 /// given parameter in the callee.
527 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
528 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
529 : PVD;
530 }
531
532 /// The callee at the point where the arguments were evaluated. This might
533 /// be different from the actual callee (a different redeclaration, or a
534 /// virtual override), but this function's parameters are the ones that
535 /// appear in the parameter map.
536 const FunctionDecl *OrigCallee;
537 /// The call index of the frame that holds the argument values.
538 unsigned CallIndex;
539 /// The version of the parameters corresponding to this call.
540 unsigned Version;
541 };
542
543 /// A stack frame in the constexpr call stack.
544 class CallStackFrame : public interp::Frame {
545 public:
546 EvalInfo &Info;
547
548 /// Parent - The caller of this stack frame.
549 CallStackFrame *Caller;
550
551 /// Callee - The function which was called.
552 const FunctionDecl *Callee;
553
554 /// This - The binding for the this pointer in this call, if any.
555 const LValue *This;
556
557 /// CallExpr - The syntactical structure of member function calls
558 const Expr *CallExpr;
559
560 /// Information on how to find the arguments to this call. Our arguments
561 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
562 /// key and this value as the version.
563 CallRef Arguments;
564
565 /// Source location information about the default argument or default
566 /// initializer expression we're evaluating, if any.
567 CurrentSourceLocExprScope CurSourceLocExprScope;
568
569 // Note that we intentionally use std::map here so that references to
570 // values are stable.
571 typedef std::pair<const void *, unsigned> MapKeyTy;
572 typedef std::map<MapKeyTy, APValue> MapTy;
573 /// Temporaries - Temporary lvalues materialized within this stack frame.
574 MapTy Temporaries;
575
576 /// CallRange - The source range of the call expression for this call.
577 SourceRange CallRange;
578
579 /// Index - The call index of this call.
580 unsigned Index;
581
582 /// The stack of integers for tracking version numbers for temporaries.
583 SmallVector<unsigned, 2> TempVersionStack = {1};
584 unsigned CurTempVersion = TempVersionStack.back();
585
586 unsigned getTempVersion() const { return TempVersionStack.back(); }
587
588 void pushTempVersion() {
589 TempVersionStack.push_back(++CurTempVersion);
590 }
591
592 void popTempVersion() {
593 TempVersionStack.pop_back();
594 }
595
596 CallRef createCall(const FunctionDecl *Callee) {
597 return {Callee, Index, ++CurTempVersion};
598 }
599
600 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
601 // on the overall stack usage of deeply-recursing constexpr evaluations.
602 // (We should cache this map rather than recomputing it repeatedly.)
603 // But let's try this and see how it goes; we can look into caching the map
604 // as a later change.
605
606 /// LambdaCaptureFields - Mapping from captured variables/this to
607 /// corresponding data members in the closure class.
608 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
609 FieldDecl *LambdaThisCaptureField = nullptr;
610
611 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
612 const FunctionDecl *Callee, const LValue *This,
613 const Expr *CallExpr, CallRef Arguments);
614 ~CallStackFrame();
615
616 // Return the temporary for Key whose version number is Version.
617 APValue *getTemporary(const void *Key, unsigned Version) {
618 MapKeyTy KV(Key, Version);
619 auto LB = Temporaries.lower_bound(KV);
620 if (LB != Temporaries.end() && LB->first == KV)
621 return &LB->second;
622 return nullptr;
623 }
624
625 // Return the current temporary for Key in the map.
626 APValue *getCurrentTemporary(const void *Key) {
627 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
628 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
629 return &std::prev(UB)->second;
630 return nullptr;
631 }
632
633 // Return the version number of the current temporary for Key.
634 unsigned getCurrentTemporaryVersion(const void *Key) const {
635 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
636 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
637 return std::prev(UB)->first.second;
638 return 0;
639 }
640
641 /// Allocate storage for an object of type T in this stack frame.
642 /// Populates LV with a handle to the created object. Key identifies
643 /// the temporary within the stack frame, and must not be reused without
644 /// bumping the temporary version number.
645 template<typename KeyT>
646 APValue &createTemporary(const KeyT *Key, QualType T,
647 ScopeKind Scope, LValue &LV);
648
649 /// Allocate storage for a parameter of a function call made in this frame.
650 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
651
652 void describe(llvm::raw_ostream &OS) const override;
653
654 Frame *getCaller() const override { return Caller; }
655 SourceRange getCallRange() const override { return CallRange; }
656 const FunctionDecl *getCallee() const override { return Callee; }
657
658 bool isStdFunction() const {
659 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
660 if (DC->isStdNamespace())
661 return true;
662 return false;
663 }
664
665 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
666 /// permitted. See MSConstexprDocs for description of permitted contexts.
667 bool CanEvalMSConstexpr = false;
668
669 private:
670 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
671 ScopeKind Scope);
672 };
673
674 /// Temporarily override 'this'.
675 class ThisOverrideRAII {
676 public:
677 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
678 : Frame(Frame), OldThis(Frame.This) {
679 if (Enable)
680 Frame.This = NewThis;
681 }
682 ~ThisOverrideRAII() {
683 Frame.This = OldThis;
684 }
685 private:
686 CallStackFrame &Frame;
687 const LValue *OldThis;
688 };
689
690 // A shorthand time trace scope struct, prints source range, for example
691 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
692 class ExprTimeTraceScope {
693 public:
694 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
695 : TimeScope(Name, [E, &Ctx] {
696 return E->getSourceRange().printToString(Ctx.getSourceManager());
697 }) {}
698
699 private:
700 llvm::TimeTraceScope TimeScope;
701 };
702
703 /// RAII object used to change the current ability of
704 /// [[msvc::constexpr]] evaulation.
705 struct MSConstexprContextRAII {
706 CallStackFrame &Frame;
707 bool OldValue;
708 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
709 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
710 Frame.CanEvalMSConstexpr = Value;
711 }
712
713 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
714 };
715}
716
717static bool HandleDestruction(EvalInfo &Info, const Expr *E,
718 const LValue &This, QualType ThisType);
719static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
721 QualType T);
722
723namespace {
724 /// A cleanup, and a flag indicating whether it is lifetime-extended.
725 class Cleanup {
726 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
728 QualType T;
729
730 public:
731 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
732 ScopeKind Scope)
733 : Value(Val, Scope), Base(Base), T(T) {}
734
735 /// Determine whether this cleanup should be performed at the end of the
736 /// given kind of scope.
737 bool isDestroyedAtEndOf(ScopeKind K) const {
738 return (int)Value.getInt() >= (int)K;
739 }
740 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
741 if (RunDestructors) {
743 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
744 Loc = VD->getLocation();
745 else if (const Expr *E = Base.dyn_cast<const Expr*>())
746 Loc = E->getExprLoc();
747 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
748 }
749 *Value.getPointer() = APValue();
750 return true;
751 }
752
753 bool hasSideEffect() {
754 return T.isDestructedType();
755 }
756 };
757
758 /// A reference to an object whose construction we are currently evaluating.
759 struct ObjectUnderConstruction {
762 friend bool operator==(const ObjectUnderConstruction &LHS,
763 const ObjectUnderConstruction &RHS) {
764 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
765 }
766 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
767 return llvm::hash_combine(Obj.Base, Obj.Path);
768 }
769 };
770 enum class ConstructionPhase {
771 None,
772 Bases,
773 AfterBases,
774 AfterFields,
775 Destroying,
776 DestroyingBases
777 };
778}
779
780namespace llvm {
781template<> struct DenseMapInfo<ObjectUnderConstruction> {
782 using Base = DenseMapInfo<APValue::LValueBase>;
783 static ObjectUnderConstruction getEmptyKey() {
784 return {Base::getEmptyKey(), {}}; }
785 static ObjectUnderConstruction getTombstoneKey() {
786 return {Base::getTombstoneKey(), {}};
787 }
788 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
789 return hash_value(Object);
790 }
791 static bool isEqual(const ObjectUnderConstruction &LHS,
792 const ObjectUnderConstruction &RHS) {
793 return LHS == RHS;
794 }
795};
796}
797
798namespace {
799 /// A dynamically-allocated heap object.
800 struct DynAlloc {
801 /// The value of this heap-allocated object.
803 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
804 /// or a CallExpr (the latter is for direct calls to operator new inside
805 /// std::allocator<T>::allocate).
806 const Expr *AllocExpr = nullptr;
807
808 enum Kind {
809 New,
810 ArrayNew,
811 StdAllocator
812 };
813
814 /// Get the kind of the allocation. This must match between allocation
815 /// and deallocation.
816 Kind getKind() const {
817 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
818 return NE->isArray() ? ArrayNew : New;
819 assert(isa<CallExpr>(AllocExpr));
820 return StdAllocator;
821 }
822 };
823
824 struct DynAllocOrder {
825 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
826 return L.getIndex() < R.getIndex();
827 }
828 };
829
830 /// EvalInfo - This is a private struct used by the evaluator to capture
831 /// information about a subexpression as it is folded. It retains information
832 /// about the AST context, but also maintains information about the folded
833 /// expression.
834 ///
835 /// If an expression could be evaluated, it is still possible it is not a C
836 /// "integer constant expression" or constant expression. If not, this struct
837 /// captures information about how and why not.
838 ///
839 /// One bit of information passed *into* the request for constant folding
840 /// indicates whether the subexpression is "evaluated" or not according to C
841 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
842 /// evaluate the expression regardless of what the RHS is, but C only allows
843 /// certain things in certain situations.
844 class EvalInfo : public interp::State {
845 public:
846 ASTContext &Ctx;
847
848 /// EvalStatus - Contains information about the evaluation.
849 Expr::EvalStatus &EvalStatus;
850
851 /// CurrentCall - The top of the constexpr call stack.
852 CallStackFrame *CurrentCall;
853
854 /// CallStackDepth - The number of calls in the call stack right now.
855 unsigned CallStackDepth;
856
857 /// NextCallIndex - The next call index to assign.
858 unsigned NextCallIndex;
859
860 /// StepsLeft - The remaining number of evaluation steps we're permitted
861 /// to perform. This is essentially a limit for the number of statements
862 /// we will evaluate.
863 unsigned StepsLeft;
864
865 /// Enable the experimental new constant interpreter. If an expression is
866 /// not supported by the interpreter, an error is triggered.
867 bool EnableNewConstInterp;
868
869 /// BottomFrame - The frame in which evaluation started. This must be
870 /// initialized after CurrentCall and CallStackDepth.
871 CallStackFrame BottomFrame;
872
873 /// A stack of values whose lifetimes end at the end of some surrounding
874 /// evaluation frame.
876
877 /// EvaluatingDecl - This is the declaration whose initializer is being
878 /// evaluated, if any.
879 APValue::LValueBase EvaluatingDecl;
880
881 enum class EvaluatingDeclKind {
882 None,
883 /// We're evaluating the construction of EvaluatingDecl.
884 Ctor,
885 /// We're evaluating the destruction of EvaluatingDecl.
886 Dtor,
887 };
888 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
889
890 /// EvaluatingDeclValue - This is the value being constructed for the
891 /// declaration whose initializer is being evaluated, if any.
892 APValue *EvaluatingDeclValue;
893
894 /// Set of objects that are currently being constructed.
895 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
896 ObjectsUnderConstruction;
897
898 /// Current heap allocations, along with the location where each was
899 /// allocated. We use std::map here because we need stable addresses
900 /// for the stored APValues.
901 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
902
903 /// The number of heap allocations performed so far in this evaluation.
904 unsigned NumHeapAllocs = 0;
905
906 struct EvaluatingConstructorRAII {
907 EvalInfo &EI;
908 ObjectUnderConstruction Object;
909 bool DidInsert;
910 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
911 bool HasBases)
912 : EI(EI), Object(Object) {
913 DidInsert =
914 EI.ObjectsUnderConstruction
915 .insert({Object, HasBases ? ConstructionPhase::Bases
916 : ConstructionPhase::AfterBases})
917 .second;
918 }
919 void finishedConstructingBases() {
920 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
921 }
922 void finishedConstructingFields() {
923 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
924 }
925 ~EvaluatingConstructorRAII() {
926 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
927 }
928 };
929
930 struct EvaluatingDestructorRAII {
931 EvalInfo &EI;
932 ObjectUnderConstruction Object;
933 bool DidInsert;
934 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
935 : EI(EI), Object(Object) {
936 DidInsert = EI.ObjectsUnderConstruction
937 .insert({Object, ConstructionPhase::Destroying})
938 .second;
939 }
940 void startedDestroyingBases() {
941 EI.ObjectsUnderConstruction[Object] =
942 ConstructionPhase::DestroyingBases;
943 }
944 ~EvaluatingDestructorRAII() {
945 if (DidInsert)
946 EI.ObjectsUnderConstruction.erase(Object);
947 }
948 };
949
950 ConstructionPhase
951 isEvaluatingCtorDtor(APValue::LValueBase Base,
953 return ObjectsUnderConstruction.lookup({Base, Path});
954 }
955
956 /// If we're currently speculatively evaluating, the outermost call stack
957 /// depth at which we can mutate state, otherwise 0.
958 unsigned SpeculativeEvaluationDepth = 0;
959
960 /// The current array initialization index, if we're performing array
961 /// initialization.
962 uint64_t ArrayInitIndex = -1;
963
964 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
965 /// notes attached to it will also be stored, otherwise they will not be.
966 bool HasActiveDiagnostic;
967
968 /// Have we emitted a diagnostic explaining why we couldn't constant
969 /// fold (not just why it's not strictly a constant expression)?
970 bool HasFoldFailureDiagnostic;
971
972 /// Whether we're checking that an expression is a potential constant
973 /// expression. If so, do not fail on constructs that could become constant
974 /// later on (such as a use of an undefined global).
975 bool CheckingPotentialConstantExpression = false;
976
977 /// Whether we're checking for an expression that has undefined behavior.
978 /// If so, we will produce warnings if we encounter an operation that is
979 /// always undefined.
980 ///
981 /// Note that we still need to evaluate the expression normally when this
982 /// is set; this is used when evaluating ICEs in C.
983 bool CheckingForUndefinedBehavior = false;
984
985 enum EvaluationMode {
986 /// Evaluate as a constant expression. Stop if we find that the expression
987 /// is not a constant expression.
988 EM_ConstantExpression,
989
990 /// Evaluate as a constant expression. Stop if we find that the expression
991 /// is not a constant expression. Some expressions can be retried in the
992 /// optimizer if we don't constant fold them here, but in an unevaluated
993 /// context we try to fold them immediately since the optimizer never
994 /// gets a chance to look at it.
995 EM_ConstantExpressionUnevaluated,
996
997 /// Fold the expression to a constant. Stop if we hit a side-effect that
998 /// we can't model.
999 EM_ConstantFold,
1000
1001 /// Evaluate in any way we know how. Don't worry about side-effects that
1002 /// can't be modeled.
1003 EM_IgnoreSideEffects,
1004 } EvalMode;
1005
1006 /// Are we checking whether the expression is a potential constant
1007 /// expression?
1008 bool checkingPotentialConstantExpression() const override {
1009 return CheckingPotentialConstantExpression;
1010 }
1011
1012 /// Are we checking an expression for overflow?
1013 // FIXME: We should check for any kind of undefined or suspicious behavior
1014 // in such constructs, not just overflow.
1015 bool checkingForUndefinedBehavior() const override {
1016 return CheckingForUndefinedBehavior;
1017 }
1018
1019 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
1020 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
1021 CallStackDepth(0), NextCallIndex(1),
1022 StepsLeft(C.getLangOpts().ConstexprStepLimit),
1023 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
1024 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
1025 /*This=*/nullptr,
1026 /*CallExpr=*/nullptr, CallRef()),
1027 EvaluatingDecl((const ValueDecl *)nullptr),
1028 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
1029 HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
1030
1031 ~EvalInfo() {
1032 discardCleanups();
1033 }
1034
1035 ASTContext &getASTContext() const override { return Ctx; }
1036
1037 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
1038 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
1039 EvaluatingDecl = Base;
1040 IsEvaluatingDecl = EDK;
1041 EvaluatingDeclValue = &Value;
1042 }
1043
1044 bool CheckCallLimit(SourceLocation Loc) {
1045 // Don't perform any constexpr calls (other than the call we're checking)
1046 // when checking a potential constant expression.
1047 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1048 return false;
1049 if (NextCallIndex == 0) {
1050 // NextCallIndex has wrapped around.
1051 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1052 return false;
1053 }
1054 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1055 return true;
1056 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1057 << getLangOpts().ConstexprCallDepth;
1058 return false;
1059 }
1060
1061 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
1062 uint64_t ElemCount, bool Diag) {
1063 // FIXME: GH63562
1064 // APValue stores array extents as unsigned,
1065 // so anything that is greater that unsigned would overflow when
1066 // constructing the array, we catch this here.
1067 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
1068 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
1069 if (Diag)
1070 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
1071 return false;
1072 }
1073
1074 // FIXME: GH63562
1075 // Arrays allocate an APValue per element.
1076 // We use the number of constexpr steps as a proxy for the maximum size
1077 // of arrays to avoid exhausting the system resources, as initialization
1078 // of each element is likely to take some number of steps anyway.
1079 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
1080 if (ElemCount > Limit) {
1081 if (Diag)
1082 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
1083 << ElemCount << Limit;
1084 return false;
1085 }
1086 return true;
1087 }
1088
1089 std::pair<CallStackFrame *, unsigned>
1090 getCallFrameAndDepth(unsigned CallIndex) {
1091 assert(CallIndex && "no call index in getCallFrameAndDepth");
1092 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1093 // be null in this loop.
1094 unsigned Depth = CallStackDepth;
1095 CallStackFrame *Frame = CurrentCall;
1096 while (Frame->Index > CallIndex) {
1097 Frame = Frame->Caller;
1098 --Depth;
1099 }
1100 if (Frame->Index == CallIndex)
1101 return {Frame, Depth};
1102 return {nullptr, 0};
1103 }
1104
1105 bool nextStep(const Stmt *S) {
1106 if (!StepsLeft) {
1107 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1108 return false;
1109 }
1110 --StepsLeft;
1111 return true;
1112 }
1113
1114 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1115
1116 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1117 std::optional<DynAlloc *> Result;
1118 auto It = HeapAllocs.find(DA);
1119 if (It != HeapAllocs.end())
1120 Result = &It->second;
1121 return Result;
1122 }
1123
1124 /// Get the allocated storage for the given parameter of the given call.
1125 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1126 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1127 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1128 : nullptr;
1129 }
1130
1131 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1132 struct StdAllocatorCaller {
1133 unsigned FrameIndex;
1134 QualType ElemType;
1135 explicit operator bool() const { return FrameIndex != 0; };
1136 };
1137
1138 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1139 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1140 Call = Call->Caller) {
1141 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1142 if (!MD)
1143 continue;
1144 const IdentifierInfo *FnII = MD->getIdentifier();
1145 if (!FnII || !FnII->isStr(FnName))
1146 continue;
1147
1148 const auto *CTSD =
1149 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1150 if (!CTSD)
1151 continue;
1152
1153 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1154 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1155 if (CTSD->isInStdNamespace() && ClassII &&
1156 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1157 TAL[0].getKind() == TemplateArgument::Type)
1158 return {Call->Index, TAL[0].getAsType()};
1159 }
1160
1161 return {};
1162 }
1163
1164 void performLifetimeExtension() {
1165 // Disable the cleanups for lifetime-extended temporaries.
1166 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1167 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1168 });
1169 }
1170
1171 /// Throw away any remaining cleanups at the end of evaluation. If any
1172 /// cleanups would have had a side-effect, note that as an unmodeled
1173 /// side-effect and return false. Otherwise, return true.
1174 bool discardCleanups() {
1175 for (Cleanup &C : CleanupStack) {
1176 if (C.hasSideEffect() && !noteSideEffect()) {
1177 CleanupStack.clear();
1178 return false;
1179 }
1180 }
1181 CleanupStack.clear();
1182 return true;
1183 }
1184
1185 private:
1186 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1187 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1188
1189 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1190 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1191
1192 void setFoldFailureDiagnostic(bool Flag) override {
1193 HasFoldFailureDiagnostic = Flag;
1194 }
1195
1196 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1197
1198 // If we have a prior diagnostic, it will be noting that the expression
1199 // isn't a constant expression. This diagnostic is more important,
1200 // unless we require this evaluation to produce a constant expression.
1201 //
1202 // FIXME: We might want to show both diagnostics to the user in
1203 // EM_ConstantFold mode.
1204 bool hasPriorDiagnostic() override {
1205 if (!EvalStatus.Diag->empty()) {
1206 switch (EvalMode) {
1207 case EM_ConstantFold:
1208 case EM_IgnoreSideEffects:
1209 if (!HasFoldFailureDiagnostic)
1210 break;
1211 // We've already failed to fold something. Keep that diagnostic.
1212 [[fallthrough]];
1213 case EM_ConstantExpression:
1214 case EM_ConstantExpressionUnevaluated:
1215 setActiveDiagnostic(false);
1216 return true;
1217 }
1218 }
1219 return false;
1220 }
1221
1222 unsigned getCallStackDepth() override { return CallStackDepth; }
1223
1224 public:
1225 /// Should we continue evaluation after encountering a side-effect that we
1226 /// couldn't model?
1227 bool keepEvaluatingAfterSideEffect() const override {
1228 switch (EvalMode) {
1229 case EM_IgnoreSideEffects:
1230 return true;
1231
1232 case EM_ConstantExpression:
1233 case EM_ConstantExpressionUnevaluated:
1234 case EM_ConstantFold:
1235 // By default, assume any side effect might be valid in some other
1236 // evaluation of this expression from a different context.
1237 return checkingPotentialConstantExpression() ||
1238 checkingForUndefinedBehavior();
1239 }
1240 llvm_unreachable("Missed EvalMode case");
1241 }
1242
1243 /// Note that we have had a side-effect, and determine whether we should
1244 /// keep evaluating.
1245 bool noteSideEffect() override {
1246 EvalStatus.HasSideEffects = true;
1247 return keepEvaluatingAfterSideEffect();
1248 }
1249
1250 /// Should we continue evaluation after encountering undefined behavior?
1251 bool keepEvaluatingAfterUndefinedBehavior() {
1252 switch (EvalMode) {
1253 case EM_IgnoreSideEffects:
1254 case EM_ConstantFold:
1255 return true;
1256
1257 case EM_ConstantExpression:
1258 case EM_ConstantExpressionUnevaluated:
1259 return checkingForUndefinedBehavior();
1260 }
1261 llvm_unreachable("Missed EvalMode case");
1262 }
1263
1264 /// Note that we hit something that was technically undefined behavior, but
1265 /// that we can evaluate past it (such as signed overflow or floating-point
1266 /// division by zero.)
1267 bool noteUndefinedBehavior() override {
1268 EvalStatus.HasUndefinedBehavior = true;
1269 return keepEvaluatingAfterUndefinedBehavior();
1270 }
1271
1272 /// Should we continue evaluation as much as possible after encountering a
1273 /// construct which can't be reduced to a value?
1274 bool keepEvaluatingAfterFailure() const override {
1275 if (!StepsLeft)
1276 return false;
1277
1278 switch (EvalMode) {
1279 case EM_ConstantExpression:
1280 case EM_ConstantExpressionUnevaluated:
1281 case EM_ConstantFold:
1282 case EM_IgnoreSideEffects:
1283 return checkingPotentialConstantExpression() ||
1284 checkingForUndefinedBehavior();
1285 }
1286 llvm_unreachable("Missed EvalMode case");
1287 }
1288
1289 /// Notes that we failed to evaluate an expression that other expressions
1290 /// directly depend on, and determine if we should keep evaluating. This
1291 /// should only be called if we actually intend to keep evaluating.
1292 ///
1293 /// Call noteSideEffect() instead if we may be able to ignore the value that
1294 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1295 ///
1296 /// (Foo(), 1) // use noteSideEffect
1297 /// (Foo() || true) // use noteSideEffect
1298 /// Foo() + 1 // use noteFailure
1299 [[nodiscard]] bool noteFailure() {
1300 // Failure when evaluating some expression often means there is some
1301 // subexpression whose evaluation was skipped. Therefore, (because we
1302 // don't track whether we skipped an expression when unwinding after an
1303 // evaluation failure) every evaluation failure that bubbles up from a
1304 // subexpression implies that a side-effect has potentially happened. We
1305 // skip setting the HasSideEffects flag to true until we decide to
1306 // continue evaluating after that point, which happens here.
1307 bool KeepGoing = keepEvaluatingAfterFailure();
1308 EvalStatus.HasSideEffects |= KeepGoing;
1309 return KeepGoing;
1310 }
1311
1312 class ArrayInitLoopIndex {
1313 EvalInfo &Info;
1314 uint64_t OuterIndex;
1315
1316 public:
1317 ArrayInitLoopIndex(EvalInfo &Info)
1318 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1319 Info.ArrayInitIndex = 0;
1320 }
1321 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1322
1323 operator uint64_t&() { return Info.ArrayInitIndex; }
1324 };
1325 };
1326
1327 /// Object used to treat all foldable expressions as constant expressions.
1328 struct FoldConstant {
1329 EvalInfo &Info;
1330 bool Enabled;
1331 bool HadNoPriorDiags;
1332 EvalInfo::EvaluationMode OldMode;
1333
1334 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1335 : Info(Info),
1336 Enabled(Enabled),
1337 HadNoPriorDiags(Info.EvalStatus.Diag &&
1338 Info.EvalStatus.Diag->empty() &&
1339 !Info.EvalStatus.HasSideEffects),
1340 OldMode(Info.EvalMode) {
1341 if (Enabled)
1342 Info.EvalMode = EvalInfo::EM_ConstantFold;
1343 }
1344 void keepDiagnostics() { Enabled = false; }
1345 ~FoldConstant() {
1346 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1347 !Info.EvalStatus.HasSideEffects)
1348 Info.EvalStatus.Diag->clear();
1349 Info.EvalMode = OldMode;
1350 }
1351 };
1352
1353 /// RAII object used to set the current evaluation mode to ignore
1354 /// side-effects.
1355 struct IgnoreSideEffectsRAII {
1356 EvalInfo &Info;
1357 EvalInfo::EvaluationMode OldMode;
1358 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1359 : Info(Info), OldMode(Info.EvalMode) {
1360 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1361 }
1362
1363 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1364 };
1365
1366 /// RAII object used to optionally suppress diagnostics and side-effects from
1367 /// a speculative evaluation.
1368 class SpeculativeEvaluationRAII {
1369 EvalInfo *Info = nullptr;
1370 Expr::EvalStatus OldStatus;
1371 unsigned OldSpeculativeEvaluationDepth = 0;
1372
1373 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1374 Info = Other.Info;
1375 OldStatus = Other.OldStatus;
1376 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1377 Other.Info = nullptr;
1378 }
1379
1380 void maybeRestoreState() {
1381 if (!Info)
1382 return;
1383
1384 Info->EvalStatus = OldStatus;
1385 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1386 }
1387
1388 public:
1389 SpeculativeEvaluationRAII() = default;
1390
1391 SpeculativeEvaluationRAII(
1392 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1393 : Info(&Info), OldStatus(Info.EvalStatus),
1394 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1395 Info.EvalStatus.Diag = NewDiag;
1396 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1397 }
1398
1399 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1400 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1401 moveFromAndCancel(std::move(Other));
1402 }
1403
1404 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1405 maybeRestoreState();
1406 moveFromAndCancel(std::move(Other));
1407 return *this;
1408 }
1409
1410 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1411 };
1412
1413 /// RAII object wrapping a full-expression or block scope, and handling
1414 /// the ending of the lifetime of temporaries created within it.
1415 template<ScopeKind Kind>
1416 class ScopeRAII {
1417 EvalInfo &Info;
1418 unsigned OldStackSize;
1419 public:
1420 ScopeRAII(EvalInfo &Info)
1421 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1422 // Push a new temporary version. This is needed to distinguish between
1423 // temporaries created in different iterations of a loop.
1424 Info.CurrentCall->pushTempVersion();
1425 }
1426 bool destroy(bool RunDestructors = true) {
1427 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1428 OldStackSize = -1U;
1429 return OK;
1430 }
1431 ~ScopeRAII() {
1432 if (OldStackSize != -1U)
1433 destroy(false);
1434 // Body moved to a static method to encourage the compiler to inline away
1435 // instances of this class.
1436 Info.CurrentCall->popTempVersion();
1437 }
1438 private:
1439 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1440 unsigned OldStackSize) {
1441 assert(OldStackSize <= Info.CleanupStack.size() &&
1442 "running cleanups out of order?");
1443
1444 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1445 // for a full-expression scope.
1446 bool Success = true;
1447 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1448 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1449 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1450 Success = false;
1451 break;
1452 }
1453 }
1454 }
1455
1456 // Compact any retained cleanups.
1457 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1458 if (Kind != ScopeKind::Block)
1459 NewEnd =
1460 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1461 return C.isDestroyedAtEndOf(Kind);
1462 });
1463 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1464 return Success;
1465 }
1466 };
1467 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1468 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1469 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1470}
1471
1472bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1473 CheckSubobjectKind CSK) {
1474 if (Invalid)
1475 return false;
1476 if (isOnePastTheEnd()) {
1477 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1478 << CSK;
1479 setInvalid();
1480 return false;
1481 }
1482 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1483 // must actually be at least one array element; even a VLA cannot have a
1484 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1485 return true;
1486}
1487
1488void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1489 const Expr *E) {
1490 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1491 // Do not set the designator as invalid: we can represent this situation,
1492 // and correct handling of __builtin_object_size requires us to do so.
1493}
1494
1495void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1496 const Expr *E,
1497 const APSInt &N) {
1498 // If we're complaining, we must be able to statically determine the size of
1499 // the most derived array.
1500 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1501 Info.CCEDiag(E, diag::note_constexpr_array_index)
1502 << N << /*array*/ 0
1503 << static_cast<unsigned>(getMostDerivedArraySize());
1504 else
1505 Info.CCEDiag(E, diag::note_constexpr_array_index)
1506 << N << /*non-array*/ 1;
1507 setInvalid();
1508}
1509
1510CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1511 const FunctionDecl *Callee, const LValue *This,
1512 const Expr *CallExpr, CallRef Call)
1513 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1514 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1515 Index(Info.NextCallIndex++) {
1516 Info.CurrentCall = this;
1517 ++Info.CallStackDepth;
1518}
1519
1520CallStackFrame::~CallStackFrame() {
1521 assert(Info.CurrentCall == this && "calls retired out of order");
1522 --Info.CallStackDepth;
1523 Info.CurrentCall = Caller;
1524}
1525
1526static bool isRead(AccessKinds AK) {
1527 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1528 AK == AK_IsWithinLifetime;
1529}
1530
1532 switch (AK) {
1533 case AK_Read:
1535 case AK_MemberCall:
1536 case AK_DynamicCast:
1537 case AK_TypeId:
1539 return false;
1540 case AK_Assign:
1541 case AK_Increment:
1542 case AK_Decrement:
1543 case AK_Construct:
1544 case AK_Destroy:
1545 return true;
1546 }
1547 llvm_unreachable("unknown access kind");
1548}
1549
1550static bool isAnyAccess(AccessKinds AK) {
1551 return isRead(AK) || isModification(AK);
1552}
1553
1554/// Is this an access per the C++ definition?
1556 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1557 AK != AK_IsWithinLifetime;
1558}
1559
1560/// Is this kind of axcess valid on an indeterminate object value?
1562 switch (AK) {
1563 case AK_Read:
1564 case AK_Increment:
1565 case AK_Decrement:
1566 // These need the object's value.
1567 return false;
1568
1571 case AK_Assign:
1572 case AK_Construct:
1573 case AK_Destroy:
1574 // Construction and destruction don't need the value.
1575 return true;
1576
1577 case AK_MemberCall:
1578 case AK_DynamicCast:
1579 case AK_TypeId:
1580 // These aren't really meaningful on scalars.
1581 return true;
1582 }
1583 llvm_unreachable("unknown access kind");
1584}
1585
1586namespace {
1587 struct ComplexValue {
1588 private:
1589 bool IsInt;
1590
1591 public:
1592 APSInt IntReal, IntImag;
1593 APFloat FloatReal, FloatImag;
1594
1595 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1596
1597 void makeComplexFloat() { IsInt = false; }
1598 bool isComplexFloat() const { return !IsInt; }
1599 APFloat &getComplexFloatReal() { return FloatReal; }
1600 APFloat &getComplexFloatImag() { return FloatImag; }
1601
1602 void makeComplexInt() { IsInt = true; }
1603 bool isComplexInt() const { return IsInt; }
1604 APSInt &getComplexIntReal() { return IntReal; }
1605 APSInt &getComplexIntImag() { return IntImag; }
1606
1607 void moveInto(APValue &v) const {
1608 if (isComplexFloat())
1609 v = APValue(FloatReal, FloatImag);
1610 else
1611 v = APValue(IntReal, IntImag);
1612 }
1613 void setFrom(const APValue &v) {
1614 assert(v.isComplexFloat() || v.isComplexInt());
1615 if (v.isComplexFloat()) {
1616 makeComplexFloat();
1617 FloatReal = v.getComplexFloatReal();
1618 FloatImag = v.getComplexFloatImag();
1619 } else {
1620 makeComplexInt();
1621 IntReal = v.getComplexIntReal();
1622 IntImag = v.getComplexIntImag();
1623 }
1624 }
1625 };
1626
1627 struct LValue {
1629 CharUnits Offset;
1630 SubobjectDesignator Designator;
1631 bool IsNullPtr : 1;
1632 bool InvalidBase : 1;
1633
1634 const APValue::LValueBase getLValueBase() const { return Base; }
1635 CharUnits &getLValueOffset() { return Offset; }
1636 const CharUnits &getLValueOffset() const { return Offset; }
1637 SubobjectDesignator &getLValueDesignator() { return Designator; }
1638 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1639 bool isNullPointer() const { return IsNullPtr;}
1640
1641 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1642 unsigned getLValueVersion() const { return Base.getVersion(); }
1643
1644 void moveInto(APValue &V) const {
1645 if (Designator.Invalid)
1646 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1647 else {
1648 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1649 V = APValue(Base, Offset, Designator.Entries,
1650 Designator.IsOnePastTheEnd, IsNullPtr);
1651 }
1652 }
1653 void setFrom(ASTContext &Ctx, const APValue &V) {
1654 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1655 Base = V.getLValueBase();
1656 Offset = V.getLValueOffset();
1657 InvalidBase = false;
1658 Designator = SubobjectDesignator(Ctx, V);
1659 IsNullPtr = V.isNullPointer();
1660 }
1661
1662 void set(APValue::LValueBase B, bool BInvalid = false) {
1663#ifndef NDEBUG
1664 // We only allow a few types of invalid bases. Enforce that here.
1665 if (BInvalid) {
1666 const auto *E = B.get<const Expr *>();
1667 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1668 "Unexpected type of invalid base");
1669 }
1670#endif
1671
1672 Base = B;
1673 Offset = CharUnits::fromQuantity(0);
1674 InvalidBase = BInvalid;
1675 Designator = SubobjectDesignator(getType(B));
1676 IsNullPtr = false;
1677 }
1678
1679 void setNull(ASTContext &Ctx, QualType PointerTy) {
1680 Base = (const ValueDecl *)nullptr;
1681 Offset =
1683 InvalidBase = false;
1684 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1685 IsNullPtr = true;
1686 }
1687
1688 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1689 set(B, true);
1690 }
1691
1692 std::string toString(ASTContext &Ctx, QualType T) const {
1693 APValue Printable;
1694 moveInto(Printable);
1695 return Printable.getAsString(Ctx, T);
1696 }
1697
1698 private:
1699 // Check that this LValue is not based on a null pointer. If it is, produce
1700 // a diagnostic and mark the designator as invalid.
1701 template <typename GenDiagType>
1702 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1703 if (Designator.Invalid)
1704 return false;
1705 if (IsNullPtr) {
1706 GenDiag();
1707 Designator.setInvalid();
1708 return false;
1709 }
1710 return true;
1711 }
1712
1713 public:
1714 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1715 CheckSubobjectKind CSK) {
1716 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1717 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1718 });
1719 }
1720
1721 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1722 AccessKinds AK) {
1723 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1724 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1725 });
1726 }
1727
1728 // Check this LValue refers to an object. If not, set the designator to be
1729 // invalid and emit a diagnostic.
1730 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1731 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1732 Designator.checkSubobject(Info, E, CSK);
1733 }
1734
1735 void addDecl(EvalInfo &Info, const Expr *E,
1736 const Decl *D, bool Virtual = false) {
1737 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1738 Designator.addDeclUnchecked(D, Virtual);
1739 }
1740 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1741 if (!Designator.Entries.empty()) {
1742 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1743 Designator.setInvalid();
1744 return;
1745 }
1746 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1747 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1748 Designator.FirstEntryIsAnUnsizedArray = true;
1749 Designator.addUnsizedArrayUnchecked(ElemTy);
1750 }
1751 }
1752 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1753 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1754 Designator.addArrayUnchecked(CAT);
1755 }
1756 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1757 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1758 Designator.addComplexUnchecked(EltTy, Imag);
1759 }
1760 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1761 uint64_t Size, uint64_t Idx) {
1762 if (checkSubobject(Info, E, CSK_VectorElement))
1763 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1764 }
1765 void clearIsNullPointer() {
1766 IsNullPtr = false;
1767 }
1768 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1769 const APSInt &Index, CharUnits ElementSize) {
1770 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1771 // but we're not required to diagnose it and it's valid in C++.)
1772 if (!Index)
1773 return;
1774
1775 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1776 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1777 // offsets.
1778 uint64_t Offset64 = Offset.getQuantity();
1779 uint64_t ElemSize64 = ElementSize.getQuantity();
1780 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1781 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1782
1783 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1784 Designator.adjustIndex(Info, E, Index);
1785 clearIsNullPointer();
1786 }
1787 void adjustOffset(CharUnits N) {
1788 Offset += N;
1789 if (N.getQuantity())
1790 clearIsNullPointer();
1791 }
1792 };
1793
1794 struct MemberPtr {
1795 MemberPtr() {}
1796 explicit MemberPtr(const ValueDecl *Decl)
1797 : DeclAndIsDerivedMember(Decl, false) {}
1798
1799 /// The member or (direct or indirect) field referred to by this member
1800 /// pointer, or 0 if this is a null member pointer.
1801 const ValueDecl *getDecl() const {
1802 return DeclAndIsDerivedMember.getPointer();
1803 }
1804 /// Is this actually a member of some type derived from the relevant class?
1805 bool isDerivedMember() const {
1806 return DeclAndIsDerivedMember.getInt();
1807 }
1808 /// Get the class which the declaration actually lives in.
1809 const CXXRecordDecl *getContainingRecord() const {
1810 return cast<CXXRecordDecl>(
1811 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1812 }
1813
1814 void moveInto(APValue &V) const {
1815 V = APValue(getDecl(), isDerivedMember(), Path);
1816 }
1817 void setFrom(const APValue &V) {
1818 assert(V.isMemberPointer());
1819 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1820 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1821 Path.clear();
1822 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1823 Path.insert(Path.end(), P.begin(), P.end());
1824 }
1825
1826 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1827 /// whether the member is a member of some class derived from the class type
1828 /// of the member pointer.
1829 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1830 /// Path - The path of base/derived classes from the member declaration's
1831 /// class (exclusive) to the class type of the member pointer (inclusive).
1833
1834 /// Perform a cast towards the class of the Decl (either up or down the
1835 /// hierarchy).
1836 bool castBack(const CXXRecordDecl *Class) {
1837 assert(!Path.empty());
1838 const CXXRecordDecl *Expected;
1839 if (Path.size() >= 2)
1840 Expected = Path[Path.size() - 2];
1841 else
1842 Expected = getContainingRecord();
1843 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1844 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1845 // if B does not contain the original member and is not a base or
1846 // derived class of the class containing the original member, the result
1847 // of the cast is undefined.
1848 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1849 // (D::*). We consider that to be a language defect.
1850 return false;
1851 }
1852 Path.pop_back();
1853 return true;
1854 }
1855 /// Perform a base-to-derived member pointer cast.
1856 bool castToDerived(const CXXRecordDecl *Derived) {
1857 if (!getDecl())
1858 return true;
1859 if (!isDerivedMember()) {
1860 Path.push_back(Derived);
1861 return true;
1862 }
1863 if (!castBack(Derived))
1864 return false;
1865 if (Path.empty())
1866 DeclAndIsDerivedMember.setInt(false);
1867 return true;
1868 }
1869 /// Perform a derived-to-base member pointer cast.
1870 bool castToBase(const CXXRecordDecl *Base) {
1871 if (!getDecl())
1872 return true;
1873 if (Path.empty())
1874 DeclAndIsDerivedMember.setInt(true);
1875 if (isDerivedMember()) {
1876 Path.push_back(Base);
1877 return true;
1878 }
1879 return castBack(Base);
1880 }
1881 };
1882
1883 /// Compare two member pointers, which are assumed to be of the same type.
1884 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1885 if (!LHS.getDecl() || !RHS.getDecl())
1886 return !LHS.getDecl() && !RHS.getDecl();
1887 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1888 return false;
1889 return LHS.Path == RHS.Path;
1890 }
1891}
1892
1893static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1894static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1895 const LValue &This, const Expr *E,
1896 bool AllowNonLiteralTypes = false);
1897static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1898 bool InvalidBaseOK = false);
1899static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1900 bool InvalidBaseOK = false);
1901static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1902 EvalInfo &Info);
1903static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1904static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1905static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1906 EvalInfo &Info);
1907static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1908static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1909static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1910 EvalInfo &Info);
1911static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1912static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1913 EvalInfo &Info,
1914 std::string *StringResult = nullptr);
1915
1916/// Evaluate an integer or fixed point expression into an APResult.
1917static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1918 EvalInfo &Info);
1919
1920/// Evaluate only a fixed point expression into an APResult.
1921static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1922 EvalInfo &Info);
1923
1924//===----------------------------------------------------------------------===//
1925// Misc utilities
1926//===----------------------------------------------------------------------===//
1927
1928/// Negate an APSInt in place, converting it to a signed form if necessary, and
1929/// preserving its value (by extending by up to one bit as needed).
1930static void negateAsSigned(APSInt &Int) {
1931 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1932 Int = Int.extend(Int.getBitWidth() + 1);
1933 Int.setIsSigned(true);
1934 }
1935 Int = -Int;
1936}
1937
1938template<typename KeyT>
1939APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1940 ScopeKind Scope, LValue &LV) {
1941 unsigned Version = getTempVersion();
1942 APValue::LValueBase Base(Key, Index, Version);
1943 LV.set(Base);
1944 return createLocal(Base, Key, T, Scope);
1945}
1946
1947/// Allocate storage for a parameter of a function call made in this frame.
1948APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1949 LValue &LV) {
1950 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1951 APValue::LValueBase Base(PVD, Index, Args.Version);
1952 LV.set(Base);
1953 // We always destroy parameters at the end of the call, even if we'd allow
1954 // them to live to the end of the full-expression at runtime, in order to
1955 // give portable results and match other compilers.
1956 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1957}
1958
1959APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1960 QualType T, ScopeKind Scope) {
1961 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1962 unsigned Version = Base.getVersion();
1963 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1964 assert(Result.isAbsent() && "local created multiple times");
1965
1966 // If we're creating a local immediately in the operand of a speculative
1967 // evaluation, don't register a cleanup to be run outside the speculative
1968 // evaluation context, since we won't actually be able to initialize this
1969 // object.
1970 if (Index <= Info.SpeculativeEvaluationDepth) {
1971 if (T.isDestructedType())
1972 Info.noteSideEffect();
1973 } else {
1974 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1975 }
1976 return Result;
1977}
1978
1979APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1980 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1981 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1982 return nullptr;
1983 }
1984
1985 DynamicAllocLValue DA(NumHeapAllocs++);
1987 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1988 std::forward_as_tuple(DA), std::tuple<>());
1989 assert(Result.second && "reused a heap alloc index?");
1990 Result.first->second.AllocExpr = E;
1991 return &Result.first->second.Value;
1992}
1993
1994/// Produce a string describing the given constexpr call.
1995void CallStackFrame::describe(raw_ostream &Out) const {
1996 unsigned ArgIndex = 0;
1997 bool IsMemberCall =
1998 isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
1999 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
2000
2001 if (!IsMemberCall)
2002 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2003 /*Qualified=*/false);
2004
2005 if (This && IsMemberCall) {
2006 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
2007 const Expr *Object = MCE->getImplicitObjectArgument();
2008 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
2009 /*Indentation=*/0);
2010 if (Object->getType()->isPointerType())
2011 Out << "->";
2012 else
2013 Out << ".";
2014 } else if (const auto *OCE =
2015 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
2016 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
2017 Info.Ctx.getPrintingPolicy(),
2018 /*Indentation=*/0);
2019 Out << ".";
2020 } else {
2021 APValue Val;
2022 This->moveInto(Val);
2023 Val.printPretty(
2024 Out, Info.Ctx,
2025 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
2026 Out << ".";
2027 }
2028 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2029 /*Qualified=*/false);
2030 IsMemberCall = false;
2031 }
2032
2033 Out << '(';
2034
2035 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2036 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2037 if (ArgIndex > (unsigned)IsMemberCall)
2038 Out << ", ";
2039
2040 const ParmVarDecl *Param = *I;
2041 APValue *V = Info.getParamSlot(Arguments, Param);
2042 if (V)
2043 V->printPretty(Out, Info.Ctx, Param->getType());
2044 else
2045 Out << "<...>";
2046
2047 if (ArgIndex == 0 && IsMemberCall)
2048 Out << "->" << *Callee << '(';
2049 }
2050
2051 Out << ')';
2052}
2053
2054/// Evaluate an expression to see if it had side-effects, and discard its
2055/// result.
2056/// \return \c true if the caller should keep evaluating.
2057static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2058 assert(!E->isValueDependent());
2059 APValue Scratch;
2060 if (!Evaluate(Scratch, Info, E))
2061 // We don't need the value, but we might have skipped a side effect here.
2062 return Info.noteSideEffect();
2063 return true;
2064}
2065
2066/// Should this call expression be treated as forming an opaque constant?
2067static bool IsOpaqueConstantCall(const CallExpr *E) {
2068 unsigned Builtin = E->getBuiltinCallee();
2069 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2070 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2071 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
2072 Builtin == Builtin::BI__builtin_function_start);
2073}
2074
2075static bool IsOpaqueConstantCall(const LValue &LVal) {
2076 const auto *BaseExpr =
2077 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
2078 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
2079}
2080
2082 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2083 // constant expression of pointer type that evaluates to...
2084
2085 // ... a null pointer value, or a prvalue core constant expression of type
2086 // std::nullptr_t.
2087 if (!B)
2088 return true;
2089
2090 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2091 // ... the address of an object with static storage duration,
2092 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2093 return VD->hasGlobalStorage();
2094 if (isa<TemplateParamObjectDecl>(D))
2095 return true;
2096 // ... the address of a function,
2097 // ... the address of a GUID [MS extension],
2098 // ... the address of an unnamed global constant
2099 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
2100 }
2101
2102 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2103 return true;
2104
2105 const Expr *E = B.get<const Expr*>();
2106 switch (E->getStmtClass()) {
2107 default:
2108 return false;
2109 case Expr::CompoundLiteralExprClass: {
2110 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2111 return CLE->isFileScope() && CLE->isLValue();
2112 }
2113 case Expr::MaterializeTemporaryExprClass:
2114 // A materialized temporary might have been lifetime-extended to static
2115 // storage duration.
2116 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2117 // A string literal has static storage duration.
2118 case Expr::StringLiteralClass:
2119 case Expr::PredefinedExprClass:
2120 case Expr::ObjCStringLiteralClass:
2121 case Expr::ObjCEncodeExprClass:
2122 return true;
2123 case Expr::ObjCBoxedExprClass:
2124 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2125 case Expr::CallExprClass:
2126 return IsOpaqueConstantCall(cast<CallExpr>(E));
2127 // For GCC compatibility, &&label has static storage duration.
2128 case Expr::AddrLabelExprClass:
2129 return true;
2130 // A Block literal expression may be used as the initialization value for
2131 // Block variables at global or local static scope.
2132 case Expr::BlockExprClass:
2133 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2134 // The APValue generated from a __builtin_source_location will be emitted as a
2135 // literal.
2136 case Expr::SourceLocExprClass:
2137 return true;
2138 case Expr::ImplicitValueInitExprClass:
2139 // FIXME:
2140 // We can never form an lvalue with an implicit value initialization as its
2141 // base through expression evaluation, so these only appear in one case: the
2142 // implicit variable declaration we invent when checking whether a constexpr
2143 // constructor can produce a constant expression. We must assume that such
2144 // an expression might be a global lvalue.
2145 return true;
2146 }
2147}
2148
2149static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2150 return LVal.Base.dyn_cast<const ValueDecl*>();
2151}
2152
2153// Information about an LValueBase that is some kind of string.
2156 StringRef Bytes;
2158};
2159
2160// Gets the lvalue base of LVal as a string.
2161static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2162 LValueBaseString &AsString) {
2163 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2164 if (!BaseExpr)
2165 return false;
2166
2167 // For ObjCEncodeExpr, we need to compute and store the string.
2168 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2169 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2170 AsString.ObjCEncodeStorage);
2171 AsString.Bytes = AsString.ObjCEncodeStorage;
2172 AsString.CharWidth = 1;
2173 return true;
2174 }
2175
2176 // Otherwise, we have a StringLiteral.
2177 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2178 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2179 Lit = PE->getFunctionName();
2180
2181 if (!Lit)
2182 return false;
2183
2184 AsString.Bytes = Lit->getBytes();
2185 AsString.CharWidth = Lit->getCharByteWidth();
2186 return true;
2187}
2188
2189// Determine whether two string literals potentially overlap. This will be the
2190// case if they agree on the values of all the bytes on the overlapping region
2191// between them.
2192//
2193// The overlapping region is the portion of the two string literals that must
2194// overlap in memory if the pointers actually point to the same address at
2195// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2196// the overlapping region is "cdef\0", which in this case does agree, so the
2197// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2198// "bazbar" + 3, the overlapping region contains all of both strings, so they
2199// are not potentially overlapping, even though they agree from the given
2200// addresses onwards.
2201//
2202// See open core issue CWG2765 which is discussing the desired rule here.
2203static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2204 const LValue &LHS,
2205 const LValue &RHS) {
2206 LValueBaseString LHSString, RHSString;
2207 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2208 !GetLValueBaseAsString(Info, RHS, RHSString))
2209 return false;
2210
2211 // This is the byte offset to the location of the first character of LHS
2212 // within RHS. We don't need to look at the characters of one string that
2213 // would appear before the start of the other string if they were merged.
2214 CharUnits Offset = RHS.Offset - LHS.Offset;
2215 if (Offset.isNegative())
2216 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2217 else
2218 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2219
2220 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2221 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2222 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2223 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2224
2225 // The null terminator isn't included in the string data, so check for it
2226 // manually. If the longer string doesn't have a null terminator where the
2227 // shorter string ends, they aren't potentially overlapping.
2228 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2229 if (Shorter.size() + NullByte >= Longer.size())
2230 break;
2231 if (Longer[Shorter.size() + NullByte])
2232 return false;
2233 }
2234
2235 // Otherwise, they're potentially overlapping if and only if the overlapping
2236 // region is the same.
2237 return Shorter == Longer.take_front(Shorter.size());
2238}
2239
2240static bool IsWeakLValue(const LValue &Value) {
2242 return Decl && Decl->isWeak();
2243}
2244
2245static bool isZeroSized(const LValue &Value) {
2247 if (isa_and_nonnull<VarDecl>(Decl)) {
2248 QualType Ty = Decl->getType();
2249 if (Ty->isArrayType())
2250 return Ty->isIncompleteType() ||
2251 Decl->getASTContext().getTypeSize(Ty) == 0;
2252 }
2253 return false;
2254}
2255
2256static bool HasSameBase(const LValue &A, const LValue &B) {
2257 if (!A.getLValueBase())
2258 return !B.getLValueBase();
2259 if (!B.getLValueBase())
2260 return false;
2261
2262 if (A.getLValueBase().getOpaqueValue() !=
2263 B.getLValueBase().getOpaqueValue())
2264 return false;
2265
2266 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2267 A.getLValueVersion() == B.getLValueVersion();
2268}
2269
2270static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2271 assert(Base && "no location for a null lvalue");
2272 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2273
2274 // For a parameter, find the corresponding call stack frame (if it still
2275 // exists), and point at the parameter of the function definition we actually
2276 // invoked.
2277 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2278 unsigned Idx = PVD->getFunctionScopeIndex();
2279 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2280 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2281 F->Arguments.Version == Base.getVersion() && F->Callee &&
2282 Idx < F->Callee->getNumParams()) {
2283 VD = F->Callee->getParamDecl(Idx);
2284 break;
2285 }
2286 }
2287 }
2288
2289 if (VD)
2290 Info.Note(VD->getLocation(), diag::note_declared_at);
2291 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2292 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2293 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2294 // FIXME: Produce a note for dangling pointers too.
2295 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2296 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2297 diag::note_constexpr_dynamic_alloc_here);
2298 }
2299
2300 // We have no information to show for a typeid(T) object.
2301}
2302
2306};
2307
2308/// Materialized temporaries that we've already checked to determine if they're
2309/// initializsed by a constant expression.
2312
2314 EvalInfo &Info, SourceLocation DiagLoc,
2315 QualType Type, const APValue &Value,
2316 ConstantExprKind Kind,
2317 const FieldDecl *SubobjectDecl,
2318 CheckedTemporaries &CheckedTemps);
2319
2320/// Check that this reference or pointer core constant expression is a valid
2321/// value for an address or reference constant expression. Return true if we
2322/// can fold this expression, whether or not it's a constant expression.
2324 QualType Type, const LValue &LVal,
2325 ConstantExprKind Kind,
2326 CheckedTemporaries &CheckedTemps) {
2327 bool IsReferenceType = Type->isReferenceType();
2328
2329 APValue::LValueBase Base = LVal.getLValueBase();
2330 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2331
2332 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2333 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2334
2335 // Additional restrictions apply in a template argument. We only enforce the
2336 // C++20 restrictions here; additional syntactic and semantic restrictions
2337 // are applied elsewhere.
2338 if (isTemplateArgument(Kind)) {
2339 int InvalidBaseKind = -1;
2340 StringRef Ident;
2341 if (Base.is<TypeInfoLValue>())
2342 InvalidBaseKind = 0;
2343 else if (isa_and_nonnull<StringLiteral>(BaseE))
2344 InvalidBaseKind = 1;
2345 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2346 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2347 InvalidBaseKind = 2;
2348 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2349 InvalidBaseKind = 3;
2350 Ident = PE->getIdentKindName();
2351 }
2352
2353 if (InvalidBaseKind != -1) {
2354 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2355 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2356 << Ident;
2357 return false;
2358 }
2359 }
2360
2361 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2362 FD && FD->isImmediateFunction()) {
2363 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2364 << !Type->isAnyPointerType();
2365 Info.Note(FD->getLocation(), diag::note_declared_at);
2366 return false;
2367 }
2368
2369 // Check that the object is a global. Note that the fake 'this' object we
2370 // manufacture when checking potential constant expressions is conservatively
2371 // assumed to be global here.
2372 if (!IsGlobalLValue(Base)) {
2373 if (Info.getLangOpts().CPlusPlus11) {
2374 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2375 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2376 << BaseVD;
2377 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2378 if (VarD && VarD->isConstexpr()) {
2379 // Non-static local constexpr variables have unintuitive semantics:
2380 // constexpr int a = 1;
2381 // constexpr const int *p = &a;
2382 // ... is invalid because the address of 'a' is not constant. Suggest
2383 // adding a 'static' in this case.
2384 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2385 << VarD
2386 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2387 } else {
2388 NoteLValueLocation(Info, Base);
2389 }
2390 } else {
2391 Info.FFDiag(Loc);
2392 }
2393 // Don't allow references to temporaries to escape.
2394 return false;
2395 }
2396 assert((Info.checkingPotentialConstantExpression() ||
2397 LVal.getLValueCallIndex() == 0) &&
2398 "have call index for global lvalue");
2399
2400 if (Base.is<DynamicAllocLValue>()) {
2401 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2402 << IsReferenceType << !Designator.Entries.empty();
2403 NoteLValueLocation(Info, Base);
2404 return false;
2405 }
2406
2407 if (BaseVD) {
2408 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2409 // Check if this is a thread-local variable.
2410 if (Var->getTLSKind())
2411 // FIXME: Diagnostic!
2412 return false;
2413
2414 // A dllimport variable never acts like a constant, unless we're
2415 // evaluating a value for use only in name mangling.
2416 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2417 // FIXME: Diagnostic!
2418 return false;
2419
2420 // In CUDA/HIP device compilation, only device side variables have
2421 // constant addresses.
2422 if (Info.getASTContext().getLangOpts().CUDA &&
2423 Info.getASTContext().getLangOpts().CUDAIsDevice &&
2424 Info.getASTContext().CUDAConstantEvalCtx.NoWrongSidedVars) {
2425 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2426 !Var->hasAttr<CUDAConstantAttr>() &&
2427 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2428 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2429 Var->hasAttr<HIPManagedAttr>())
2430 return false;
2431 }
2432 }
2433 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2434 // __declspec(dllimport) must be handled very carefully:
2435 // We must never initialize an expression with the thunk in C++.
2436 // Doing otherwise would allow the same id-expression to yield
2437 // different addresses for the same function in different translation
2438 // units. However, this means that we must dynamically initialize the
2439 // expression with the contents of the import address table at runtime.
2440 //
2441 // The C language has no notion of ODR; furthermore, it has no notion of
2442 // dynamic initialization. This means that we are permitted to
2443 // perform initialization with the address of the thunk.
2444 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2445 FD->hasAttr<DLLImportAttr>())
2446 // FIXME: Diagnostic!
2447 return false;
2448 }
2449 } else if (const auto *MTE =
2450 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2451 if (CheckedTemps.insert(MTE).second) {
2452 QualType TempType = getType(Base);
2453 if (TempType.isDestructedType()) {
2454 Info.FFDiag(MTE->getExprLoc(),
2455 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2456 << TempType;
2457 return false;
2458 }
2459
2460 APValue *V = MTE->getOrCreateValue(false);
2461 assert(V && "evasluation result refers to uninitialised temporary");
2462 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2463 Info, MTE->getExprLoc(), TempType, *V, Kind,
2464 /*SubobjectDecl=*/nullptr, CheckedTemps))
2465 return false;
2466 }
2467 }
2468
2469 // Allow address constant expressions to be past-the-end pointers. This is
2470 // an extension: the standard requires them to point to an object.
2471 if (!IsReferenceType)
2472 return true;
2473
2474 // A reference constant expression must refer to an object.
2475 if (!Base) {
2476 // FIXME: diagnostic
2477 Info.CCEDiag(Loc);
2478 return true;
2479 }
2480
2481 // Does this refer one past the end of some object?
2482 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2483 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2484 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2485 NoteLValueLocation(Info, Base);
2486 }
2487
2488 return true;
2489}
2490
2491/// Member pointers are constant expressions unless they point to a
2492/// non-virtual dllimport member function.
2493static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2495 QualType Type,
2496 const APValue &Value,
2497 ConstantExprKind Kind) {
2498 const ValueDecl *Member = Value.getMemberPointerDecl();
2499 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2500 if (!FD)
2501 return true;
2502 if (FD->isImmediateFunction()) {
2503 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2504 Info.Note(FD->getLocation(), diag::note_declared_at);
2505 return false;
2506 }
2507 return isForManglingOnly(Kind) || FD->isVirtual() ||
2508 !FD->hasAttr<DLLImportAttr>();
2509}
2510
2511/// Check that this core constant expression is of literal type, and if not,
2512/// produce an appropriate diagnostic.
2513static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2514 const LValue *This = nullptr) {
2515 // The restriction to literal types does not exist in C++23 anymore.
2516 if (Info.getLangOpts().CPlusPlus23)
2517 return true;
2518
2519 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2520 return true;
2521
2522 // C++1y: A constant initializer for an object o [...] may also invoke
2523 // constexpr constructors for o and its subobjects even if those objects
2524 // are of non-literal class types.
2525 //
2526 // C++11 missed this detail for aggregates, so classes like this:
2527 // struct foo_t { union { int i; volatile int j; } u; };
2528 // are not (obviously) initializable like so:
2529 // __attribute__((__require_constant_initialization__))
2530 // static const foo_t x = {{0}};
2531 // because "i" is a subobject with non-literal initialization (due to the
2532 // volatile member of the union). See:
2533 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2534 // Therefore, we use the C++1y behavior.
2535 if (This && Info.EvaluatingDecl == This->getLValueBase())
2536 return true;
2537
2538 // Prvalue constant expressions must be of literal types.
2539 if (Info.getLangOpts().CPlusPlus11)
2540 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2541 << E->getType();
2542 else
2543 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2544 return false;
2545}
2546
2548 EvalInfo &Info, SourceLocation DiagLoc,
2549 QualType Type, const APValue &Value,
2550 ConstantExprKind Kind,
2551 const FieldDecl *SubobjectDecl,
2552 CheckedTemporaries &CheckedTemps) {
2553 if (!Value.hasValue()) {
2554 if (SubobjectDecl) {
2555 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2556 << /*(name)*/ 1 << SubobjectDecl;
2557 Info.Note(SubobjectDecl->getLocation(),
2558 diag::note_constexpr_subobject_declared_here);
2559 } else {
2560 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2561 << /*of type*/ 0 << Type;
2562 }
2563 return false;
2564 }
2565
2566 // We allow _Atomic(T) to be initialized from anything that T can be
2567 // initialized from.
2568 if (const AtomicType *AT = Type->getAs<AtomicType>())
2569 Type = AT->getValueType();
2570
2571 // Core issue 1454: For a literal constant expression of array or class type,
2572 // each subobject of its value shall have been initialized by a constant
2573 // expression.
2574 if (Value.isArray()) {
2576 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2577 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2578 Value.getArrayInitializedElt(I), Kind,
2579 SubobjectDecl, CheckedTemps))
2580 return false;
2581 }
2582 if (!Value.hasArrayFiller())
2583 return true;
2584 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2585 Value.getArrayFiller(), Kind, SubobjectDecl,
2586 CheckedTemps);
2587 }
2588 if (Value.isUnion() && Value.getUnionField()) {
2589 return CheckEvaluationResult(
2590 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2591 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2592 }
2593 if (Value.isStruct()) {
2594 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2595 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2596 unsigned BaseIndex = 0;
2597 for (const CXXBaseSpecifier &BS : CD->bases()) {
2598 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2599 if (!BaseValue.hasValue()) {
2600 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2601 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2602 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2603 return false;
2604 }
2605 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2606 Kind, /*SubobjectDecl=*/nullptr,
2607 CheckedTemps))
2608 return false;
2609 ++BaseIndex;
2610 }
2611 }
2612 for (const auto *I : RD->fields()) {
2613 if (I->isUnnamedBitField())
2614 continue;
2615
2616 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2617 Value.getStructField(I->getFieldIndex()), Kind,
2618 I, CheckedTemps))
2619 return false;
2620 }
2621 }
2622
2623 if (Value.isLValue() &&
2624 CERK == CheckEvaluationResultKind::ConstantExpression) {
2625 LValue LVal;
2626 LVal.setFrom(Info.Ctx, Value);
2627 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2628 CheckedTemps);
2629 }
2630
2631 if (Value.isMemberPointer() &&
2632 CERK == CheckEvaluationResultKind::ConstantExpression)
2633 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2634
2635 // Everything else is fine.
2636 return true;
2637}
2638
2639/// Check that this core constant expression value is a valid value for a
2640/// constant expression. If not, report an appropriate diagnostic. Does not
2641/// check that the expression is of literal type.
2642static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2643 QualType Type, const APValue &Value,
2644 ConstantExprKind Kind) {
2645 // Nothing to check for a constant expression of type 'cv void'.
2646 if (Type->isVoidType())
2647 return true;
2648
2649 CheckedTemporaries CheckedTemps;
2650 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2651 Info, DiagLoc, Type, Value, Kind,
2652 /*SubobjectDecl=*/nullptr, CheckedTemps);
2653}
2654
2655/// Check that this evaluated value is fully-initialized and can be loaded by
2656/// an lvalue-to-rvalue conversion.
2657static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2658 QualType Type, const APValue &Value) {
2659 CheckedTemporaries CheckedTemps;
2660 return CheckEvaluationResult(
2661 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2662 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2663}
2664
2665/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2666/// "the allocated storage is deallocated within the evaluation".
2667static bool CheckMemoryLeaks(EvalInfo &Info) {
2668 if (!Info.HeapAllocs.empty()) {
2669 // We can still fold to a constant despite a compile-time memory leak,
2670 // so long as the heap allocation isn't referenced in the result (we check
2671 // that in CheckConstantExpression).
2672 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2673 diag::note_constexpr_memory_leak)
2674 << unsigned(Info.HeapAllocs.size() - 1);
2675 }
2676 return true;
2677}
2678
2679static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2680 // A null base expression indicates a null pointer. These are always
2681 // evaluatable, and they are false unless the offset is zero.
2682 if (!Value.getLValueBase()) {
2683 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2684 Result = !Value.getLValueOffset().isZero();
2685 return true;
2686 }
2687
2688 // We have a non-null base. These are generally known to be true, but if it's
2689 // a weak declaration it can be null at runtime.
2690 Result = true;
2691 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2692 return !Decl || !Decl->isWeak();
2693}
2694
2695static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2696 // TODO: This function should produce notes if it fails.
2697 switch (Val.getKind()) {
2698 case APValue::None:
2700 return false;
2701 case APValue::Int:
2702 Result = Val.getInt().getBoolValue();
2703 return true;
2705 Result = Val.getFixedPoint().getBoolValue();
2706 return true;
2707 case APValue::Float:
2708 Result = !Val.getFloat().isZero();
2709 return true;
2711 Result = Val.getComplexIntReal().getBoolValue() ||
2712 Val.getComplexIntImag().getBoolValue();
2713 return true;
2715 Result = !Val.getComplexFloatReal().isZero() ||
2716 !Val.getComplexFloatImag().isZero();
2717 return true;
2718 case APValue::LValue:
2719 return EvalPointerValueAsBool(Val, Result);
2721 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2722 return false;
2723 }
2724 Result = Val.getMemberPointerDecl();
2725 return true;
2726 case APValue::Vector:
2727 case APValue::Array:
2728 case APValue::Struct:
2729 case APValue::Union:
2731 return false;
2732 }
2733
2734 llvm_unreachable("unknown APValue kind");
2735}
2736
2737static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2738 EvalInfo &Info) {
2739 assert(!E->isValueDependent());
2740 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2741 APValue Val;
2742 if (!Evaluate(Val, Info, E))
2743 return false;
2744 return HandleConversionToBool(Val, Result);
2745}
2746
2747template<typename T>
2748static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2749 const T &SrcValue, QualType DestType) {
2750 Info.CCEDiag(E, diag::note_constexpr_overflow)
2751 << SrcValue << DestType;
2752 return Info.noteUndefinedBehavior();
2753}
2754
2755static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2756 QualType SrcType, const APFloat &Value,
2757 QualType DestType, APSInt &Result) {
2758 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2759 // Determine whether we are converting to unsigned or signed.
2760 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2761
2762 Result = APSInt(DestWidth, !DestSigned);
2763 bool ignored;
2764 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2765 & APFloat::opInvalidOp)
2766 return HandleOverflow(Info, E, Value, DestType);
2767 return true;
2768}
2769
2770/// Get rounding mode to use in evaluation of the specified expression.
2771///
2772/// If rounding mode is unknown at compile time, still try to evaluate the
2773/// expression. If the result is exact, it does not depend on rounding mode.
2774/// So return "tonearest" mode instead of "dynamic".
2775static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2776 llvm::RoundingMode RM =
2777 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2778 if (RM == llvm::RoundingMode::Dynamic)
2779 RM = llvm::RoundingMode::NearestTiesToEven;
2780 return RM;
2781}
2782
2783/// Check if the given evaluation result is allowed for constant evaluation.
2784static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2785 APFloat::opStatus St) {
2786 // In a constant context, assume that any dynamic rounding mode or FP
2787 // exception state matches the default floating-point environment.
2788 if (Info.InConstantContext)
2789 return true;
2790
2791 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2792 if ((St & APFloat::opInexact) &&
2793 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2794 // Inexact result means that it depends on rounding mode. If the requested
2795 // mode is dynamic, the evaluation cannot be made in compile time.
2796 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2797 return false;
2798 }
2799
2800 if ((St != APFloat::opOK) &&
2801 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2802 FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2803 FPO.getAllowFEnvAccess())) {
2804 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2805 return false;
2806 }
2807
2808 if ((St & APFloat::opStatus::opInvalidOp) &&
2809 FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2810 // There is no usefully definable result.
2811 Info.FFDiag(E);
2812 return false;
2813 }
2814
2815 // FIXME: if:
2816 // - evaluation triggered other FP exception, and
2817 // - exception mode is not "ignore", and
2818 // - the expression being evaluated is not a part of global variable
2819 // initializer,
2820 // the evaluation probably need to be rejected.
2821 return true;
2822}
2823
2824static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2825 QualType SrcType, QualType DestType,
2826 APFloat &Result) {
2827 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2828 isa<ConvertVectorExpr>(E)) &&
2829 "HandleFloatToFloatCast has been checked with only CastExpr, "
2830 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2831 "the new expression or address the root cause of this usage.");
2832 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2833 APFloat::opStatus St;
2834 APFloat Value = Result;
2835 bool ignored;
2836 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2837 return checkFloatingPointResult(Info, E, St);
2838}
2839
2840static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2841 QualType DestType, QualType SrcType,
2842 const APSInt &Value) {
2843 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2844 // Figure out if this is a truncate, extend or noop cast.
2845 // If the input is signed, do a sign extend, noop, or truncate.
2846 APSInt Result = Value.extOrTrunc(DestWidth);
2847 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2848 if (DestType->isBooleanType())
2849 Result = Value.getBoolValue();
2850 return Result;
2851}
2852
2853static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2854 const FPOptions FPO,
2855 QualType SrcType, const APSInt &Value,
2856 QualType DestType, APFloat &Result) {
2857 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2858 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2859 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2860 return checkFloatingPointResult(Info, E, St);
2861}
2862
2863static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2864 APValue &Value, const FieldDecl *FD) {
2865 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2866
2867 if (!Value.isInt()) {
2868 // Trying to store a pointer-cast-to-integer into a bitfield.
2869 // FIXME: In this case, we should provide the diagnostic for casting
2870 // a pointer to an integer.
2871 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2872 Info.FFDiag(E);
2873 return false;
2874 }
2875
2876 APSInt &Int = Value.getInt();
2877 unsigned OldBitWidth = Int.getBitWidth();
2878 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2879 if (NewBitWidth < OldBitWidth)
2880 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2881 return true;
2882}
2883
2884/// Perform the given integer operation, which is known to need at most BitWidth
2885/// bits, and check for overflow in the original type (if that type was not an
2886/// unsigned type).
2887template<typename Operation>
2888static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2889 const APSInt &LHS, const APSInt &RHS,
2890 unsigned BitWidth, Operation Op,
2891 APSInt &Result) {
2892 if (LHS.isUnsigned()) {
2893 Result = Op(LHS, RHS);
2894 return true;
2895 }
2896
2897 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2898 Result = Value.trunc(LHS.getBitWidth());
2899 if (Result.extend(BitWidth) != Value) {
2900 if (Info.checkingForUndefinedBehavior())
2901 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2902 diag::warn_integer_constant_overflow)
2903 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2904 /*UpperCase=*/true, /*InsertSeparators=*/true)
2905 << E->getType() << E->getSourceRange();
2906 return HandleOverflow(Info, E, Value, E->getType());
2907 }
2908 return true;
2909}
2910
2911/// Perform the given binary integer operation.
2912static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2913 const APSInt &LHS, BinaryOperatorKind Opcode,
2914 APSInt RHS, APSInt &Result) {
2915 bool HandleOverflowResult = true;
2916 switch (Opcode) {
2917 default:
2918 Info.FFDiag(E);
2919 return false;
2920 case BO_Mul:
2921 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2922 std::multiplies<APSInt>(), Result);
2923 case BO_Add:
2924 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2925 std::plus<APSInt>(), Result);
2926 case BO_Sub:
2927 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2928 std::minus<APSInt>(), Result);
2929 case BO_And: Result = LHS & RHS; return true;
2930 case BO_Xor: Result = LHS ^ RHS; return true;
2931 case BO_Or: Result = LHS | RHS; return true;
2932 case BO_Div:
2933 case BO_Rem:
2934 if (RHS == 0) {
2935 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2936 << E->getRHS()->getSourceRange();
2937 return false;
2938 }
2939 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2940 // this operation and gives the two's complement result.
2941 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2942 LHS.isMinSignedValue())
2943 HandleOverflowResult = HandleOverflow(
2944 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2945 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2946 return HandleOverflowResult;
2947 case BO_Shl: {
2948 if (Info.getLangOpts().OpenCL)
2949 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2950 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2951 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2952 RHS.isUnsigned());
2953 else if (RHS.isSigned() && RHS.isNegative()) {
2954 // During constant-folding, a negative shift is an opposite shift. Such
2955 // a shift is not a constant expression.
2956 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2957 if (!Info.noteUndefinedBehavior())
2958 return false;
2959 RHS = -RHS;
2960 goto shift_right;
2961 }
2962 shift_left:
2963 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2964 // the shifted type.
2965 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2966 if (SA != RHS) {
2967 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2968 << RHS << E->getType() << LHS.getBitWidth();
2969 if (!Info.noteUndefinedBehavior())
2970 return false;
2971 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2972 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2973 // operand, and must not overflow the corresponding unsigned type.
2974 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2975 // E1 x 2^E2 module 2^N.
2976 if (LHS.isNegative()) {
2977 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2978 if (!Info.noteUndefinedBehavior())
2979 return false;
2980 } else if (LHS.countl_zero() < SA) {
2981 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2982 if (!Info.noteUndefinedBehavior())
2983 return false;
2984 }
2985 }
2986 Result = LHS << SA;
2987 return true;
2988 }
2989 case BO_Shr: {
2990 if (Info.getLangOpts().OpenCL)
2991 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2992 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2993 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2994 RHS.isUnsigned());
2995 else if (RHS.isSigned() && RHS.isNegative()) {
2996 // During constant-folding, a negative shift is an opposite shift. Such a
2997 // shift is not a constant expression.
2998 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2999 if (!Info.noteUndefinedBehavior())
3000 return false;
3001 RHS = -RHS;
3002 goto shift_left;
3003 }
3004 shift_right:
3005 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
3006 // shifted type.
3007 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3008 if (SA != RHS) {
3009 Info.CCEDiag(E, diag::note_constexpr_large_shift)
3010 << RHS << E->getType() << LHS.getBitWidth();
3011 if (!Info.noteUndefinedBehavior())
3012 return false;
3013 }
3014
3015 Result = LHS >> SA;
3016 return true;
3017 }
3018
3019 case BO_LT: Result = LHS < RHS; return true;
3020 case BO_GT: Result = LHS > RHS; return true;
3021 case BO_LE: Result = LHS <= RHS; return true;
3022 case BO_GE: Result = LHS >= RHS; return true;
3023 case BO_EQ: Result = LHS == RHS; return true;
3024 case BO_NE: Result = LHS != RHS; return true;
3025 case BO_Cmp:
3026 llvm_unreachable("BO_Cmp should be handled elsewhere");
3027 }
3028}
3029
3030/// Perform the given binary floating-point operation, in-place, on LHS.
3031static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
3032 APFloat &LHS, BinaryOperatorKind Opcode,
3033 const APFloat &RHS) {
3034 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
3035 APFloat::opStatus St;
3036 switch (Opcode) {
3037 default:
3038 Info.FFDiag(E);
3039 return false;
3040 case BO_Mul:
3041 St = LHS.multiply(RHS, RM);
3042 break;
3043 case BO_Add:
3044 St = LHS.add(RHS, RM);
3045 break;
3046 case BO_Sub:
3047 St = LHS.subtract(RHS, RM);
3048 break;
3049 case BO_Div:
3050 // [expr.mul]p4:
3051 // If the second operand of / or % is zero the behavior is undefined.
3052 if (RHS.isZero())
3053 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
3054 St = LHS.divide(RHS, RM);
3055 break;
3056 }
3057
3058 // [expr.pre]p4:
3059 // If during the evaluation of an expression, the result is not
3060 // mathematically defined [...], the behavior is undefined.
3061 // FIXME: C++ rules require us to not conform to IEEE 754 here.
3062 if (LHS.isNaN()) {
3063 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
3064 return Info.noteUndefinedBehavior();
3065 }
3066
3067 return checkFloatingPointResult(Info, E, St);
3068}
3069
3070static bool handleLogicalOpForVector(const APInt &LHSValue,
3071 BinaryOperatorKind Opcode,
3072 const APInt &RHSValue, APInt &Result) {
3073 bool LHS = (LHSValue != 0);
3074 bool RHS = (RHSValue != 0);
3075
3076 if (Opcode == BO_LAnd)
3077 Result = LHS && RHS;
3078 else
3079 Result = LHS || RHS;
3080 return true;
3081}
3082static bool handleLogicalOpForVector(const APFloat &LHSValue,
3083 BinaryOperatorKind Opcode,
3084 const APFloat &RHSValue, APInt &Result) {
3085 bool LHS = !LHSValue.isZero();
3086 bool RHS = !RHSValue.isZero();
3087
3088 if (Opcode == BO_LAnd)
3089 Result = LHS && RHS;
3090 else
3091 Result = LHS || RHS;
3092 return true;
3093}
3094
3095static bool handleLogicalOpForVector(const APValue &LHSValue,
3096 BinaryOperatorKind Opcode,
3097 const APValue &RHSValue, APInt &Result) {
3098 // The result is always an int type, however operands match the first.
3099 if (LHSValue.getKind() == APValue::Int)
3100 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3101 RHSValue.getInt(), Result);
3102 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3103 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3104 RHSValue.getFloat(), Result);
3105}
3106
3107template <typename APTy>
3108static bool
3110 const APTy &RHSValue, APInt &Result) {
3111 switch (Opcode) {
3112 default:
3113 llvm_unreachable("unsupported binary operator");
3114 case BO_EQ:
3115 Result = (LHSValue == RHSValue);
3116 break;
3117 case BO_NE:
3118 Result = (LHSValue != RHSValue);
3119 break;
3120 case BO_LT:
3121 Result = (LHSValue < RHSValue);
3122 break;
3123 case BO_GT:
3124 Result = (LHSValue > RHSValue);
3125 break;
3126 case BO_LE:
3127 Result = (LHSValue <= RHSValue);
3128 break;
3129 case BO_GE:
3130 Result = (LHSValue >= RHSValue);
3131 break;
3132 }
3133
3134 // The boolean operations on these vector types use an instruction that
3135 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3136 // to -1 to make sure that we produce the correct value.
3137 Result.negate();
3138
3139 return true;
3140}
3141
3142static bool handleCompareOpForVector(const APValue &LHSValue,
3143 BinaryOperatorKind Opcode,
3144 const APValue &RHSValue, APInt &Result) {
3145 // The result is always an int type, however operands match the first.
3146 if (LHSValue.getKind() == APValue::Int)
3147 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3148 RHSValue.getInt(), Result);
3149 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3150 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3151 RHSValue.getFloat(), Result);
3152}
3153
3154// Perform binary operations for vector types, in place on the LHS.
3155static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3156 BinaryOperatorKind Opcode,
3157 APValue &LHSValue,
3158 const APValue &RHSValue) {
3159 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3160 "Operation not supported on vector types");
3161
3162 const auto *VT = E->getType()->castAs<VectorType>();
3163 unsigned NumElements = VT->getNumElements();
3164 QualType EltTy = VT->getElementType();
3165
3166 // In the cases (typically C as I've observed) where we aren't evaluating
3167 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3168 // just give up.
3169 if (!LHSValue.isVector()) {
3170 assert(LHSValue.isLValue() &&
3171 "A vector result that isn't a vector OR uncalculated LValue");
3172 Info.FFDiag(E);
3173 return false;
3174 }
3175
3176 assert(LHSValue.getVectorLength() == NumElements &&
3177 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3178
3179 SmallVector<APValue, 4> ResultElements;
3180
3181 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3182 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3183 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3184
3185 if (EltTy->isIntegerType()) {
3186 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3187 EltTy->isUnsignedIntegerType()};
3188 bool Success = true;
3189
3190 if (BinaryOperator::isLogicalOp(Opcode))
3191 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3192 else if (BinaryOperator::isComparisonOp(Opcode))
3193 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3194 else
3195 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3196 RHSElt.getInt(), EltResult);
3197
3198 if (!Success) {
3199 Info.FFDiag(E);
3200 return false;
3201 }
3202 ResultElements.emplace_back(EltResult);
3203
3204 } else if (EltTy->isFloatingType()) {
3205 assert(LHSElt.getKind() == APValue::Float &&
3206 RHSElt.getKind() == APValue::Float &&
3207 "Mismatched LHS/RHS/Result Type");
3208 APFloat LHSFloat = LHSElt.getFloat();
3209
3210 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3211 RHSElt.getFloat())) {
3212 Info.FFDiag(E);
3213 return false;
3214 }
3215
3216 ResultElements.emplace_back(LHSFloat);
3217 }
3218 }
3219
3220 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3221 return true;
3222}
3223
3224/// Cast an lvalue referring to a base subobject to a derived class, by
3225/// truncating the lvalue's path to the given length.
3226static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3227 const RecordDecl *TruncatedType,
3228 unsigned TruncatedElements) {
3229 SubobjectDesignator &D = Result.Designator;
3230
3231 // Check we actually point to a derived class object.
3232 if (TruncatedElements == D.Entries.size())
3233 return true;
3234 assert(TruncatedElements >= D.MostDerivedPathLength &&
3235 "not casting to a derived class");
3236 if (!Result.checkSubobject(Info, E, CSK_Derived))
3237 return false;
3238
3239 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3240 const RecordDecl *RD = TruncatedType;
3241 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3242 if (RD->isInvalidDecl()) return false;
3243 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3244 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3245 if (isVirtualBaseClass(D.Entries[I]))
3246 Result.Offset -= Layout.getVBaseClassOffset(Base);
3247 else
3248 Result.Offset -= Layout.getBaseClassOffset(Base);
3249 RD = Base;
3250 }
3251 D.Entries.resize(TruncatedElements);
3252 return true;
3253}
3254
3255static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3256 const CXXRecordDecl *Derived,
3257 const CXXRecordDecl *Base,
3258 const ASTRecordLayout *RL = nullptr) {
3259 if (!RL) {
3260 if (Derived->isInvalidDecl()) return false;
3261 RL = &Info.Ctx.getASTRecordLayout(Derived);
3262 }
3263
3264 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3265 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3266 return true;
3267}
3268
3269static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3270 const CXXRecordDecl *DerivedDecl,
3271 const CXXBaseSpecifier *Base) {
3272 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3273
3274 if (!Base->isVirtual())
3275 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3276
3277 SubobjectDesignator &D = Obj.Designator;
3278 if (D.Invalid)
3279 return false;
3280
3281 // Extract most-derived object and corresponding type.
3282 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3283 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3284 return false;
3285
3286 // Find the virtual base class.
3287 if (DerivedDecl->isInvalidDecl()) return false;
3288 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3289 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3290 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3291 return true;
3292}
3293
3294static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3295 QualType Type, LValue &Result) {
3296 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3297 PathE = E->path_end();
3298 PathI != PathE; ++PathI) {
3299 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3300 *PathI))
3301 return false;
3302 Type = (*PathI)->getType();
3303 }
3304 return true;
3305}
3306
3307/// Cast an lvalue referring to a derived class to a known base subobject.
3308static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3309 const CXXRecordDecl *DerivedRD,
3310 const CXXRecordDecl *BaseRD) {
3311 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3312 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3313 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3314 llvm_unreachable("Class must be derived from the passed in base class!");
3315
3316 for (CXXBasePathElement &Elem : Paths.front())
3317 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3318 return false;
3319 return true;
3320}
3321
3322/// Update LVal to refer to the given field, which must be a member of the type
3323/// currently described by LVal.
3324static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3325 const FieldDecl *FD,
3326 const ASTRecordLayout *RL = nullptr) {
3327 if (!RL) {
3328 if (FD->getParent()->isInvalidDecl()) return false;
3329 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3330 }
3331
3332 unsigned I = FD->getFieldIndex();
3333 LVal.addDecl(Info, E, FD);
3334 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3335 return true;
3336}
3337
3338/// Update LVal to refer to the given indirect field.
3339static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3340 LValue &LVal,
3341 const IndirectFieldDecl *IFD) {
3342 for (const auto *C : IFD->chain())
3343 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3344 return false;
3345 return true;
3346}
3347
3348enum class SizeOfType {
3349 SizeOf,
3350 DataSizeOf,
3351};
3352
3353/// Get the size of the given type in char units.
3354static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3355 CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) {
3356 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3357 // extension.
3358 if (Type->isVoidType() || Type->isFunctionType()) {
3359 Size = CharUnits::One();
3360 return true;
3361 }
3362
3363 if (Type->isDependentType()) {
3364 Info.FFDiag(Loc);
3365 return false;
3366 }
3367
3368 if (!Type->isConstantSizeType()) {
3369 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3370 // FIXME: Better diagnostic.
3371 Info.FFDiag(Loc);
3372 return false;
3373 }
3374
3375 if (SOT == SizeOfType::SizeOf)
3376 Size = Info.Ctx.getTypeSizeInChars(Type);
3377 else
3378 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3379 return true;
3380}
3381
3382/// Update a pointer value to model pointer arithmetic.
3383/// \param Info - Information about the ongoing evaluation.
3384/// \param E - The expression being evaluated, for diagnostic purposes.
3385/// \param LVal - The pointer value to be updated.
3386/// \param EltTy - The pointee type represented by LVal.
3387/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3388static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3389 LValue &LVal, QualType EltTy,
3390 APSInt Adjustment) {
3391 CharUnits SizeOfPointee;
3392 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3393 return false;
3394
3395 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3396 return true;
3397}
3398
3399static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3400 LValue &LVal, QualType EltTy,
3401 int64_t Adjustment) {
3402 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3403 APSInt::get(Adjustment));
3404}
3405
3406/// Update an lvalue to refer to a component of a complex number.
3407/// \param Info - Information about the ongoing evaluation.
3408/// \param LVal - The lvalue to be updated.
3409/// \param EltTy - The complex number's component type.
3410/// \param Imag - False for the real component, true for the imaginary.
3411static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3412 LValue &LVal, QualType EltTy,
3413 bool Imag) {
3414 if (Imag) {
3415 CharUnits SizeOfComponent;
3416 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3417 return false;
3418 LVal.Offset += SizeOfComponent;
3419 }
3420 LVal.addComplex(Info, E, EltTy, Imag);
3421 return true;
3422}
3423
3424static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3425 LValue &LVal, QualType EltTy,
3426 uint64_t Size, uint64_t Idx) {
3427 if (Idx) {
3428 CharUnits SizeOfElement;
3429 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3430 return false;
3431 LVal.Offset += SizeOfElement * Idx;
3432 }
3433 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3434 return true;
3435}
3436
3437/// Try to evaluate the initializer for a variable declaration.
3438///
3439/// \param Info Information about the ongoing evaluation.
3440/// \param E An expression to be used when printing diagnostics.
3441/// \param VD The variable whose initializer should be obtained.
3442/// \param Version The version of the variable within the frame.
3443/// \param Frame The frame in which the variable was created. Must be null
3444/// if this variable is not local to the evaluation.
3445/// \param Result Filled in with a pointer to the value of the variable.
3446static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3447 const VarDecl *VD, CallStackFrame *Frame,
3448 unsigned Version, APValue *&Result) {
3449 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3450
3451 // If this is a local variable, dig out its value.
3452 if (Frame) {
3453 Result = Frame->getTemporary(VD, Version);
3454 if (Result)
3455 return true;
3456
3457 if (!isa<ParmVarDecl>(VD)) {
3458 // Assume variables referenced within a lambda's call operator that were
3459 // not declared within the call operator are captures and during checking
3460 // of a potential constant expression, assume they are unknown constant
3461 // expressions.
3462 assert(isLambdaCallOperator(Frame->Callee) &&
3463 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3464 "missing value for local variable");
3465 if (Info.checkingPotentialConstantExpression())
3466 return false;
3467 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3468 // still reachable at all?
3469 Info.FFDiag(E->getBeginLoc(),
3470 diag::note_unimplemented_constexpr_lambda_feature_ast)
3471 << "captures not currently allowed";
3472 return false;
3473 }
3474 }
3475
3476 // If we're currently evaluating the initializer of this declaration, use that
3477 // in-flight value.
3478 if (Info.EvaluatingDecl == Base) {
3479 Result = Info.EvaluatingDeclValue;
3480 return true;
3481 }
3482
3483 if (isa<ParmVarDecl>(VD)) {
3484 // Assume parameters of a potential constant expression are usable in
3485 // constant expressions.
3486 if (!Info.checkingPotentialConstantExpression() ||
3487 !Info.CurrentCall->Callee ||
3488 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3489 if (Info.getLangOpts().CPlusPlus11) {
3490 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3491 << VD;
3492 NoteLValueLocation(Info, Base);
3493 } else {
3494 Info.FFDiag(E);
3495 }
3496 }
3497 return false;
3498 }
3499
3500 if (E->isValueDependent())
3501 return false;
3502
3503 // Dig out the initializer, and use the declaration which it's attached to.
3504 // FIXME: We should eventually check whether the variable has a reachable
3505 // initializing declaration.
3506 const Expr *Init = VD->getAnyInitializer(VD);
3507 if (!Init) {
3508 // Don't diagnose during potential constant expression checking; an
3509 // initializer might be added later.
3510 if (!Info.checkingPotentialConstantExpression()) {
3511 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3512 << VD;
3513 NoteLValueLocation(Info, Base);
3514 }
3515 return false;
3516 }
3517
3518 if (Init->isValueDependent()) {
3519 // The DeclRefExpr is not value-dependent, but the variable it refers to
3520 // has a value-dependent initializer. This should only happen in
3521 // constant-folding cases, where the variable is not actually of a suitable
3522 // type for use in a constant expression (otherwise the DeclRefExpr would
3523 // have been value-dependent too), so diagnose that.
3524 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3525 if (!Info.checkingPotentialConstantExpression()) {
3526 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3527 ? diag::note_constexpr_ltor_non_constexpr
3528 : diag::note_constexpr_ltor_non_integral, 1)
3529 << VD << VD->getType();
3530 NoteLValueLocation(Info, Base);
3531 }
3532 return false;
3533 }
3534
3535 // Check that we can fold the initializer. In C++, we will have already done
3536 // this in the cases where it matters for conformance.
3537 if (!VD->evaluateValue()) {
3538 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3539 NoteLValueLocation(Info, Base);
3540 return false;
3541 }
3542
3543 // Check that the variable is actually usable in constant expressions. For a
3544 // const integral variable or a reference, we might have a non-constant
3545 // initializer that we can nonetheless evaluate the initializer for. Such
3546 // variables are not usable in constant expressions. In C++98, the
3547 // initializer also syntactically needs to be an ICE.
3548 //
3549 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3550 // expressions here; doing so would regress diagnostics for things like
3551 // reading from a volatile constexpr variable.
3552 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3553 VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3554 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3555 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3556 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3557 NoteLValueLocation(Info, Base);
3558 }
3559
3560 // Never use the initializer of a weak variable, not even for constant
3561 // folding. We can't be sure that this is the definition that will be used.
3562 if (VD->isWeak()) {
3563 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3564 NoteLValueLocation(Info, Base);
3565 return false;
3566 }
3567
3568 Result = VD->getEvaluatedValue();
3569 return true;
3570}
3571
3572/// Get the base index of the given base class within an APValue representing
3573/// the given derived class.
3574static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3575 const CXXRecordDecl *Base) {
3576 Base = Base->getCanonicalDecl();
3577 unsigned Index = 0;
3579 E = Derived->bases_end(); I != E; ++I, ++Index) {
3580 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3581 return Index;
3582 }
3583
3584 llvm_unreachable("base class missing from derived class's bases list");
3585}
3586
3587/// Extract the value of a character from a string literal.
3588static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3589 uint64_t Index) {
3590 assert(!isa<SourceLocExpr>(Lit) &&
3591 "SourceLocExpr should have already been converted to a StringLiteral");
3592
3593 // FIXME: Support MakeStringConstant
3594 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3595 std::string Str;
3596 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3597 assert(Index <= Str.size() && "Index too large");
3598 return APSInt::getUnsigned(Str.c_str()[Index]);
3599 }
3600
3601 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3602 Lit = PE->getFunctionName();
3603 const StringLiteral *S = cast<StringLiteral>(Lit);
3604 const ConstantArrayType *CAT =
3605 Info.Ctx.getAsConstantArrayType(S->getType());
3606 assert(CAT && "string literal isn't an array");
3607 QualType CharType = CAT->getElementType();
3608 assert(CharType->isIntegerType() && "unexpected character type");
3609 APSInt Value(Info.Ctx.getTypeSize(CharType),
3610 CharType->isUnsignedIntegerType());
3611 if (Index < S->getLength())
3612 Value = S->getCodeUnit(Index);
3613 return Value;
3614}
3615
3616// Expand a string literal into an array of characters.
3617//
3618// FIXME: This is inefficient; we should probably introduce something similar
3619// to the LLVM ConstantDataArray to make this cheaper.
3620static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3621 APValue &Result,
3622 QualType AllocType = QualType()) {
3623 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3624 AllocType.isNull() ? S->getType() : AllocType);
3625 assert(CAT && "string literal isn't an array");
3626 QualType CharType = CAT->getElementType();
3627 assert(CharType->isIntegerType() && "unexpected character type");
3628
3629 unsigned Elts = CAT->getZExtSize();
3630 Result = APValue(APValue::UninitArray(),
3631 std::min(S->getLength(), Elts), Elts);
3632 APSInt Value(Info.Ctx.getTypeSize(CharType),
3633 CharType->isUnsignedIntegerType());
3634 if (Result.hasArrayFiller())
3635 Result.getArrayFiller() = APValue(Value);
3636 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3637 Value = S->getCodeUnit(I);
3638 Result.getArrayInitializedElt(I) = APValue(Value);
3639 }
3640}
3641
3642// Expand an array so that it has more than Index filled elements.
3643static void expandArray(APValue &Array, unsigned Index) {
3644 unsigned Size = Array.getArraySize();
3645 assert(Index < Size);
3646
3647 // Always at least double the number of elements for which we store a value.
3648 unsigned OldElts = Array.getArrayInitializedElts();
3649 unsigned NewElts = std::max(Index+1, OldElts * 2);
3650 NewElts = std::min(Size, std::max(NewElts, 8u));
3651
3652 // Copy the data across.
3653 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3654 for (unsigned I = 0; I != OldElts; ++I)
3655 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3656 for (unsigned I = OldElts; I != NewElts; ++I)
3657 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3658 if (NewValue.hasArrayFiller())
3659 NewValue.getArrayFiller() = Array.getArrayFiller();
3660 Array.swap(NewValue);
3661}
3662
3663/// Determine whether a type would actually be read by an lvalue-to-rvalue
3664/// conversion. If it's of class type, we may assume that the copy operation
3665/// is trivial. Note that this is never true for a union type with fields
3666/// (because the copy always "reads" the active member) and always true for
3667/// a non-class type.
3668static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3671 return !RD || isReadByLvalueToRvalueConversion(RD);
3672}
3674 // FIXME: A trivial copy of a union copies the object representation, even if
3675 // the union is empty.
3676 if (RD->isUnion())
3677 return !RD->field_empty();
3678 if (RD->isEmpty())
3679 return false;
3680
3681 for (auto *Field : RD->fields())
3682 if (!Field->isUnnamedBitField() &&
3683 isReadByLvalueToRvalueConversion(Field->getType()))
3684 return true;
3685
3686 for (auto &BaseSpec : RD->bases())
3687 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3688 return true;
3689
3690 return false;
3691}
3692
3693/// Diagnose an attempt to read from any unreadable field within the specified
3694/// type, which might be a class type.
3695static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3696 QualType T) {
3698 if (!RD)
3699 return false;
3700
3701 if (!RD->hasMutableFields())
3702 return false;
3703
3704 for (auto *Field : RD->fields()) {
3705 // If we're actually going to read this field in some way, then it can't
3706 // be mutable. If we're in a union, then assigning to a mutable field
3707 // (even an empty one) can change the active member, so that's not OK.
3708 // FIXME: Add core issue number for the union case.
3709 if (Field->isMutable() &&
3710 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3711 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3712 Info.Note(Field->getLocation(), diag::note_declared_at);
3713 return true;
3714 }
3715
3716 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3717 return true;
3718 }
3719
3720 for (auto &BaseSpec : RD->bases())
3721 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3722 return true;
3723
3724 // All mutable fields were empty, and thus not actually read.
3725 return false;
3726}
3727
3728static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3730 bool MutableSubobject = false) {
3731 // A temporary or transient heap allocation we created.
3732 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3733 return true;
3734
3735 switch (Info.IsEvaluatingDecl) {
3736 case EvalInfo::EvaluatingDeclKind::None:
3737 return false;
3738
3739 case EvalInfo::EvaluatingDeclKind::Ctor:
3740 // The variable whose initializer we're evaluating.
3741 if (Info.EvaluatingDecl == Base)
3742 return true;
3743
3744 // A temporary lifetime-extended by the variable whose initializer we're
3745 // evaluating.
3746 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3747 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3748 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3749 return false;
3750
3751 case EvalInfo::EvaluatingDeclKind::Dtor:
3752 // C++2a [expr.const]p6:
3753 // [during constant destruction] the lifetime of a and its non-mutable
3754 // subobjects (but not its mutable subobjects) [are] considered to start
3755 // within e.
3756 if (MutableSubobject || Base != Info.EvaluatingDecl)
3757 return false;
3758 // FIXME: We can meaningfully extend this to cover non-const objects, but
3759 // we will need special handling: we should be able to access only
3760 // subobjects of such objects that are themselves declared const.
3761 QualType T = getType(Base);
3762 return T.isConstQualified() || T->isReferenceType();
3763 }
3764
3765 llvm_unreachable("unknown evaluating decl kind");
3766}
3767
3768static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3769 SourceLocation CallLoc = {}) {
3770 return Info.CheckArraySize(
3771 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3772 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3773 /*Diag=*/true);
3774}
3775
3776namespace {
3777/// A handle to a complete object (an object that is not a subobject of
3778/// another object).
3779struct CompleteObject {
3780 /// The identity of the object.
3782 /// The value of the complete object.
3783 APValue *Value;
3784 /// The type of the complete object.
3785 QualType Type;
3786
3787 CompleteObject() : Value(nullptr) {}
3789 : Base(Base), Value(Value), Type(Type) {}
3790
3791 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3792 // If this isn't a "real" access (eg, if it's just accessing the type
3793 // info), allow it. We assume the type doesn't change dynamically for
3794 // subobjects of constexpr objects (even though we'd hit UB here if it
3795 // did). FIXME: Is this right?
3796 if (!isAnyAccess(AK))
3797 return true;
3798
3799 // In C++14 onwards, it is permitted to read a mutable member whose
3800 // lifetime began within the evaluation.
3801 // FIXME: Should we also allow this in C++11?
3802 if (!Info.getLangOpts().CPlusPlus14 &&
3803 AK != AccessKinds::AK_IsWithinLifetime)
3804 return false;
3805 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3806 }
3807
3808 explicit operator bool() const { return !Type.isNull(); }
3809};
3810} // end anonymous namespace
3811
3812static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3813 bool IsMutable = false) {
3814 // C++ [basic.type.qualifier]p1:
3815 // - A const object is an object of type const T or a non-mutable subobject
3816 // of a const object.
3817 if (ObjType.isConstQualified() && !IsMutable)
3818 SubobjType.addConst();
3819 // - A volatile object is an object of type const T or a subobject of a
3820 // volatile object.
3821 if (ObjType.isVolatileQualified())
3822 SubobjType.addVolatile();
3823 return SubobjType;
3824}
3825
3826/// Find the designated sub-object of an rvalue.
3827template <typename SubobjectHandler>
3828static typename SubobjectHandler::result_type
3829findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3830 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3831 if (Sub.Invalid)
3832 // A diagnostic will have already been produced.
3833 return handler.failed();
3834 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3835 if (Info.getLangOpts().CPlusPlus11)
3836 Info.FFDiag(E, Sub.isOnePastTheEnd()
3837 ? diag::note_constexpr_access_past_end
3838 : diag::note_constexpr_access_unsized_array)
3839 << handler.AccessKind;
3840 else
3841 Info.FFDiag(E);
3842 return handler.failed();
3843 }
3844
3845 APValue *O = Obj.Value;
3846 QualType ObjType = Obj.Type;
3847 const FieldDecl *LastField = nullptr;
3848 const FieldDecl *VolatileField = nullptr;
3849
3850 // Walk the designator's path to find the subobject.
3851 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3852 // Reading an indeterminate value is undefined, but assigning over one is OK.
3853 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3854 (O->isIndeterminate() &&
3855 !isValidIndeterminateAccess(handler.AccessKind))) {
3856 // Object has ended lifetime.
3857 // If I is non-zero, some subobject (member or array element) of a
3858 // complete object has ended its lifetime, so this is valid for
3859 // IsWithinLifetime, resulting in false.
3860 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
3861 return false;
3862 if (!Info.checkingPotentialConstantExpression())
3863 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3864 << handler.AccessKind << O->isIndeterminate()
3865 << E->getSourceRange();
3866 return handler.failed();
3867 }
3868
3869 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3870 // const and volatile semantics are not applied on an object under
3871 // {con,de}struction.
3872 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3873 ObjType->isRecordType() &&
3874 Info.isEvaluatingCtorDtor(
3875 Obj.Base,
3876 llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3877 ConstructionPhase::None) {
3878 ObjType = Info.Ctx.getCanonicalType(ObjType);
3879 ObjType.removeLocalConst();
3880 ObjType.removeLocalVolatile();
3881 }
3882
3883 // If this is our last pass, check that the final object type is OK.
3884 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3885 // Accesses to volatile objects are prohibited.
3886 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3887 if (Info.getLangOpts().CPlusPlus) {
3888 int DiagKind;
3890 const NamedDecl *Decl = nullptr;
3891 if (VolatileField) {
3892 DiagKind = 2;
3893 Loc = VolatileField->getLocation();
3894 Decl = VolatileField;
3895 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3896 DiagKind = 1;
3897 Loc = VD->getLocation();
3898 Decl = VD;
3899 } else {
3900 DiagKind = 0;
3901 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3902 Loc = E->getExprLoc();
3903 }
3904 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3905 << handler.AccessKind << DiagKind << Decl;
3906 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3907 } else {
3908 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3909 }
3910 return handler.failed();
3911 }
3912
3913 // If we are reading an object of class type, there may still be more
3914 // things we need to check: if there are any mutable subobjects, we
3915 // cannot perform this read. (This only happens when performing a trivial
3916 // copy or assignment.)
3917 if (ObjType->isRecordType() &&
3918 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3919 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3920 return handler.failed();
3921 }
3922
3923 if (I == N) {
3924 if (!handler.found(*O, ObjType))
3925 return false;
3926
3927 // If we modified a bit-field, truncate it to the right width.
3928 if (isModification(handler.AccessKind) &&
3929 LastField && LastField->isBitField() &&
3930 !truncateBitfieldValue(Info, E, *O, LastField))
3931 return false;
3932
3933 return true;
3934 }
3935
3936 LastField = nullptr;
3937 if (ObjType->isArrayType()) {
3938 // Next subobject is an array element.
3939 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3940 assert(CAT && "vla in literal type?");
3941 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3942 if (CAT->getSize().ule(Index)) {
3943 // Note, it should not be possible to form a pointer with a valid
3944 // designator which points more than one past the end of the array.
3945 if (Info.getLangOpts().CPlusPlus11)
3946 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3947 << handler.AccessKind;
3948 else
3949 Info.FFDiag(E);
3950 return handler.failed();
3951 }
3952
3953 ObjType = CAT->getElementType();
3954
3955 if (O->getArrayInitializedElts() > Index)
3956 O = &O->getArrayInitializedElt(Index);
3957 else if (!isRead(handler.AccessKind)) {
3958 if (!CheckArraySize(Info, CAT, E->getExprLoc()))
3959 return handler.failed();
3960
3961 expandArray(*O, Index);
3962 O = &O->getArrayInitializedElt(Index);
3963 } else
3964 O = &O->getArrayFiller();
3965 } else if (ObjType->isAnyComplexType()) {
3966 // Next subobject is a complex number.
3967 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3968 if (Index > 1) {
3969 if (Info.getLangOpts().CPlusPlus11)
3970 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3971 << handler.AccessKind;
3972 else
3973 Info.FFDiag(E);
3974 return handler.failed();
3975 }
3976
3977 ObjType = getSubobjectType(
3978 ObjType, ObjType->castAs<ComplexType>()->getElementType());
3979
3980 assert(I == N - 1 && "extracting subobject of scalar?");
3981 if (O->isComplexInt()) {
3982 return handler.found(Index ? O->getComplexIntImag()
3983 : O->getComplexIntReal(), ObjType);
3984 } else {
3985 assert(O->isComplexFloat());
3986 return handler.found(Index ? O->getComplexFloatImag()
3987 : O->getComplexFloatReal(), ObjType);
3988 }
3989 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
3990 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3991 unsigned NumElements = VT->getNumElements();
3992 if (Index == NumElements) {
3993 if (Info.getLangOpts().CPlusPlus11)
3994 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3995 << handler.AccessKind;
3996 else
3997 Info.FFDiag(E);
3998 return handler.failed();
3999 }
4000
4001 if (Index > NumElements) {
4002 Info.CCEDiag(E, diag::note_constexpr_array_index)
4003 << Index << /*array*/ 0 << NumElements;
4004 return handler.failed();
4005 }
4006
4007 ObjType = VT->getElementType();
4008 assert(I == N - 1 && "extracting subobject of scalar?");
4009 return handler.found(O->getVectorElt(Index), ObjType);
4010 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4011 if (Field->isMutable() &&
4012 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4013 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4014 << handler.AccessKind << Field;
4015 Info.Note(Field->getLocation(), diag::note_declared_at);
4016 return handler.failed();
4017 }
4018
4019 // Next subobject is a class, struct or union field.
4020 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
4021 if (RD->isUnion()) {
4022 const FieldDecl *UnionField = O->getUnionField();
4023 if (!UnionField ||
4024 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4025 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4026 // Placement new onto an inactive union member makes it active.
4027 O->setUnion(Field, APValue());
4028 } else {
4029 // Pointer to/into inactive union member: Not within lifetime
4030 if (handler.AccessKind == AK_IsWithinLifetime)
4031 return false;
4032 // FIXME: If O->getUnionValue() is absent, report that there's no
4033 // active union member rather than reporting the prior active union
4034 // member. We'll need to fix nullptr_t to not use APValue() as its
4035 // representation first.
4036 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4037 << handler.AccessKind << Field << !UnionField << UnionField;
4038 return handler.failed();
4039 }
4040 }
4041 O = &O->getUnionValue();
4042 } else
4043 O = &O->getStructField(Field->getFieldIndex());
4044
4045 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4046 LastField = Field;
4047 if (Field->getType().isVolatileQualified())
4048 VolatileField = Field;
4049 } else {
4050 // Next subobject is a base class.
4051 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4052 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4053 O = &O->getStructBase(getBaseIndex(Derived, Base));
4054
4055 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
4056 }
4057 }
4058}
4059
4060namespace {
4061struct ExtractSubobjectHandler {
4062 EvalInfo &Info;
4063 const Expr *E;
4064 APValue &Result;
4065 const AccessKinds AccessKind;
4066
4067 typedef bool result_type;
4068 bool failed() { return false; }
4069 bool found(APValue &Subobj, QualType SubobjType) {
4070 Result = Subobj;
4071 if (AccessKind == AK_ReadObjectRepresentation)
4072 return true;
4073 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4074 }
4075 bool found(APSInt &Value, QualType SubobjType) {
4076 Result = APValue(Value);
4077 return true;
4078 }
4079 bool found(APFloat &Value, QualType SubobjType) {
4080 Result = APValue(Value);
4081 return true;
4082 }
4083};
4084} // end anonymous namespace
4085
4086/// Extract the designated sub-object of an rvalue.
4087static bool extractSubobject(EvalInfo &Info, const Expr *E,
4088 const CompleteObject &Obj,
4089 const SubobjectDesignator &Sub, APValue &Result,
4090 AccessKinds AK = AK_Read) {
4091 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4092 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4093 return findSubobject(Info, E, Obj, Sub, Handler);
4094}
4095
4096namespace {
4097struct ModifySubobjectHandler {
4098 EvalInfo &Info;
4099 APValue &NewVal;
4100 const Expr *E;
4101
4102 typedef bool result_type;
4103 static const AccessKinds AccessKind = AK_Assign;
4104
4105 bool checkConst(QualType QT) {
4106 // Assigning to a const object has undefined behavior.
4107 if (QT.isConstQualified()) {
4108 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4109 return false;
4110 }
4111 return true;
4112 }
4113
4114 bool failed() { return false; }
4115 bool found(APValue &Subobj, QualType SubobjType) {
4116 if (!checkConst(SubobjType))
4117 return false;
4118 // We've been given ownership of NewVal, so just swap it in.
4119 Subobj.swap(NewVal);
4120 return true;
4121 }
4122 bool found(APSInt &Value, QualType SubobjType) {
4123 if (!checkConst(SubobjType))
4124 return false;
4125 if (!NewVal.isInt()) {
4126 // Maybe trying to write a cast pointer value into a complex?
4127 Info.FFDiag(E);
4128 return false;
4129 }
4130 Value = NewVal.getInt();
4131 return true;
4132 }
4133 bool found(APFloat &Value, QualType SubobjType) {
4134 if (!checkConst(SubobjType))
4135 return false;
4136 Value = NewVal.getFloat();
4137 return true;
4138 }
4139};
4140} // end anonymous namespace
4141
4142const AccessKinds ModifySubobjectHandler::AccessKind;
4143
4144/// Update the designated sub-object of an rvalue to the given value.
4145static bool modifySubobject(EvalInfo &Info, const Expr *E,
4146 const CompleteObject &Obj,
4147 const SubobjectDesignator &Sub,
4148 APValue &NewVal) {
4149 ModifySubobjectHandler Handler = { Info, NewVal, E };
4150 return findSubobject(Info, E, Obj, Sub, Handler);
4151}
4152
4153/// Find the position where two subobject designators diverge, or equivalently
4154/// the length of the common initial subsequence.
4155static unsigned FindDesignatorMismatch(QualType ObjType,
4156 const SubobjectDesignator &A,
4157 const SubobjectDesignator &B,
4158 bool &WasArrayIndex) {
4159 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4160 for (/**/; I != N; ++I) {
4161 if (!ObjType.isNull() &&
4162 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4163 // Next subobject is an array element.
4164 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4165 WasArrayIndex = true;
4166 return I;
4167 }
4168 if (ObjType->isAnyComplexType())
4169 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4170 else
4171 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4172 } else {
4173 if (A.Entries[I].getAsBaseOrMember() !=
4174 B.Entries[I].getAsBaseOrMember()) {
4175 WasArrayIndex = false;
4176 return I;
4177 }
4178 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4179 // Next subobject is a field.
4180 ObjType = FD->getType();
4181 else
4182 // Next subobject is a base class.
4183 ObjType = QualType();
4184 }
4185 }
4186 WasArrayIndex = false;
4187 return I;
4188}
4189
4190/// Determine whether the given subobject designators refer to elements of the
4191/// same array object.
4193 const SubobjectDesignator &A,
4194 const SubobjectDesignator &B) {
4195 if (A.Entries.size() != B.Entries.size())
4196 return false;
4197
4198 bool IsArray = A.MostDerivedIsArrayElement;
4199 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4200 // A is a subobject of the array element.
4201 return false;
4202
4203 // If A (and B) designates an array element, the last entry will be the array
4204 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4205 // of length 1' case, and the entire path must match.
4206 bool WasArrayIndex;
4207 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4208 return CommonLength >= A.Entries.size() - IsArray;
4209}
4210
4211/// Find the complete object to which an LValue refers.
4212static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4213 AccessKinds AK, const LValue &LVal,
4214 QualType LValType) {
4215 if (LVal.InvalidBase) {
4216 Info.FFDiag(E);
4217 return CompleteObject();
4218 }
4219
4220 if (!LVal.Base) {
4221 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4222 return CompleteObject();
4223 }
4224
4225 CallStackFrame *Frame = nullptr;
4226 unsigned Depth = 0;
4227 if (LVal.getLValueCallIndex()) {
4228 std::tie(Frame, Depth) =
4229 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4230 if (!Frame) {
4231 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4232 << AK << LVal.Base.is<const ValueDecl*>();
4233 NoteLValueLocation(Info, LVal.Base);
4234 return CompleteObject();
4235 }
4236 }
4237
4238 bool IsAccess = isAnyAccess(AK);
4239
4240 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4241 // is not a constant expression (even if the object is non-volatile). We also
4242 // apply this rule to C++98, in order to conform to the expected 'volatile'
4243 // semantics.
4244 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4245 if (Info.getLangOpts().CPlusPlus)
4246 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4247 << AK << LValType;
4248 else
4249 Info.FFDiag(E);
4250 return CompleteObject();
4251 }
4252
4253 // Compute value storage location and type of base object.
4254 APValue *BaseVal = nullptr;
4255 QualType BaseType = getType(LVal.Base);
4256
4257 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4258 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4259 // This is the object whose initializer we're evaluating, so its lifetime
4260 // started in the current evaluation.
4261 BaseVal = Info.EvaluatingDeclValue;
4262 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4263 // Allow reading from a GUID declaration.
4264 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4265 if (isModification(AK)) {
4266 // All the remaining cases do not permit modification of the object.
4267 Info.FFDiag(E, diag::note_constexpr_modify_global);
4268 return CompleteObject();
4269 }
4270 APValue &V = GD->getAsAPValue();
4271 if (V.isAbsent()) {
4272 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4273 << GD->getType();
4274 return CompleteObject();
4275 }
4276 return CompleteObject(LVal.Base, &V, GD->getType());
4277 }
4278
4279 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4280 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4281 if (isModification(AK)) {
4282 Info.FFDiag(E, diag::note_constexpr_modify_global);
4283 return CompleteObject();
4284 }
4285 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4286 GCD->getType());
4287 }
4288
4289 // Allow reading from template parameter objects.
4290 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4291 if (isModification(AK)) {
4292 Info.FFDiag(E, diag::note_constexpr_modify_global);
4293 return CompleteObject();
4294 }
4295 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4296 TPO->getType());
4297 }
4298
4299 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4300 // In C++11, constexpr, non-volatile variables initialized with constant
4301 // expressions are constant expressions too. Inside constexpr functions,
4302 // parameters are constant expressions even if they're non-const.
4303 // In C++1y, objects local to a constant expression (those with a Frame) are
4304 // both readable and writable inside constant expressions.
4305 // In C, such things can also be folded, although they are not ICEs.
4306 const VarDecl *VD = dyn_cast<VarDecl>(D);
4307 if (VD) {
4308 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4309 VD = VDef;
4310 }
4311 if (!VD || VD->isInvalidDecl()) {
4312 Info.FFDiag(E);
4313 return CompleteObject();
4314 }
4315
4316 bool IsConstant = BaseType.isConstant(Info.Ctx);
4317 bool ConstexprVar = false;
4318 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4319 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4320 ConstexprVar = VD->isConstexpr();
4321
4322 // Unless we're looking at a local variable or argument in a constexpr call,
4323 // the variable we're reading must be const.
4324 if (!Frame) {
4325 if (IsAccess && isa<ParmVarDecl>(VD)) {
4326 // Access of a parameter that's not associated with a frame isn't going
4327 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4328 // suitable diagnostic.
4329 } else if (Info.getLangOpts().CPlusPlus14 &&
4330 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4331 // OK, we can read and modify an object if we're in the process of
4332 // evaluating its initializer, because its lifetime began in this
4333 // evaluation.
4334 } else if (isModification(AK)) {
4335 // All the remaining cases do not permit modification of the object.
4336 Info.FFDiag(E, diag::note_constexpr_modify_global);
4337 return CompleteObject();
4338 } else if (VD->isConstexpr()) {
4339 // OK, we can read this variable.
4340 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4341 Info.FFDiag(E);
4342 return CompleteObject();
4343 } else if (BaseType->isIntegralOrEnumerationType()) {
4344 if (!IsConstant) {
4345 if (!IsAccess)
4346 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4347 if (Info.getLangOpts().CPlusPlus) {
4348 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4349 Info.Note(VD->getLocation(), diag::note_declared_at);
4350 } else {
4351 Info.FFDiag(E);
4352 }
4353 return CompleteObject();
4354 }
4355 } else if (!IsAccess) {
4356 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4357 } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4358 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4359 // This variable might end up being constexpr. Don't diagnose it yet.
4360 } else if (IsConstant) {
4361 // Keep evaluating to see what we can do. In particular, we support
4362 // folding of const floating-point types, in order to make static const
4363 // data members of such types (supported as an extension) more useful.
4364 if (Info.getLangOpts().CPlusPlus) {
4365 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4366 ? diag::note_constexpr_ltor_non_constexpr
4367 : diag::note_constexpr_ltor_non_integral, 1)
4368 << VD << BaseType;
4369 Info.Note(VD->getLocation(), diag::note_declared_at);
4370 } else {
4371 Info.CCEDiag(E);
4372 }
4373 } else {
4374 // Never allow reading a non-const value.
4375 if (Info.getLangOpts().CPlusPlus) {
4376 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4377 ? diag::note_constexpr_ltor_non_constexpr
4378 : diag::note_constexpr_ltor_non_integral, 1)
4379 << VD << BaseType;
4380 Info.Note(VD->getLocation(), diag::note_declared_at);
4381 } else {
4382 Info.FFDiag(E);
4383 }
4384 return CompleteObject();
4385 }
4386 }
4387
4388 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4389 return CompleteObject();
4390 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4391 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4392 if (!Alloc) {
4393 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4394 return CompleteObject();
4395 }
4396 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4397 LVal.Base.getDynamicAllocType());
4398 } else {
4399 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4400
4401 if (!Frame) {
4402 if (const MaterializeTemporaryExpr *MTE =
4403 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4404 assert(MTE->getStorageDuration() == SD_Static &&
4405 "should have a frame for a non-global materialized temporary");
4406
4407 // C++20 [expr.const]p4: [DR2126]
4408 // An object or reference is usable in constant expressions if it is
4409 // - a temporary object of non-volatile const-qualified literal type
4410 // whose lifetime is extended to that of a variable that is usable
4411 // in constant expressions
4412 //
4413 // C++20 [expr.const]p5:
4414 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4415 // - a non-volatile glvalue that refers to an object that is usable
4416 // in constant expressions, or
4417 // - a non-volatile glvalue of literal type that refers to a
4418 // non-volatile object whose lifetime began within the evaluation
4419 // of E;
4420 //
4421 // C++11 misses the 'began within the evaluation of e' check and
4422 // instead allows all temporaries, including things like:
4423 // int &&r = 1;
4424 // int x = ++r;
4425 // constexpr int k = r;
4426 // Therefore we use the C++14-onwards rules in C++11 too.
4427 //
4428 // Note that temporaries whose lifetimes began while evaluating a
4429 // variable's constructor are not usable while evaluating the
4430 // corresponding destructor, not even if they're of const-qualified
4431 // types.
4432 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4433 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4434 if (!IsAccess)
4435 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4436 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4437 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4438 return CompleteObject();
4439 }
4440
4441 BaseVal = MTE->getOrCreateValue(false);
4442 assert(BaseVal && "got reference to unevaluated temporary");
4443 } else {
4444 if (!IsAccess)
4445 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4446 APValue Val;
4447 LVal.moveInto(Val);
4448 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4449 << AK
4450 << Val.getAsString(Info.Ctx,
4451 Info.Ctx.getLValueReferenceType(LValType));
4452 NoteLValueLocation(Info, LVal.Base);
4453 return CompleteObject();
4454 }
4455 } else {
4456 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4457 assert(BaseVal && "missing value for temporary");
4458 }
4459 }
4460
4461 // In C++14, we can't safely access any mutable state when we might be
4462 // evaluating after an unmodeled side effect. Parameters are modeled as state
4463 // in the caller, but aren't visible once the call returns, so they can be
4464 // modified in a speculatively-evaluated call.
4465 //
4466 // FIXME: Not all local state is mutable. Allow local constant subobjects
4467 // to be read here (but take care with 'mutable' fields).
4468 unsigned VisibleDepth = Depth;
4469 if (llvm::isa_and_nonnull<ParmVarDecl>(
4470 LVal.Base.dyn_cast<const ValueDecl *>()))
4471 ++VisibleDepth;
4472 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4473 Info.EvalStatus.HasSideEffects) ||
4474 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4475 return CompleteObject();
4476
4477 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4478}
4479
4480/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4481/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4482/// glvalue referred to by an entity of reference type.
4483///
4484/// \param Info - Information about the ongoing evaluation.
4485/// \param Conv - The expression for which we are performing the conversion.
4486/// Used for diagnostics.
4487/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4488/// case of a non-class type).
4489/// \param LVal - The glvalue on which we are attempting to perform this action.
4490/// \param RVal - The produced value will be placed here.
4491/// \param WantObjectRepresentation - If true, we're looking for the object
4492/// representation rather than the value, and in particular,
4493/// there is no requirement that the result be fully initialized.
4494static bool
4496 const LValue &LVal, APValue &RVal,
4497 bool WantObjectRepresentation = false) {
4498 if (LVal.Designator.Invalid)
4499 return false;
4500
4501 // Check for special cases where there is no existing APValue to look at.
4502 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4503
4504 AccessKinds AK =
4505 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4506
4507 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4508 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4509 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4510 // initializer until now for such expressions. Such an expression can't be
4511 // an ICE in C, so this only matters for fold.
4512 if (Type.isVolatileQualified()) {
4513 Info.FFDiag(Conv);
4514 return false;
4515 }
4516
4517 APValue Lit;
4518 if (!Evaluate(Lit, Info, CLE->getInitializer()))
4519 return false;
4520
4521 // According to GCC info page:
4522 //
4523 // 6.28 Compound Literals
4524 //
4525 // As an optimization, G++ sometimes gives array compound literals longer
4526 // lifetimes: when the array either appears outside a function or has a
4527 // const-qualified type. If foo and its initializer had elements of type
4528 // char *const rather than char *, or if foo were a global variable, the
4529 // array would have static storage duration. But it is probably safest
4530 // just to avoid the use of array compound literals in C++ code.
4531 //
4532 // Obey that rule by checking constness for converted array types.
4533
4534 QualType CLETy = CLE->getType();
4535 if (CLETy->isArrayType() && !Type->isArrayType()) {
4536 if (!CLETy.isConstant(Info.Ctx)) {
4537 Info.FFDiag(Conv);
4538 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4539 return false;
4540 }
4541 }
4542
4543 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4544 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4545 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4546 // Special-case character extraction so we don't have to construct an
4547 // APValue for the whole string.
4548 assert(LVal.Designator.Entries.size() <= 1 &&
4549 "Can only read characters from string literals");
4550 if (LVal.Designator.Entries.empty()) {
4551 // Fail for now for LValue to RValue conversion of an array.
4552 // (This shouldn't show up in C/C++, but it could be triggered by a
4553 // weird EvaluateAsRValue call from a tool.)
4554 Info.FFDiag(Conv);
4555 return false;
4556 }
4557 if (LVal.Designator.isOnePastTheEnd()) {
4558 if (Info.getLangOpts().CPlusPlus11)
4559 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4560 else
4561 Info.FFDiag(Conv);
4562 return false;
4563 }
4564 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4565 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4566 return true;
4567 }
4568 }
4569
4570 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4571 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4572}
4573
4574/// Perform an assignment of Val to LVal. Takes ownership of Val.
4575static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4576 QualType LValType, APValue &Val) {
4577 if (LVal.Designator.Invalid)
4578 return false;
4579
4580 if (!Info.getLangOpts().CPlusPlus14) {
4581 Info.FFDiag(E);
4582 return false;
4583 }
4584
4585 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4586 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4587}
4588
4589namespace {
4590struct CompoundAssignSubobjectHandler {
4591 EvalInfo &Info;
4593 QualType PromotedLHSType;
4595 const APValue &RHS;
4596
4597 static const AccessKinds AccessKind = AK_Assign;
4598
4599 typedef bool result_type;
4600
4601 bool checkConst(QualType QT) {
4602 // Assigning to a const object has undefined behavior.
4603 if (QT.isConstQualified()) {
4604 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4605 return false;
4606 }
4607 return true;
4608 }
4609
4610 bool failed() { return false; }
4611 bool found(APValue &Subobj, QualType SubobjType) {
4612 switch (Subobj.getKind()) {
4613 case APValue::Int:
4614 return found(Subobj.getInt(), SubobjType);
4615 case APValue::Float:
4616 return found(Subobj.getFloat(), SubobjType);
4619 // FIXME: Implement complex compound assignment.
4620 Info.FFDiag(E);
4621 return false;
4622 case APValue::LValue:
4623 return foundPointer(Subobj, SubobjType);
4624 case APValue::Vector:
4625 return foundVector(Subobj, SubobjType);
4627 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4628 << /*read of=*/0 << /*uninitialized object=*/1
4629 << E->getLHS()->getSourceRange();
4630 return false;
4631 default:
4632 // FIXME: can this happen?
4633 Info.FFDiag(E);
4634 return false;
4635 }
4636 }
4637
4638 bool foundVector(APValue &Value, QualType SubobjType) {
4639 if (!checkConst(SubobjType))
4640 return false;
4641
4642 if (!SubobjType->isVectorType()) {
4643 Info.FFDiag(E);
4644 return false;
4645 }
4646 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4647 }
4648
4649 bool found(APSInt &Value, QualType SubobjType) {
4650 if (!checkConst(SubobjType))
4651 return false;
4652
4653 if (!SubobjType->isIntegerType()) {
4654 // We don't support compound assignment on integer-cast-to-pointer
4655 // values.
4656 Info.FFDiag(E);
4657 return false;
4658 }
4659
4660 if (RHS.isInt()) {
4661 APSInt LHS =
4662 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4663 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4664 return false;
4665 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4666 return true;
4667 } else if (RHS.isFloat()) {
4668 const FPOptions FPO = E->getFPFeaturesInEffect(
4669 Info.Ctx.getLangOpts());
4670 APFloat FValue(0.0);
4671 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4672 PromotedLHSType, FValue) &&
4673 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4674 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4675 Value);
4676 }
4677
4678 Info.FFDiag(E);
4679 return false;
4680 }
4681 bool found(APFloat &Value, QualType SubobjType) {
4682 return checkConst(SubobjType) &&
4683 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4684 Value) &&
4685 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4686 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4687 }
4688 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4689 if (!checkConst(SubobjType))
4690 return false;
4691
4692 QualType PointeeType;
4693 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4694 PointeeType = PT->getPointeeType();
4695
4696 if (PointeeType.isNull() || !RHS.isInt() ||
4697 (Opcode != BO_Add && Opcode != BO_Sub)) {
4698 Info.FFDiag(E);
4699 return false;
4700 }
4701
4702 APSInt Offset = RHS.getInt();
4703 if (Opcode == BO_Sub)
4704 negateAsSigned(Offset);
4705
4706 LValue LVal;
4707 LVal.setFrom(Info.Ctx, Subobj);
4708 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4709 return false;
4710 LVal.moveInto(Subobj);
4711 return true;
4712 }
4713};
4714} // end anonymous namespace
4715
4716const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4717
4718/// Perform a compound assignment of LVal <op>= RVal.
4719static bool handleCompoundAssignment(EvalInfo &Info,
4721 const LValue &LVal, QualType LValType,
4722 QualType PromotedLValType,
4723 BinaryOperatorKind Opcode,
4724 const APValue &RVal) {
4725 if (LVal.Designator.Invalid)
4726 return false;
4727
4728 if (!Info.getLangOpts().CPlusPlus14) {
4729 Info.FFDiag(E);
4730 return false;
4731 }
4732
4733 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4734 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4735 RVal };
4736 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4737}
4738
4739namespace {
4740struct IncDecSubobjectHandler {
4741 EvalInfo &Info;
4742 const UnaryOperator *E;
4743 AccessKinds AccessKind;
4744 APValue *Old;
4745
4746 typedef bool result_type;
4747
4748 bool checkConst(QualType QT) {
4749 // Assigning to a const object has undefined behavior.
4750 if (QT.isConstQualified()) {
4751 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4752 return false;
4753 }
4754 return true;
4755 }
4756
4757 bool failed() { return false; }
4758 bool found(APValue &Subobj, QualType SubobjType) {
4759 // Stash the old value. Also clear Old, so we don't clobber it later
4760 // if we're post-incrementing a complex.
4761 if (Old) {
4762 *Old = Subobj;
4763 Old = nullptr;
4764 }
4765
4766 switch (Subobj.getKind()) {
4767 case APValue::Int:
4768 return found(Subobj.getInt(), SubobjType);
4769 case APValue::Float:
4770 return found(Subobj.getFloat(), SubobjType);
4772 return found(Subobj.getComplexIntReal(),
4773 SubobjType->castAs<ComplexType>()->getElementType()
4774 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4776 return found(Subobj.getComplexFloatReal(),
4777 SubobjType->castAs<ComplexType>()->getElementType()
4778 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4779 case APValue::LValue:
4780 return foundPointer(Subobj, SubobjType);
4781 default:
4782 // FIXME: can this happen?
4783 Info.FFDiag(E);
4784 return false;
4785 }
4786 }
4787 bool found(APSInt &Value, QualType SubobjType) {
4788 if (!checkConst(SubobjType))
4789 return false;
4790
4791 if (!SubobjType->isIntegerType()) {
4792 // We don't support increment / decrement on integer-cast-to-pointer
4793 // values.
4794 Info.FFDiag(E);
4795 return false;
4796 }
4797
4798 if (Old) *Old = APValue(Value);
4799
4800 // bool arithmetic promotes to int, and the conversion back to bool
4801 // doesn't reduce mod 2^n, so special-case it.
4802 if (SubobjType->isBooleanType()) {
4803 if (AccessKind == AK_Increment)
4804 Value = 1;
4805 else
4806 Value = !Value;
4807 return true;
4808 }
4809
4810 bool WasNegative = Value.isNegative();
4811 if (AccessKind == AK_Increment) {
4812 ++Value;
4813
4814 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4815 APSInt ActualValue(Value, /*IsUnsigned*/true);
4816 return HandleOverflow(Info, E, ActualValue, SubobjType);
4817 }
4818 } else {
4819 --Value;
4820
4821 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4822 unsigned BitWidth = Value.getBitWidth();
4823 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4824 ActualValue.setBit(BitWidth);
4825 return HandleOverflow(Info, E, ActualValue, SubobjType);
4826 }
4827 }
4828 return true;
4829 }
4830 bool found(APFloat &Value, QualType SubobjType) {
4831 if (!checkConst(SubobjType))
4832 return false;
4833
4834 if (Old) *Old = APValue(Value);
4835
4836 APFloat One(Value.getSemantics(), 1);
4837 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4838 APFloat::opStatus St;
4839 if (AccessKind == AK_Increment)
4840 St = Value.add(One, RM);
4841 else
4842 St = Value.subtract(One, RM);
4843 return checkFloatingPointResult(Info, E, St);
4844 }
4845 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4846 if (!checkConst(SubobjType))
4847 return false;
4848
4849 QualType PointeeType;
4850 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4851 PointeeType = PT->getPointeeType();
4852 else {
4853 Info.FFDiag(E);
4854 return false;
4855 }
4856
4857 LValue LVal;
4858 LVal.setFrom(Info.Ctx, Subobj);
4859 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4860 AccessKind == AK_Increment ? 1 : -1))
4861 return false;
4862 LVal.moveInto(Subobj);
4863 return true;
4864 }
4865};
4866} // end anonymous namespace
4867
4868/// Perform an increment or decrement on LVal.
4869static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4870 QualType LValType, bool IsIncrement, APValue *Old) {
4871 if (LVal.Designator.Invalid)
4872 return false;
4873
4874 if (!Info.getLangOpts().CPlusPlus14) {
4875 Info.FFDiag(E);
4876 return false;
4877 }
4878
4879 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4880 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4881 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4882 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4883}
4884
4885/// Build an lvalue for the object argument of a member function call.
4886static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4887 LValue &This) {
4888 if (Object->getType()->isPointerType() && Object->isPRValue())
4889 return EvaluatePointer(Object, This, Info);
4890
4891 if (Object->isGLValue())
4892 return EvaluateLValue(Object, This, Info);
4893
4894 if (Object->getType()->isLiteralType(Info.Ctx))
4895 return EvaluateTemporary(Object, This, Info);
4896
4897 if (Object->getType()->isRecordType() && Object->isPRValue())
4898 return EvaluateTemporary(Object, This, Info);
4899
4900 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4901 return false;
4902}
4903
4904/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4905/// lvalue referring to the result.
4906///
4907/// \param Info - Information about the ongoing evaluation.
4908/// \param LV - An lvalue referring to the base of the member pointer.
4909/// \param RHS - The member pointer expression.
4910/// \param IncludeMember - Specifies whether the member itself is included in
4911/// the resulting LValue subobject designator. This is not possible when
4912/// creating a bound member function.
4913/// \return The field or method declaration to which the member pointer refers,
4914/// or 0 if evaluation fails.
4915static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4916 QualType LVType,
4917 LValue &LV,
4918 const Expr *RHS,
4919 bool IncludeMember = true) {
4920 MemberPtr MemPtr;
4921 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4922 return nullptr;
4923
4924 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4925 // member value, the behavior is undefined.
4926 if (!MemPtr.getDecl()) {
4927 // FIXME: Specific diagnostic.
4928 Info.FFDiag(RHS);
4929 return nullptr;
4930 }
4931
4932 if (MemPtr.isDerivedMember()) {
4933 // This is a member of some derived class. Truncate LV appropriately.
4934 // The end of the derived-to-base path for the base object must match the
4935 // derived-to-base path for the member pointer.
4936 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4937 LV.Designator.Entries.size()) {
4938 Info.FFDiag(RHS);
4939 return nullptr;
4940 }
4941 unsigned PathLengthToMember =
4942 LV.Designator.Entries.size() - MemPtr.Path.size();
4943 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4944 const CXXRecordDecl *LVDecl = getAsBaseClass(
4945 LV.Designator.Entries[PathLengthToMember + I]);
4946 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4947 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4948 Info.FFDiag(RHS);
4949 return nullptr;
4950 }
4951 }
4952
4953 // Truncate the lvalue to the appropriate derived class.
4954 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4955 PathLengthToMember))
4956 return nullptr;
4957 } else if (!MemPtr.Path.empty()) {
4958 // Extend the LValue path with the member pointer's path.
4959 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4960 MemPtr.Path.size() + IncludeMember);
4961
4962 // Walk down to the appropriate base class.
4963 if (const PointerType *PT = LVType->getAs<PointerType>())
4964 LVType = PT->getPointeeType();
4965 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4966 assert(RD && "member pointer access on non-class-type expression");
4967 // The first class in the path is that of the lvalue.
4968 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4969 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4970 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4971 return nullptr;
4972 RD = Base;
4973 }
4974 // Finally cast to the class containing the member.
4975 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4976 MemPtr.getContainingRecord()))
4977 return nullptr;
4978 }
4979
4980 // Add the member. Note that we cannot build bound member functions here.
4981 if (IncludeMember) {
4982 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4983 if (!HandleLValueMember(Info, RHS, LV, FD))
4984 return nullptr;
4985 } else if (const IndirectFieldDecl *IFD =
4986 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4987 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4988 return nullptr;
4989 } else {
4990 llvm_unreachable("can't construct reference to bound member function");
4991 }
4992 }
4993
4994 return MemPtr.getDecl();
4995}
4996
4997static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4998 const BinaryOperator *BO,
4999 LValue &LV,
5000 bool IncludeMember = true) {
5001 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5002
5003 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5004 if (Info.noteFailure()) {
5005 MemberPtr MemPtr;
5006 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5007 }
5008 return nullptr;
5009 }
5010
5011 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5012 BO->getRHS(), IncludeMember);
5013}
5014
5015/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5016/// the provided lvalue, which currently refers to the base object.
5017static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5018 LValue &Result) {
5019 SubobjectDesignator &D = Result.Designator;
5020 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5021 return false;
5022
5023 QualType TargetQT = E->getType();
5024 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5025 TargetQT = PT->getPointeeType();
5026
5027 // Check this cast lands within the final derived-to-base subobject path.
5028 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
5029 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5030 << D.MostDerivedType << TargetQT;
5031 return false;
5032 }
5033
5034 // Check the type of the final cast. We don't need to check the path,
5035 // since a cast can only be formed if the path is unique.
5036 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5037 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5038 const CXXRecordDecl *FinalType;
5039 if (NewEntriesSize == D.MostDerivedPathLength)
5040 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5041 else
5042 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5043 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
5044 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5045 << D.MostDerivedType << TargetQT;
5046 return false;
5047 }
5048
5049 // Truncate the lvalue to the appropriate derived class.
5050 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5051}
5052
5053/// Get the value to use for a default-initialized object of type T.
5054/// Return false if it encounters something invalid.
5056 bool Success = true;
5057
5058 // If there is already a value present don't overwrite it.
5059 if (!Result.isAbsent())
5060 return true;
5061
5062 if (auto *RD = T->getAsCXXRecordDecl()) {
5063 if (RD->isInvalidDecl()) {
5064 Result = APValue();
5065 return false;
5066 }
5067 if (RD->isUnion()) {
5068 Result = APValue((const FieldDecl *)nullptr);
5069 return true;
5070 }
5071 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5072 std::distance(RD->field_begin(), RD->field_end()));
5073
5074 unsigned Index = 0;
5075 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5076 End = RD->bases_end();
5077 I != End; ++I, ++Index)
5078 Success &=
5079 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5080
5081 for (const auto *I : RD->fields()) {
5082 if (I->isUnnamedBitField())
5083 continue;
5085 I->getType(), Result.getStructField(I->getFieldIndex()));
5086 }
5087 return Success;
5088 }
5089
5090 if (auto *AT =
5091 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5092 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5093 if (Result.hasArrayFiller())
5094 Success &=
5095 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5096
5097 return Success;
5098 }
5099
5100 Result = APValue::IndeterminateValue();
5101 return true;
5102}
5103
5104namespace {
5105enum EvalStmtResult {
5106 /// Evaluation failed.
5107 ESR_Failed,
5108 /// Hit a 'return' statement.
5109 ESR_Returned,
5110 /// Evaluation succeeded.
5111 ESR_Succeeded,
5112 /// Hit a 'continue' statement.
5113 ESR_Continue,
5114 /// Hit a 'break' statement.
5115 ESR_Break,
5116 /// Still scanning for 'case' or 'default' statement.
5117 ESR_CaseNotFound
5118};
5119}
5120
5121static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5122 if (VD->isInvalidDecl())
5123 return false;
5124 // We don't need to evaluate the initializer for a static local.
5125 if (!VD->hasLocalStorage())
5126 return true;
5127
5128 LValue Result;
5129 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5130 ScopeKind::Block, Result);
5131
5132 const Expr *InitE = VD->getInit();
5133 if (!InitE) {
5134 if (VD->getType()->isDependentType())
5135 return Info.noteSideEffect();
5136 return handleDefaultInitValue(VD->getType(), Val);
5137 }
5138 if (InitE->isValueDependent())
5139 return false;
5140
5141 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5142 // Wipe out any partially-computed value, to allow tracking that this
5143 // evaluation failed.
5144 Val = APValue();
5145 return false;
5146 }
5147
5148 return true;
5149}
5150
5151static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
5152 bool OK = true;
5153
5154 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5155 OK &= EvaluateVarDecl(Info, VD);
5156
5157 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
5158 for (auto *BD : DD->bindings())
5159 if (auto *VD = BD->getHoldingVar())
5160 OK &= EvaluateDecl(Info, VD);
5161
5162 return OK;
5163}
5164
5165static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5166 assert(E->isValueDependent());
5167 if (Info.noteSideEffect())
5168 return true;
5169 assert(E->containsErrors() && "valid value-dependent expression should never "
5170 "reach invalid code path.");
5171 return false;
5172}
5173
5174/// Evaluate a condition (either a variable declaration or an expression).
5175static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5176 const Expr *Cond, bool &Result) {
5177 if (Cond->isValueDependent())
5178 return false;
5179 FullExpressionRAII Scope(Info);
5180 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5181 return false;
5182 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5183 return false;
5184 return Scope.destroy();
5185}
5186
5187namespace {
5188/// A location where the result (returned value) of evaluating a
5189/// statement should be stored.
5190struct StmtResult {
5191 /// The APValue that should be filled in with the returned value.
5192 APValue &Value;
5193 /// The location containing the result, if any (used to support RVO).
5194 const LValue *Slot;
5195};
5196
5197struct TempVersionRAII {
5198 CallStackFrame &Frame;
5199
5200 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5201 Frame.pushTempVersion();
5202 }
5203
5204 ~TempVersionRAII() {
5205 Frame.popTempVersion();
5206 }
5207};
5208
5209}
5210
5211static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5212 const Stmt *S,
5213 const SwitchCase *SC = nullptr);
5214
5215/// Evaluate the body of a loop, and translate the result as appropriate.
5216static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5217 const Stmt *Body,
5218 const SwitchCase *Case = nullptr) {
5219 BlockScopeRAII Scope(Info);
5220
5221 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5222 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5223 ESR = ESR_Failed;
5224
5225 switch (ESR) {
5226 case ESR_Break:
5227 return ESR_Succeeded;
5228 case ESR_Succeeded:
5229 case ESR_Continue:
5230 return ESR_Continue;
5231 case ESR_Failed:
5232 case ESR_Returned:
5233 case ESR_CaseNotFound:
5234 return ESR;
5235 }
5236 llvm_unreachable("Invalid EvalStmtResult!");
5237}
5238
5239/// Evaluate a switch statement.
5240static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5241 const SwitchStmt *SS) {
5242 BlockScopeRAII Scope(Info);
5243
5244 // Evaluate the switch condition.
5245 APSInt Value;
5246 {
5247 if (const Stmt *Init = SS->getInit()) {
5248 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5249 if (ESR != ESR_Succeeded) {
5250 if (ESR != ESR_Failed && !Scope.destroy())
5251 ESR = ESR_Failed;
5252 return ESR;
5253 }
5254 }
5255
5256 FullExpressionRAII CondScope(Info);
5257 if (SS->getConditionVariable() &&
5258 !EvaluateDecl(Info, SS->getConditionVariable()))
5259 return ESR_Failed;
5260 if (SS->getCond()->isValueDependent()) {
5261 // We don't know what the value is, and which branch should jump to.
5262 EvaluateDependentExpr(SS->getCond(), Info);
5263 return ESR_Failed;
5264 }
5265 if (!EvaluateInteger(SS->getCond(), Value, Info))
5266 return ESR_Failed;
5267
5268 if (!CondScope.destroy())
5269 return ESR_Failed;
5270 }
5271
5272 // Find the switch case corresponding to the value of the condition.
5273 // FIXME: Cache this lookup.
5274 const SwitchCase *Found = nullptr;
5275 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5276 SC = SC->getNextSwitchCase()) {
5277 if (isa<DefaultStmt>(SC)) {
5278 Found = SC;
5279 continue;
5280 }
5281
5282 const CaseStmt *CS = cast<CaseStmt>(SC);
5283 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5284 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5285 : LHS;
5286 if (LHS <= Value && Value <= RHS) {
5287 Found = SC;
5288 break;
5289 }
5290 }
5291
5292 if (!Found)
5293 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5294
5295 // Search the switch body for the switch case and evaluate it from there.
5296 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5297 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5298 return ESR_Failed;
5299
5300 switch (ESR) {
5301 case ESR_Break:
5302 return ESR_Succeeded;
5303 case ESR_Succeeded:
5304 case ESR_Continue:
5305 case ESR_Failed:
5306 case ESR_Returned:
5307 return ESR;
5308 case ESR_CaseNotFound:
5309 // This can only happen if the switch case is nested within a statement
5310 // expression. We have no intention of supporting that.
5311 Info.FFDiag(Found->getBeginLoc(),
5312 diag::note_constexpr_stmt_expr_unsupported);
5313 return ESR_Failed;
5314 }
5315 llvm_unreachable("Invalid EvalStmtResult!");
5316}
5317
5318static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5319 // An expression E is a core constant expression unless the evaluation of E
5320 // would evaluate one of the following: [C++23] - a control flow that passes
5321 // through a declaration of a variable with static or thread storage duration
5322 // unless that variable is usable in constant expressions.
5323 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5324 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5325 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5326 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5327 return false;
5328 }
5329 return true;
5330}
5331
5332// Evaluate a statement.
5333static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5334 const Stmt *S, const SwitchCase *Case) {
5335 if (!Info.nextStep(S))
5336 return ESR_Failed;
5337
5338 // If we're hunting down a 'case' or 'default' label, recurse through
5339 // substatements until we hit the label.
5340 if (Case) {
5341 switch (S->getStmtClass()) {
5342 case Stmt::CompoundStmtClass:
5343 // FIXME: Precompute which substatement of a compound statement we
5344 // would jump to, and go straight there rather than performing a
5345 // linear scan each time.
5346 case Stmt::LabelStmtClass:
5347 case Stmt::AttributedStmtClass:
5348 case Stmt::DoStmtClass:
5349 break;
5350
5351 case Stmt::CaseStmtClass:
5352 case Stmt::DefaultStmtClass:
5353 if (Case == S)
5354 Case = nullptr;
5355 break;
5356
5357 case Stmt::IfStmtClass: {
5358 // FIXME: Precompute which side of an 'if' we would jump to, and go
5359 // straight there rather than scanning both sides.
5360 const IfStmt *IS = cast<IfStmt>(S);
5361
5362 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5363 // preceded by our switch label.
5364 BlockScopeRAII Scope(Info);
5365
5366 // Step into the init statement in case it brings an (uninitialized)
5367 // variable into scope.
5368 if (const Stmt *Init = IS->getInit()) {
5369 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5370 if (ESR != ESR_CaseNotFound) {
5371 assert(ESR != ESR_Succeeded);
5372 return ESR;
5373 }
5374 }
5375
5376 // Condition variable must be initialized if it exists.
5377 // FIXME: We can skip evaluating the body if there's a condition
5378 // variable, as there can't be any case labels within it.
5379 // (The same is true for 'for' statements.)
5380
5381 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5382 if (ESR == ESR_Failed)
5383 return ESR;
5384 if (ESR != ESR_CaseNotFound)
5385 return Scope.destroy() ? ESR : ESR_Failed;
5386 if (!IS->getElse())
5387 return ESR_CaseNotFound;
5388
5389 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5390 if (ESR == ESR_Failed)
5391 return ESR;
5392 if (ESR != ESR_CaseNotFound)
5393 return Scope.destroy() ? ESR : ESR_Failed;
5394 return ESR_CaseNotFound;
5395 }
5396
5397 case Stmt::WhileStmtClass: {
5398 EvalStmtResult ESR =
5399 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5400 if (ESR != ESR_Continue)
5401 return ESR;
5402 break;
5403 }
5404
5405 case Stmt::ForStmtClass: {
5406 const ForStmt *FS = cast<ForStmt>(S);
5407 BlockScopeRAII Scope(Info);
5408
5409 // Step into the init statement in case it brings an (uninitialized)
5410 // variable into scope.
5411 if (const Stmt *Init = FS->getInit()) {
5412 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5413 if (ESR != ESR_CaseNotFound) {
5414 assert(ESR != ESR_Succeeded);
5415 return ESR;
5416 }
5417 }
5418
5419 EvalStmtResult ESR =
5420 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5421 if (ESR != ESR_Continue)
5422 return ESR;
5423 if (const auto *Inc = FS->getInc()) {
5424 if (Inc->isValueDependent()) {
5425 if (!EvaluateDependentExpr(Inc, Info))
5426 return ESR_Failed;
5427 } else {
5428 FullExpressionRAII IncScope(Info);
5429 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5430 return ESR_Failed;
5431 }
5432 }
5433 break;
5434 }
5435
5436 case Stmt::DeclStmtClass: {
5437 // Start the lifetime of any uninitialized variables we encounter. They
5438 // might be used by the selected branch of the switch.
5439 const DeclStmt *DS = cast<DeclStmt>(S);
5440 for (const auto *D : DS->decls()) {
5441 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5442 if (!CheckLocalVariableDeclaration(Info, VD))
5443 return ESR_Failed;
5444 if (VD->hasLocalStorage() && !VD->getInit())
5445 if (!EvaluateVarDecl(Info, VD))
5446 return ESR_Failed;
5447 // FIXME: If the variable has initialization that can't be jumped
5448 // over, bail out of any immediately-surrounding compound-statement
5449 // too. There can't be any case labels here.
5450 }
5451 }
5452 return ESR_CaseNotFound;
5453 }
5454
5455 default:
5456 return ESR_CaseNotFound;
5457 }
5458 }
5459
5460 switch (S->getStmtClass()) {
5461 default:
5462 if (const Expr *E = dyn_cast<Expr>(S)) {
5463 if (E->isValueDependent()) {
5464 if (!EvaluateDependentExpr(E, Info))
5465 return ESR_Failed;
5466 } else {
5467 // Don't bother evaluating beyond an expression-statement which couldn't
5468 // be evaluated.
5469 // FIXME: Do we need the FullExpressionRAII object here?
5470 // VisitExprWithCleanups should create one when necessary.
5471 FullExpressionRAII Scope(Info);
5472 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5473 return ESR_Failed;
5474 }
5475 return ESR_Succeeded;
5476 }
5477
5478 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5479 return ESR_Failed;
5480
5481 case Stmt::NullStmtClass:
5482 return ESR_Succeeded;
5483
5484 case Stmt::DeclStmtClass: {
5485 const DeclStmt *DS = cast<DeclStmt>(S);
5486 for (const auto *D : DS->decls()) {
5487 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5488 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5489 return ESR_Failed;
5490 // Each declaration initialization is its own full-expression.
5491 FullExpressionRAII Scope(Info);
5492 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5493 return ESR_Failed;
5494 if (!Scope.destroy())
5495 return ESR_Failed;
5496 }
5497 return ESR_Succeeded;
5498 }
5499
5500 case Stmt::ReturnStmtClass: {
5501 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5502 FullExpressionRAII Scope(Info);
5503 if (RetExpr && RetExpr->isValueDependent()) {
5504 EvaluateDependentExpr(RetExpr, Info);
5505 // We know we returned, but we don't know what the value is.
5506 return ESR_Failed;
5507 }
5508 if (RetExpr &&
5509 !(Result.Slot
5510 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5511 : Evaluate(Result.Value, Info, RetExpr)))
5512 return ESR_Failed;
5513 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5514 }
5515
5516 case Stmt::CompoundStmtClass: {
5517 BlockScopeRAII Scope(Info);
5518
5519 const CompoundStmt *CS = cast<CompoundStmt>(S);
5520 for (const auto *BI : CS->body()) {
5521 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5522 if (ESR == ESR_Succeeded)
5523 Case = nullptr;
5524 else if (ESR != ESR_CaseNotFound) {
5525 if (ESR != ESR_Failed && !Scope.destroy())
5526 return ESR_Failed;
5527 return ESR;
5528 }
5529 }
5530 if (Case)
5531 return ESR_CaseNotFound;
5532 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5533 }
5534
5535 case Stmt::IfStmtClass: {
5536 const IfStmt *IS = cast<IfStmt>(S);
5537
5538 // Evaluate the condition, as either a var decl or as an expression.
5539 BlockScopeRAII Scope(Info);
5540 if (const Stmt *Init = IS->getInit()) {
5541 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5542 if (ESR != ESR_Succeeded) {
5543 if (ESR != ESR_Failed && !Scope.destroy())
5544 return ESR_Failed;
5545 return ESR;
5546 }
5547 }
5548 bool Cond;
5549 if (IS->isConsteval()) {
5550 Cond = IS->isNonNegatedConsteval();
5551 // If we are not in a constant context, if consteval should not evaluate
5552 // to true.
5553 if (!Info.InConstantContext)
5554 Cond = !Cond;
5555 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5556 Cond))
5557 return ESR_Failed;
5558
5559 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5560 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5561 if (ESR != ESR_Succeeded) {
5562 if (ESR != ESR_Failed && !Scope.destroy())
5563 return ESR_Failed;
5564 return ESR;
5565 }
5566 }
5567 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5568 }
5569
5570 case Stmt::WhileStmtClass: {
5571 const WhileStmt *WS = cast<WhileStmt>(S);
5572 while (true) {
5573 BlockScopeRAII Scope(Info);
5574 bool Continue;
5575 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5576 Continue))
5577 return ESR_Failed;
5578 if (!Continue)
5579 break;
5580
5581 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5582 if (ESR != ESR_Continue) {
5583 if (ESR != ESR_Failed && !Scope.destroy())
5584 return ESR_Failed;
5585 return ESR;
5586 }
5587 if (!Scope.destroy())
5588 return ESR_Failed;
5589 }
5590 return ESR_Succeeded;
5591 }
5592
5593 case Stmt::DoStmtClass: {
5594 const DoStmt *DS = cast<DoStmt>(S);
5595 bool Continue;
5596 do {
5597 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5598 if (ESR != ESR_Continue)
5599 return ESR;
5600 Case = nullptr;
5601
5602 if (DS->getCond()->isValueDependent()) {
5603 EvaluateDependentExpr(DS->getCond(), Info);
5604 // Bailout as we don't know whether to keep going or terminate the loop.
5605 return ESR_Failed;
5606 }
5607 FullExpressionRAII CondScope(Info);
5608 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5609 !CondScope.destroy())
5610 return ESR_Failed;
5611 } while (Continue);
5612 return ESR_Succeeded;
5613 }
5614
5615 case Stmt::ForStmtClass: {
5616 const ForStmt *FS = cast<ForStmt>(S);
5617 BlockScopeRAII ForScope(Info);
5618 if (FS->getInit()) {
5619 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5620 if (ESR != ESR_Succeeded) {
5621 if (ESR != ESR_Failed && !ForScope.destroy())
5622 return ESR_Failed;
5623 return ESR;
5624 }
5625 }
5626 while (true) {
5627 BlockScopeRAII IterScope(Info);
5628 bool Continue = true;
5629 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5630 FS->getCond(), Continue))
5631 return ESR_Failed;
5632 if (!Continue)
5633 break;
5634
5635 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5636 if (ESR != ESR_Continue) {
5637 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5638 return ESR_Failed;
5639 return ESR;
5640 }
5641
5642 if (const auto *Inc = FS->getInc()) {
5643 if (Inc->isValueDependent()) {
5644 if (!EvaluateDependentExpr(Inc, Info))
5645 return ESR_Failed;
5646 } else {
5647 FullExpressionRAII IncScope(Info);
5648 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5649 return ESR_Failed;
5650 }
5651 }
5652
5653 if (!IterScope.destroy())
5654 return ESR_Failed;
5655 }
5656 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5657 }
5658
5659 case Stmt::CXXForRangeStmtClass: {
5660 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5661 BlockScopeRAII Scope(Info);
5662
5663 // Evaluate the init-statement if present.
5664 if (FS->getInit()) {
5665 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5666 if (ESR != ESR_Succeeded) {
5667 if (ESR != ESR_Failed && !Scope.destroy())
5668 return ESR_Failed;
5669 return ESR;
5670 }
5671 }
5672
5673 // Initialize the __range variable.
5674 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5675 if (ESR != ESR_Succeeded) {
5676 if (ESR != ESR_Failed && !Scope.destroy())
5677 return ESR_Failed;
5678 return ESR;
5679 }
5680
5681 // In error-recovery cases it's possible to get here even if we failed to
5682 // synthesize the __begin and __end variables.
5683 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5684 return ESR_Failed;
5685
5686 // Create the __begin and __end iterators.
5687 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5688 if (ESR != ESR_Succeeded) {
5689 if (ESR != ESR_Failed && !Scope.destroy())
5690 return ESR_Failed;
5691 return ESR;
5692 }
5693 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5694 if (ESR != ESR_Succeeded) {
5695 if (ESR != ESR_Failed && !Scope.destroy())
5696 return ESR_Failed;
5697 return ESR;
5698 }
5699
5700 while (true) {
5701 // Condition: __begin != __end.
5702 {
5703 if (FS->getCond()->isValueDependent()) {
5704 EvaluateDependentExpr(FS->getCond(), Info);
5705 // We don't know whether to keep going or terminate the loop.
5706 return ESR_Failed;
5707 }
5708 bool Continue = true;
5709 FullExpressionRAII CondExpr(Info);
5710 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5711 return ESR_Failed;
5712 if (!Continue)
5713 break;
5714 }
5715
5716 // User's variable declaration, initialized by *__begin.
5717 BlockScopeRAII InnerScope(Info);
5718 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5719 if (ESR != ESR_Succeeded) {
5720 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5721 return ESR_Failed;
5722 return ESR;
5723 }
5724
5725 // Loop body.
5726 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5727 if (ESR != ESR_Continue) {
5728 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5729 return ESR_Failed;
5730 return ESR;
5731 }
5732 if (FS->getInc()->isValueDependent()) {
5733 if (!EvaluateDependentExpr(FS->getInc(), Info))
5734 return ESR_Failed;
5735 } else {
5736 // Increment: ++__begin
5737 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5738 return ESR_Failed;
5739 }
5740
5741 if (!InnerScope.destroy())
5742 return ESR_Failed;
5743 }
5744
5745 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5746 }
5747
5748 case Stmt::SwitchStmtClass:
5749 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5750
5751 case Stmt::ContinueStmtClass:
5752 return ESR_Continue;
5753
5754 case Stmt::BreakStmtClass:
5755 return ESR_Break;
5756
5757 case Stmt::LabelStmtClass:
5758 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5759
5760 case Stmt::AttributedStmtClass: {
5761 const auto *AS = cast<AttributedStmt>(S);
5762 const auto *SS = AS->getSubStmt();
5763 MSConstexprContextRAII ConstexprContext(
5764 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
5765 isa<ReturnStmt>(SS));
5766
5767 auto LO = Info.getASTContext().getLangOpts();
5768 if (LO.CXXAssumptions && !LO.MSVCCompat) {
5769 for (auto *Attr : AS->getAttrs()) {
5770 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
5771 if (!AA)
5772 continue;
5773
5774 auto *Assumption = AA->getAssumption();
5775 if (Assumption->isValueDependent())
5776 return ESR_Failed;
5777
5778 if (Assumption->HasSideEffects(Info.getASTContext()))
5779 continue;
5780
5781 bool Value;
5782 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
5783 return ESR_Failed;
5784 if (!Value) {
5785 Info.CCEDiag(Assumption->getExprLoc(),
5786 diag::note_constexpr_assumption_failed);
5787 return ESR_Failed;
5788 }
5789 }
5790 }
5791
5792 return EvaluateStmt(Result, Info, SS, Case);
5793 }
5794
5795 case Stmt::CaseStmtClass:
5796 case Stmt::DefaultStmtClass:
5797 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5798 case Stmt::CXXTryStmtClass:
5799 // Evaluate try blocks by evaluating all sub statements.
5800 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5801 }
5802}
5803
5804/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5805/// default constructor. If so, we'll fold it whether or not it's marked as
5806/// constexpr. If it is marked as constexpr, we will never implicitly define it,
5807/// so we need special handling.
5809 const CXXConstructorDecl *CD,
5810 bool IsValueInitialization) {
5811 if (!CD->isTrivial() || !CD->isDefaultConstructor())
5812 return false;
5813
5814 // Value-initialization does not call a trivial default constructor, so such a
5815 // call is a core constant expression whether or not the constructor is
5816 // constexpr.
5817 if (!CD->isConstexpr() && !IsValueInitialization) {
5818 if (Info.getLangOpts().CPlusPlus11) {
5819 // FIXME: If DiagDecl is an implicitly-declared special member function,
5820 // we should be much more explicit about why it's not constexpr.
5821 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5822 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5823 Info.Note(CD->getLocation(), diag::note_declared_at);
5824 } else {
5825 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5826 }
5827 }
5828 return true;
5829}
5830
5831/// CheckConstexprFunction - Check that a function can be called in a constant
5832/// expression.
5833static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5835 const FunctionDecl *Definition,
5836 const Stmt *Body) {
5837 // Potential constant expressions can contain calls to declared, but not yet
5838 // defined, constexpr functions.
5839 if (Info.checkingPotentialConstantExpression() && !Definition &&
5840 Declaration->isConstexpr())
5841 return false;
5842
5843 // Bail out if the function declaration itself is invalid. We will
5844 // have produced a relevant diagnostic while parsing it, so just
5845 // note the problematic sub-expression.
5846 if (Declaration->isInvalidDecl()) {
5847 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5848 return false;
5849 }
5850
5851 // DR1872: An instantiated virtual constexpr function can't be called in a
5852 // constant expression (prior to C++20). We can still constant-fold such a
5853 // call.
5854 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5855 cast<CXXMethodDecl>(Declaration)->isVirtual())
5856 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5857
5858 if (Definition && Definition->isInvalidDecl()) {
5859 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5860 return false;
5861 }
5862
5863 // Can we evaluate this function call?
5864 if (Definition && Body &&
5865 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
5866 Definition->hasAttr<MSConstexprAttr>())))
5867 return true;
5868
5869 if (Info.getLangOpts().CPlusPlus11) {
5870 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5871
5872 // If this function is not constexpr because it is an inherited
5873 // non-constexpr constructor, diagnose that directly.
5874 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5875 if (CD && CD->isInheritingConstructor()) {
5876 auto *Inherited = CD->getInheritedConstructor().getConstructor();
5877 if (!Inherited->isConstexpr())
5878 DiagDecl = CD = Inherited;
5879 }
5880
5881 // FIXME: If DiagDecl is an implicitly-declared special member function
5882 // or an inheriting constructor, we should be much more explicit about why
5883 // it's not constexpr.
5884 if (CD && CD->isInheritingConstructor())
5885 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5886 << CD->getInheritedConstructor().getConstructor()->getParent();
5887 else
5888 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5889 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5890 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5891 } else {
5892 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5893 }
5894 return false;
5895}
5896
5897namespace {
5898struct CheckDynamicTypeHandler {
5899 AccessKinds AccessKind;
5900 typedef bool result_type;
5901 bool failed() { return false; }
5902 bool found(APValue &Subobj, QualType SubobjType) { return true; }
5903 bool found(APSInt &Value, QualType SubobjType) { return true; }
5904 bool found(APFloat &Value, QualType SubobjType) { return true; }
5905};
5906} // end anonymous namespace
5907
5908/// Check that we can access the notional vptr of an object / determine its
5909/// dynamic type.
5910static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5911 AccessKinds AK, bool Polymorphic) {
5912 if (This.Designator.Invalid)
5913 return false;
5914
5915 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5916
5917 if (!Obj)
5918 return false;
5919
5920 if (!Obj.Value) {
5921 // The object is not usable in constant expressions, so we can't inspect
5922 // its value to see if it's in-lifetime or what the active union members
5923 // are. We can still check for a one-past-the-end lvalue.
5924 if (This.Designator.isOnePastTheEnd() ||
5925 This.Designator.isMostDerivedAnUnsizedArray()) {
5926 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5927 ? diag::note_constexpr_access_past_end
5928 : diag::note_constexpr_access_unsized_array)
5929 << AK;
5930 return false;
5931 } else if (Polymorphic) {
5932 // Conservatively refuse to perform a polymorphic operation if we would
5933 // not be able to read a notional 'vptr' value.
5934 APValue Val;
5935 This.moveInto(Val);
5936 QualType StarThisType =
5937 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5938 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5939 << AK << Val.getAsString(Info.Ctx, StarThisType);
5940 return false;
5941 }
5942 return true;
5943 }
5944
5945 CheckDynamicTypeHandler Handler{AK};
5946 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5947}
5948
5949/// Check that the pointee of the 'this' pointer in a member function call is
5950/// either within its lifetime or in its period of construction or destruction.
5951static bool
5953 const LValue &This,
5954 const CXXMethodDecl *NamedMember) {
5955 return checkDynamicType(
5956 Info, E, This,
5957 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5958}
5959
5961 /// The dynamic class type of the object.
5963 /// The corresponding path length in the lvalue.
5964 unsigned PathLength;
5965};
5966
5967static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5968 unsigned PathLength) {
5969 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5970 Designator.Entries.size() && "invalid path length");
5971 return (PathLength == Designator.MostDerivedPathLength)
5972 ? Designator.MostDerivedType->getAsCXXRecordDecl()
5973 : getAsBaseClass(Designator.Entries[PathLength - 1]);
5974}
5975
5976/// Determine the dynamic type of an object.
5977static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
5978 const Expr *E,
5979 LValue &This,
5980 AccessKinds AK) {
5981 // If we don't have an lvalue denoting an object of class type, there is no
5982 // meaningful dynamic type. (We consider objects of non-class type to have no
5983 // dynamic type.)
5984 if (!checkDynamicType(Info, E, This, AK, true))
5985 return std::nullopt;
5986
5987 // Refuse to compute a dynamic type in the presence of virtual bases. This
5988 // shouldn't happen other than in constant-folding situations, since literal
5989 // types can't have virtual bases.
5990 //
5991 // Note that consumers of DynamicType assume that the type has no virtual
5992 // bases, and will need modifications if this restriction is relaxed.
5993 const CXXRecordDecl *Class =
5994 This.Designator.MostDerivedType->getAsCXXRecordDecl();
5995 if (!Class || Class->getNumVBases()) {
5996 Info.FFDiag(E);
5997 return std::nullopt;
5998 }
5999
6000 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6001 // binary search here instead. But the overwhelmingly common case is that
6002 // we're not in the middle of a constructor, so it probably doesn't matter
6003 // in practice.
6004 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6005 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6006 PathLength <= Path.size(); ++PathLength) {
6007 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6008 Path.slice(0, PathLength))) {
6009 case ConstructionPhase::Bases:
6010 case ConstructionPhase::DestroyingBases:
6011 // We're constructing or destroying a base class. This is not the dynamic
6012 // type.
6013 break;
6014
6015 case ConstructionPhase::None:
6016 case ConstructionPhase::AfterBases:
6017 case ConstructionPhase::AfterFields:
6018 case ConstructionPhase::Destroying:
6019 // We've finished constructing the base classes and not yet started
6020 // destroying them again, so this is the dynamic type.
6021 return DynamicType{getBaseClassType(This.Designator, PathLength),
6022 PathLength};
6023 }
6024 }
6025
6026 // CWG issue 1517: we're constructing a base class of the object described by
6027 // 'This', so that object has not yet begun its period of construction and
6028 // any polymorphic operation on it results in undefined behavior.
6029 Info.FFDiag(E);
6030 return std::nullopt;
6031}
6032
6033/// Perform virtual dispatch.
6035 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6036 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6037 std::optional<DynamicType> DynType = ComputeDynamicType(
6038 Info, E, This,
6039 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
6040 if (!DynType)
6041 return nullptr;
6042
6043 // Find the final overrider. It must be declared in one of the classes on the
6044 // path from the dynamic type to the static type.
6045 // FIXME: If we ever allow literal types to have virtual base classes, that
6046 // won't be true.
6047 const CXXMethodDecl *Callee = Found;
6048 unsigned PathLength = DynType->PathLength;
6049 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6050 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6051 const CXXMethodDecl *Overrider =
6052 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6053 if (Overrider) {
6054 Callee = Overrider;
6055 break;
6056 }
6057 }
6058
6059 // C++2a [class.abstract]p6:
6060 // the effect of making a virtual call to a pure virtual function [...] is
6061 // undefined
6062 if (Callee->isPureVirtual()) {
6063 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6064 Info.Note(Callee->getLocation(), diag::note_declared_at);
6065 return nullptr;
6066 }
6067
6068 // If necessary, walk the rest of the path to determine the sequence of
6069 // covariant adjustment steps to apply.
6070 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6071 Found->getReturnType())) {
6072 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6073 for (unsigned CovariantPathLength = PathLength + 1;
6074 CovariantPathLength != This.Designator.Entries.size();
6075 ++CovariantPathLength) {
6076 const CXXRecordDecl *NextClass =
6077 getBaseClassType(This.Designator, CovariantPathLength);
6078 const CXXMethodDecl *Next =
6079 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6080 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6081 Next->getReturnType(), CovariantAdjustmentPath.back()))
6082 CovariantAdjustmentPath.push_back(Next->getReturnType());
6083 }
6084 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6085 CovariantAdjustmentPath.back()))
6086 CovariantAdjustmentPath.push_back(Found->getReturnType());
6087 }
6088
6089 // Perform 'this' adjustment.
6090 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6091 return nullptr;
6092
6093 return Callee;
6094}
6095
6096/// Perform the adjustment from a value returned by a virtual function to
6097/// a value of the statically expected type, which may be a pointer or
6098/// reference to a base class of the returned type.
6099static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6100 APValue &Result,
6102 assert(Result.isLValue() &&
6103 "unexpected kind of APValue for covariant return");
6104 if (Result.isNullPointer())
6105 return true;
6106
6107 LValue LVal;
6108 LVal.setFrom(Info.Ctx, Result);
6109
6110 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6111 for (unsigned I = 1; I != Path.size(); ++I) {
6112 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6113 assert(OldClass && NewClass && "unexpected kind of covariant return");
6114 if (OldClass != NewClass &&
6115 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6116 return false;
6117 OldClass = NewClass;
6118 }
6119
6120 LVal.moveInto(Result);
6121 return true;
6122}
6123
6124/// Determine whether \p Base, which is known to be a direct base class of
6125/// \p Derived, is a public base class.
6126static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6127 const CXXRecordDecl *Base) {
6128 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6129 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6130 if (BaseClass && declaresSameEntity(BaseClass, Base))
6131 return BaseSpec.getAccessSpecifier() == AS_public;
6132 }
6133 llvm_unreachable("Base is not a direct base of Derived");
6134}
6135
6136/// Apply the given dynamic cast operation on the provided lvalue.
6137///
6138/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6139/// to find a suitable target subobject.
6140static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6141 LValue &Ptr) {
6142 // We can't do anything with a non-symbolic pointer value.
6143 SubobjectDesignator &D = Ptr.Designator;
6144 if (D.Invalid)
6145 return false;
6146
6147 // C++ [expr.dynamic.cast]p6:
6148 // If v is a null pointer value, the result is a null pointer value.
6149 if (Ptr.isNullPointer() && !E->isGLValue())
6150 return true;
6151
6152 // For all the other cases, we need the pointer to point to an object within
6153 // its lifetime / period of construction / destruction, and we need to know
6154 // its dynamic type.
6155 std::optional<DynamicType> DynType =
6156 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6157 if (!DynType)
6158 return false;
6159
6160 // C++ [expr.dynamic.cast]p7:
6161 // If T is "pointer to cv void", then the result is a pointer to the most
6162 // derived object
6163 if (E->getType()->isVoidPointerType())
6164 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6165
6166 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
6167 assert(C && "dynamic_cast target is not void pointer nor class");
6168 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
6169
6170 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6171 // C++ [expr.dynamic.cast]p9:
6172 if (!E->isGLValue()) {
6173 // The value of a failed cast to pointer type is the null pointer value
6174 // of the required result type.
6175 Ptr.setNull(Info.Ctx, E->getType());
6176 return true;
6177 }
6178
6179 // A failed cast to reference type throws [...] std::bad_cast.
6180 unsigned DiagKind;
6181 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6182 DynType->Type->isDerivedFrom(C)))
6183 DiagKind = 0;
6184 else if (!Paths || Paths->begin() == Paths->end())
6185 DiagKind = 1;
6186 else if (Paths->isAmbiguous(CQT))
6187 DiagKind = 2;
6188 else {
6189 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6190 DiagKind = 3;
6191 }
6192 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6193 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6194 << Info.Ctx.getRecordType(DynType->Type)
6196 return false;
6197 };
6198
6199 // Runtime check, phase 1:
6200 // Walk from the base subobject towards the derived object looking for the
6201 // target type.
6202 for (int PathLength = Ptr.Designator.Entries.size();
6203 PathLength >= (int)DynType->PathLength; --PathLength) {
6204 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6206 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6207 // We can only walk across public inheritance edges.
6208 if (PathLength > (int)DynType->PathLength &&
6209 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6210 Class))
6211 return RuntimeCheckFailed(nullptr);
6212 }
6213
6214 // Runtime check, phase 2:
6215 // Search the dynamic type for an unambiguous public base of type C.
6216 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6217 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6218 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6219 Paths.front().Access == AS_public) {
6220 // Downcast to the dynamic type...
6221 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6222 return false;
6223 // ... then upcast to the chosen base class subobject.
6224 for (CXXBasePathElement &Elem : Paths.front())
6225 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6226 return false;
6227 return true;
6228 }
6229
6230 // Otherwise, the runtime check fails.
6231 return RuntimeCheckFailed(&Paths);
6232}
6233
6234namespace {
6235struct StartLifetimeOfUnionMemberHandler {
6236 EvalInfo &Info;
6237 const Expr *LHSExpr;
6238 const FieldDecl *Field;
6239 bool DuringInit;
6240 bool Failed = false;
6241 static const AccessKinds AccessKind = AK_Assign;
6242
6243 typedef bool result_type;
6244 bool failed() { return Failed; }
6245 bool found(APValue &Subobj, QualType SubobjType) {
6246 // We are supposed to perform no initialization but begin the lifetime of
6247 // the object. We interpret that as meaning to do what default
6248 // initialization of the object would do if all constructors involved were
6249 // trivial:
6250 // * All base, non-variant member, and array element subobjects' lifetimes
6251 // begin
6252 // * No variant members' lifetimes begin
6253 // * All scalar subobjects whose lifetimes begin have indeterminate values
6254 assert(SubobjType->isUnionType());
6255 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6256 // This union member is already active. If it's also in-lifetime, there's
6257 // nothing to do.
6258 if (Subobj.getUnionValue().hasValue())
6259 return true;
6260 } else if (DuringInit) {
6261 // We're currently in the process of initializing a different union
6262 // member. If we carried on, that initialization would attempt to
6263 // store to an inactive union member, resulting in undefined behavior.
6264 Info.FFDiag(LHSExpr,
6265 diag::note_constexpr_union_member_change_during_init);
6266 return false;
6267 }
6268 APValue Result;
6269 Failed = !handleDefaultInitValue(Field->getType(), Result);
6270 Subobj.setUnion(Field, Result);
6271 return true;
6272 }
6273 bool found(APSInt &Value, QualType SubobjType) {
6274 llvm_unreachable("wrong value kind for union object");
6275 }
6276 bool found(APFloat &Value, QualType SubobjType) {
6277 llvm_unreachable("wrong value kind for union object");
6278 }
6279};
6280} // end anonymous namespace
6281
6282const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6283
6284/// Handle a builtin simple-assignment or a call to a trivial assignment
6285/// operator whose left-hand side might involve a union member access. If it
6286/// does, implicitly start the lifetime of any accessed union elements per
6287/// C++20 [class.union]5.
6288static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6289 const Expr *LHSExpr,
6290 const LValue &LHS) {
6291 if (LHS.InvalidBase || LHS.Designator.Invalid)
6292 return false;
6293
6295 // C++ [class.union]p5:
6296 // define the set S(E) of subexpressions of E as follows:
6297 unsigned PathLength = LHS.Designator.Entries.size();
6298 for (const Expr *E = LHSExpr; E != nullptr;) {
6299 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6300 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6301 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6302 // Note that we can't implicitly start the lifetime of a reference,
6303 // so we don't need to proceed any further if we reach one.
6304 if (!FD || FD->getType()->isReferenceType())
6305 break;
6306
6307 // ... and also contains A.B if B names a union member ...
6308 if (FD->getParent()->isUnion()) {
6309 // ... of a non-class, non-array type, or of a class type with a
6310 // trivial default constructor that is not deleted, or an array of
6311 // such types.
6312 auto *RD =
6313 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6314 if (!RD || RD->hasTrivialDefaultConstructor())
6315 UnionPathLengths.push_back({PathLength - 1, FD});
6316 }
6317
6318 E = ME->getBase();
6319 --PathLength;
6320 assert(declaresSameEntity(FD,
6321 LHS.Designator.Entries[PathLength]
6322 .getAsBaseOrMember().getPointer()));
6323
6324 // -- If E is of the form A[B] and is interpreted as a built-in array
6325 // subscripting operator, S(E) is [S(the array operand, if any)].
6326 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6327 // Step over an ArrayToPointerDecay implicit cast.
6328 auto *Base = ASE->getBase()->IgnoreImplicit();
6329 if (!Base->getType()->isArrayType())
6330 break;
6331
6332 E = Base;
6333 --PathLength;
6334
6335 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6336 // Step over a derived-to-base conversion.
6337 E = ICE->getSubExpr();
6338 if (ICE->getCastKind() == CK_NoOp)
6339 continue;
6340 if (ICE->getCastKind() != CK_DerivedToBase &&
6341 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6342 break;
6343 // Walk path backwards as we walk up from the base to the derived class.
6344 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6345 if (Elt->isVirtual()) {
6346 // A class with virtual base classes never has a trivial default
6347 // constructor, so S(E) is empty in this case.
6348 E = nullptr;
6349 break;
6350 }
6351
6352 --PathLength;
6353 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6354 LHS.Designator.Entries[PathLength]
6355 .getAsBaseOrMember().getPointer()));
6356 }
6357
6358 // -- Otherwise, S(E) is empty.
6359 } else {
6360 break;
6361 }
6362 }
6363
6364 // Common case: no unions' lifetimes are started.
6365 if (UnionPathLengths.empty())
6366 return true;
6367
6368 // if modification of X [would access an inactive union member], an object
6369 // of the type of X is implicitly created
6370 CompleteObject Obj =
6371 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6372 if (!Obj)
6373 return false;
6374 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6375 llvm::reverse(UnionPathLengths)) {
6376 // Form a designator for the union object.
6377 SubobjectDesignator D = LHS.Designator;
6378 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6379
6380 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6381 ConstructionPhase::AfterBases;
6382 StartLifetimeOfUnionMemberHandler StartLifetime{
6383 Info, LHSExpr, LengthAndField.second, DuringInit};
6384 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6385 return false;
6386 }
6387
6388 return true;
6389}
6390
6391static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6392 CallRef Call, EvalInfo &Info,
6393 bool NonNull = false) {
6394 LValue LV;
6395 // Create the parameter slot and register its destruction. For a vararg
6396 // argument, create a temporary.
6397 // FIXME: For calling conventions that destroy parameters in the callee,
6398 // should we consider performing destruction when the function returns
6399 // instead?
6400 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6401 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6402 ScopeKind::Call, LV);
6403 if (!EvaluateInPlace(V, Info, LV, Arg))
6404 return false;
6405
6406 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6407 // undefined behavior, so is non-constant.
6408 if (NonNull && V.isLValue() && V.isNullPointer()) {
6409 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6410 return false;
6411 }
6412
6413 return true;
6414}
6415
6416/// Evaluate the arguments to a function call.
6417static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6418 EvalInfo &Info, const FunctionDecl *Callee,
6419 bool RightToLeft = false) {
6420 bool Success = true;
6421 llvm::SmallBitVector ForbiddenNullArgs;
6422 if (Callee->hasAttr<NonNullAttr>()) {
6423 ForbiddenNullArgs.resize(Args.size());
6424 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6425 if (!Attr->args_size()) {
6426 ForbiddenNullArgs.set();
6427 break;
6428 } else
6429 for (auto Idx : Attr->args()) {
6430 unsigned ASTIdx = Idx.getASTIndex();
6431 if (ASTIdx >= Args.size())
6432 continue;
6433 ForbiddenNullArgs[ASTIdx] = true;
6434 }
6435 }
6436 }
6437 for (unsigned I = 0; I < Args.size(); I++) {
6438 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6439 const ParmVarDecl *PVD =
6440 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6441 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6442 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6443 // If we're checking for a potential constant expression, evaluate all
6444 // initializers even if some of them fail.
6445 if (!Info.noteFailure())
6446 return false;
6447 Success = false;
6448 }
6449 }
6450 return Success;
6451}
6452
6453/// Perform a trivial copy from Param, which is the parameter of a copy or move
6454/// constructor or assignment operator.
6455static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6456 const Expr *E, APValue &Result,
6457 bool CopyObjectRepresentation) {
6458 // Find the reference argument.
6459 CallStackFrame *Frame = Info.CurrentCall;
6460 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6461 if (!RefValue) {
6462 Info.FFDiag(E);
6463 return false;
6464 }
6465
6466 // Copy out the contents of the RHS object.
6467 LValue RefLValue;
6468 RefLValue.setFrom(Info.Ctx, *RefValue);
6470 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6471 CopyObjectRepresentation);
6472}
6473
6474/// Evaluate a function call.
6476 const FunctionDecl *Callee, const LValue *This,
6477 const Expr *E, ArrayRef<const Expr *> Args,
6478 CallRef Call, const Stmt *Body, EvalInfo &Info,
6479 APValue &Result, const LValue *ResultSlot) {
6480 if (!Info.CheckCallLimit(CallLoc))
6481 return false;
6482
6483 CallStackFrame Frame(Info, E->getSourceRange(), Callee, This, E, Call);
6484
6485 // For a trivial copy or move assignment, perform an APValue copy. This is
6486 // essential for unions, where the operations performed by the assignment
6487 // operator cannot be represented as statements.
6488 //
6489 // Skip this for non-union classes with no fields; in that case, the defaulted
6490 // copy/move does not actually read the object.
6491 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6492 if (MD && MD->isDefaulted() &&
6493 (MD->getParent()->isUnion() ||
6494 (MD->isTrivial() &&
6496 assert(This &&
6498 APValue RHSValue;
6499 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6500 MD->getParent()->isUnion()))
6501 return false;
6502 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6503 RHSValue))
6504 return false;
6505 This->moveInto(Result);
6506 return true;
6507 } else if (MD && isLambdaCallOperator(MD)) {
6508 // We're in a lambda; determine the lambda capture field maps unless we're
6509 // just constexpr checking a lambda's call operator. constexpr checking is
6510 // done before the captures have been added to the closure object (unless
6511 // we're inferring constexpr-ness), so we don't have access to them in this
6512 // case. But since we don't need the captures to constexpr check, we can
6513 // just ignore them.
6514 if (!Info.checkingPotentialConstantExpression())
6515 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6516 Frame.LambdaThisCaptureField);
6517 }
6518
6519 StmtResult Ret = {Result, ResultSlot};
6520 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6521 if (ESR == ESR_Succeeded) {
6522 if (Callee->getReturnType()->isVoidType())
6523 return true;
6524 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6525 }
6526 return ESR == ESR_Returned;
6527}
6528
6529/// Evaluate a constructor call.
6530static bool HandleConstructorCall(const Expr *E, const LValue &This,
6531 CallRef Call,
6533 EvalInfo &Info, APValue &Result) {
6534 SourceLocation CallLoc = E->getExprLoc();
6535 if (!Info.CheckCallLimit(CallLoc))
6536 return false;
6537
6538 const CXXRecordDecl *RD = Definition->getParent();
6539 if (RD->getNumVBases()) {
6540 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6541 return false;
6542 }
6543
6544 EvalInfo::EvaluatingConstructorRAII EvalObj(
6545 Info,
6546 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6547 RD->getNumBases());
6548 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
6549
6550 // FIXME: Creating an APValue just to hold a nonexistent return value is
6551 // wasteful.
6552 APValue RetVal;
6553 StmtResult Ret = {RetVal, nullptr};
6554
6555 // If it's a delegating constructor, delegate.
6556 if (Definition->isDelegatingConstructor()) {
6558 if ((*I)->getInit()->isValueDependent()) {
6559 if (!EvaluateDependentExpr((*I)->getInit(), Info))
6560 return false;
6561 } else {
6562 FullExpressionRAII InitScope(Info);
6563 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6564 !InitScope.destroy())
6565 return false;
6566 }
6567 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6568 }
6569
6570 // For a trivial copy or move constructor, perform an APValue copy. This is
6571 // essential for unions (or classes with anonymous union members), where the
6572 // operations performed by the constructor cannot be represented by
6573 // ctor-initializers.
6574 //
6575 // Skip this for empty non-union classes; we should not perform an
6576 // lvalue-to-rvalue conversion on them because their copy constructor does not
6577 // actually read them.
6578 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6579 (Definition->getParent()->isUnion() ||
6580 (Definition->isTrivial() &&
6582 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6583 Definition->getParent()->isUnion());
6584 }
6585
6586 // Reserve space for the struct members.
6587 if (!Result.hasValue()) {
6588 if (!RD->isUnion())
6589 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6590 std::distance(RD->field_begin(), RD->field_end()));
6591 else
6592 // A union starts with no active member.
6593 Result = APValue((const FieldDecl*)nullptr);
6594 }
6595
6596 if (RD->isInvalidDecl()) return false;
6597 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6598
6599 // A scope for temporaries lifetime-extended by reference members.
6600 BlockScopeRAII LifetimeExtendedScope(Info);
6601
6602 bool Success = true;
6603 unsigned BasesSeen = 0;
6604#ifndef NDEBUG
6606#endif
6608 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6609 // We might be initializing the same field again if this is an indirect
6610 // field initialization.
6611 if (FieldIt == RD->field_end() ||
6612 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6613 assert(Indirect && "fields out of order?");
6614 return;
6615 }
6616
6617 // Default-initialize any fields with no explicit initializer.
6618 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6619 assert(FieldIt != RD->field_end() && "missing field?");
6620 if (!FieldIt->isUnnamedBitField())
6622 FieldIt->getType(),
6623 Result.getStructField(FieldIt->getFieldIndex()));
6624 }
6625 ++FieldIt;
6626 };
6627 for (const auto *I : Definition->inits()) {
6628 LValue Subobject = This;
6629 LValue SubobjectParent = This;
6630 APValue *Value = &Result;
6631
6632 // Determine the subobject to initialize.
6633 FieldDecl *FD = nullptr;
6634 if (I->isBaseInitializer()) {
6635 QualType BaseType(I->getBaseClass(), 0);
6636#ifndef NDEBUG
6637 // Non-virtual base classes are initialized in the order in the class
6638 // definition. We have already checked for virtual base classes.
6639 assert(!BaseIt->isVirtual() && "virtual base for literal type");
6640 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
6641 "base class initializers not in expected order");
6642 ++BaseIt;
6643#endif
6644 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6645 BaseType->getAsCXXRecordDecl(), &Layout))
6646 return false;
6647 Value = &Result.getStructBase(BasesSeen++);
6648 } else if ((FD = I->getMember())) {
6649 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6650 return false;
6651 if (RD->isUnion()) {
6652 Result = APValue(FD);
6653 Value = &Result.getUnionValue();
6654 } else {
6655 SkipToField(FD, false);
6656 Value = &Result.getStructField(FD->getFieldIndex());
6657 }
6658 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6659 // Walk the indirect field decl's chain to find the object to initialize,
6660 // and make sure we've initialized every step along it.
6661 auto IndirectFieldChain = IFD->chain();
6662 for (auto *C : IndirectFieldChain) {
6663 FD = cast<FieldDecl>(C);
6664 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6665 // Switch the union field if it differs. This happens if we had
6666 // preceding zero-initialization, and we're now initializing a union
6667 // subobject other than the first.
6668 // FIXME: In this case, the values of the other subobjects are
6669 // specified, since zero-initialization sets all padding bits to zero.
6670 if (!Value->hasValue() ||
6671 (Value->isUnion() && Value->getUnionField() != FD)) {
6672 if (CD->isUnion())
6673 *Value = APValue(FD);
6674 else
6675 // FIXME: This immediately starts the lifetime of all members of
6676 // an anonymous struct. It would be preferable to strictly start
6677 // member lifetime in initialization order.
6678 Success &=
6679 handleDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6680 }
6681 // Store Subobject as its parent before updating it for the last element
6682 // in the chain.
6683 if (C == IndirectFieldChain.back())
6684 SubobjectParent = Subobject;
6685 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6686 return false;
6687 if (CD->isUnion())
6688 Value = &Value->getUnionValue();
6689 else {
6690 if (C == IndirectFieldChain.front() && !RD->isUnion())
6691 SkipToField(FD, true);
6692 Value = &Value->getStructField(FD->getFieldIndex());
6693 }
6694 }
6695 } else {
6696 llvm_unreachable("unknown base initializer kind");
6697 }
6698
6699 // Need to override This for implicit field initializers as in this case
6700 // This refers to innermost anonymous struct/union containing initializer,
6701 // not to currently constructed class.
6702 const Expr *Init = I->getInit();
6703 if (Init->isValueDependent()) {
6704 if (!EvaluateDependentExpr(Init, Info))
6705 return false;
6706 } else {
6707 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6708 isa<CXXDefaultInitExpr>(Init));
6709 FullExpressionRAII InitScope(Info);
6710 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6711 (FD && FD->isBitField() &&
6712 !truncateBitfieldValue(Info, Init, *Value, FD))) {
6713 // If we're checking for a potential constant expression, evaluate all
6714 // initializers even if some of them fail.
6715 if (!Info.noteFailure())
6716 return false;
6717 Success = false;
6718 }
6719 }
6720
6721 // This is the point at which the dynamic type of the object becomes this
6722 // class type.
6723 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6724 EvalObj.finishedConstructingBases();
6725 }
6726
6727 // Default-initialize any remaining fields.
6728 if (!RD->isUnion()) {
6729 for (; FieldIt != RD->field_end(); ++FieldIt) {
6730 if (!FieldIt->isUnnamedBitField())
6732 FieldIt->getType(),
6733 Result.getStructField(FieldIt->getFieldIndex()));
6734 }
6735 }
6736
6737 EvalObj.finishedConstructingFields();
6738
6739 return Success &&
6740 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6741 LifetimeExtendedScope.destroy();
6742}
6743
6744static bool HandleConstructorCall(const Expr *E, const LValue &This,
6747 EvalInfo &Info, APValue &Result) {
6748 CallScopeRAII CallScope(Info);
6749 CallRef Call = Info.CurrentCall->createCall(Definition);
6750 if (!EvaluateArgs(Args, Call, Info, Definition))
6751 return false;
6752
6753 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6754 CallScope.destroy();
6755}
6756
6757static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
6758 const LValue &This, APValue &Value,
6759 QualType T) {
6760 // Objects can only be destroyed while they're within their lifetimes.
6761 // FIXME: We have no representation for whether an object of type nullptr_t
6762 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6763 // as indeterminate instead?
6764 if (Value.isAbsent() && !T->isNullPtrType()) {
6765 APValue Printable;
6766 This.moveInto(Printable);
6767 Info.FFDiag(CallRange.getBegin(),
6768 diag::note_constexpr_destroy_out_of_lifetime)
6769 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6770 return false;
6771 }
6772
6773 // Invent an expression for location purposes.
6774 // FIXME: We shouldn't need to do this.
6775 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
6776
6777 // For arrays, destroy elements right-to-left.
6778 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6779 uint64_t Size = CAT->getZExtSize();
6780 QualType ElemT = CAT->getElementType();
6781
6782 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
6783 return false;
6784
6785 LValue ElemLV = This;
6786 ElemLV.addArray(Info, &LocE, CAT);
6787 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6788 return false;
6789
6790 // Ensure that we have actual array elements available to destroy; the
6791 // destructors might mutate the value, so we can't run them on the array
6792 // filler.
6793 if (Size && Size > Value.getArrayInitializedElts())
6794 expandArray(Value, Value.getArraySize() - 1);
6795
6796 // The size of the array might have been reduced by
6797 // a placement new.
6798 for (Size = Value.getArraySize(); Size != 0; --Size) {
6799 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6800 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6801 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
6802 return false;
6803 }
6804
6805 // End the lifetime of this array now.
6806 Value = APValue();
6807 return true;
6808 }
6809
6810 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6811 if (!RD) {
6812 if (T.isDestructedType()) {
6813 Info.FFDiag(CallRange.getBegin(),
6814 diag::note_constexpr_unsupported_destruction)
6815 << T;
6816 return false;
6817 }
6818
6819 Value = APValue();
6820 return true;
6821 }
6822
6823 if (RD->getNumVBases()) {
6824 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
6825 return false;
6826 }
6827
6828 const CXXDestructorDecl *DD = RD->getDestructor();
6829 if (!DD && !RD->hasTrivialDestructor()) {
6830 Info.FFDiag(CallRange.getBegin());
6831 return false;
6832 }
6833
6834 if (!DD || DD->isTrivial() ||
6835 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6836 // A trivial destructor just ends the lifetime of the object. Check for
6837 // this case before checking for a body, because we might not bother
6838 // building a body for a trivial destructor. Note that it doesn't matter
6839 // whether the destructor is constexpr in this case; all trivial
6840 // destructors are constexpr.
6841 //
6842 // If an anonymous union would be destroyed, some enclosing destructor must
6843 // have been explicitly defined, and the anonymous union destruction should
6844 // have no effect.
6845 Value = APValue();
6846 return true;
6847 }
6848
6849 if (!Info.CheckCallLimit(CallRange.getBegin()))
6850 return false;
6851
6852 const FunctionDecl *Definition = nullptr;
6853 const Stmt *Body = DD->getBody(Definition);
6854
6855 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
6856 return false;
6857
6858 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
6859 CallRef());
6860
6861 // We're now in the period of destruction of this object.
6862 unsigned BasesLeft = RD->getNumBases();
6863 EvalInfo::EvaluatingDestructorRAII EvalObj(
6864 Info,
6865 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6866 if (!EvalObj.DidInsert) {
6867 // C++2a [class.dtor]p19:
6868 // the behavior is undefined if the destructor is invoked for an object
6869 // whose lifetime has ended
6870 // (Note that formally the lifetime ends when the period of destruction
6871 // begins, even though certain uses of the object remain valid until the
6872 // period of destruction ends.)
6873 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
6874 return false;
6875 }
6876
6877 // FIXME: Creating an APValue just to hold a nonexistent return value is
6878 // wasteful.
6879 APValue RetVal;
6880 StmtResult Ret = {RetVal, nullptr};
6881 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6882 return false;
6883
6884 // A union destructor does not implicitly destroy its members.
6885 if (RD->isUnion())
6886 return true;
6887
6888 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6889
6890 // We don't have a good way to iterate fields in reverse, so collect all the
6891 // fields first and then walk them backwards.
6892 SmallVector<FieldDecl*, 16> Fields(RD->fields());
6893 for (const FieldDecl *FD : llvm::reverse(Fields)) {
6894 if (FD->isUnnamedBitField())
6895 continue;
6896
6897 LValue Subobject = This;
6898 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6899 return false;
6900
6901 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6902 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
6903 FD->getType()))
6904 return false;
6905 }
6906
6907 if (BasesLeft != 0)
6908 EvalObj.startedDestroyingBases();
6909
6910 // Destroy base classes in reverse order.
6911 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6912 --BasesLeft;
6913
6914 QualType BaseType = Base.getType();
6915 LValue Subobject = This;
6916 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6917 BaseType->getAsCXXRecordDecl(), &Layout))
6918 return false;
6919
6920 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6921 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
6922 BaseType))
6923 return false;
6924 }
6925 assert(BasesLeft == 0 && "NumBases was wrong?");
6926
6927 // The period of destruction ends now. The object is gone.
6928 Value = APValue();
6929 return true;
6930}
6931
6932namespace {
6933struct DestroyObjectHandler {
6934 EvalInfo &Info;
6935 const Expr *E;
6936 const LValue &This;
6937 const AccessKinds AccessKind;
6938
6939 typedef bool result_type;
6940 bool failed() { return false; }
6941 bool found(APValue &Subobj, QualType SubobjType) {
6942 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
6943 SubobjType);
6944 }
6945 bool found(APSInt &Value, QualType SubobjType) {
6946 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6947 return false;
6948 }
6949 bool found(APFloat &Value, QualType SubobjType) {
6950 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6951 return false;
6952 }
6953};
6954}
6955
6956/// Perform a destructor or pseudo-destructor call on the given object, which
6957/// might in general not be a complete object.
6958static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6959 const LValue &This, QualType ThisType) {
6960 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6961 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6962 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6963}
6964
6965/// Destroy and end the lifetime of the given complete object.
6966static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6968 QualType T) {
6969 // If we've had an unmodeled side-effect, we can't rely on mutable state
6970 // (such as the object we're about to destroy) being correct.
6971 if (Info.EvalStatus.HasSideEffects)
6972 return false;
6973
6974 LValue LV;
6975 LV.set({LVBase});
6976 return HandleDestructionImpl(Info, Loc, LV, Value, T);
6977}
6978
6979/// Perform a call to 'operator new' or to `__builtin_operator_new'.
6980static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6981 LValue &Result) {
6982 if (Info.checkingPotentialConstantExpression() ||
6983 Info.SpeculativeEvaluationDepth)
6984 return false;
6985
6986 // This is permitted only within a call to std::allocator<T>::allocate.
6987 auto Caller = Info.getStdAllocatorCaller("allocate");
6988 if (!Caller) {
6989 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6990 ? diag::note_constexpr_new_untyped
6991 : diag::note_constexpr_new);
6992 return false;
6993 }
6994
6995 QualType ElemType = Caller.ElemType;
6996 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6997 Info.FFDiag(E->getExprLoc(),
6998 diag::note_constexpr_new_not_complete_object_type)
6999 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7000 return false;
7001 }
7002
7003 APSInt ByteSize;
7004 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7005 return false;
7006 bool IsNothrow = false;
7007 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7008 EvaluateIgnoredValue(Info, E->getArg(I));
7009 IsNothrow |= E->getType()->isNothrowT();
7010 }
7011
7012 CharUnits ElemSize;
7013 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7014 return false;
7015 APInt Size, Remainder;
7016 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7017 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7018 if (Remainder != 0) {
7019 // This likely indicates a bug in the implementation of 'std::allocator'.
7020 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7021 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7022 return false;
7023 }
7024
7025 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7026 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7027 if (IsNothrow) {
7028 Result.setNull(Info.Ctx, E->getType());
7029 return true;
7030 }
7031 return false;
7032 }
7033
7034 QualType AllocType = Info.Ctx.getConstantArrayType(
7035 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7036 APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
7037 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7038 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7039 return true;
7040}
7041
7043 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7044 if (CXXDestructorDecl *DD = RD->getDestructor())
7045 return DD->isVirtual();
7046 return false;
7047}
7048
7050 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7051 if (CXXDestructorDecl *DD = RD->getDestructor())
7052 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7053 return nullptr;
7054}
7055
7056/// Check that the given object is a suitable pointer to a heap allocation that
7057/// still exists and is of the right kind for the purpose of a deletion.
7058///
7059/// On success, returns the heap allocation to deallocate. On failure, produces
7060/// a diagnostic and returns std::nullopt.
7061static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7062 const LValue &Pointer,
7063 DynAlloc::Kind DeallocKind) {
7064 auto PointerAsString = [&] {
7065 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7066 };
7067
7068 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7069 if (!DA) {
7070 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7071 << PointerAsString();
7072 if (Pointer.Base)
7073 NoteLValueLocation(Info, Pointer.Base);
7074 return std::nullopt;
7075 }
7076
7077 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7078 if (!Alloc) {
7079 Info.FFDiag(E, diag::note_constexpr_double_delete);
7080 return std::nullopt;
7081 }
7082
7083 if (DeallocKind != (*Alloc)->getKind()) {
7084 QualType AllocType = Pointer.Base.getDynamicAllocType();
7085 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7086 << DeallocKind << (*Alloc)->getKind() << AllocType;
7087 NoteLValueLocation(Info, Pointer.Base);
7088 return std::nullopt;
7089 }
7090
7091 bool Subobject = false;
7092 if (DeallocKind == DynAlloc::New) {
7093 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7094 Pointer.Designator.isOnePastTheEnd();
7095 } else {
7096 Subobject = Pointer.Designator.Entries.size() != 1 ||
7097 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7098 }
7099 if (Subobject) {
7100 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7101 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7102 return std::nullopt;
7103 }
7104
7105 return Alloc;
7106}
7107
7108// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7109static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7110 if (Info.checkingPotentialConstantExpression() ||
7111 Info.SpeculativeEvaluationDepth)
7112 return false;
7113
7114 // This is permitted only within a call to std::allocator<T>::deallocate.
7115 if (!Info.getStdAllocatorCaller("deallocate")) {
7116 Info.FFDiag(E->getExprLoc());
7117 return true;
7118 }
7119
7120 LValue Pointer;
7121 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7122 return false;
7123 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7124 EvaluateIgnoredValue(Info, E->getArg(I));
7125
7126 if (Pointer.Designator.Invalid)
7127 return false;
7128
7129 // Deleting a null pointer would have no effect, but it's not permitted by
7130 // std::allocator<T>::deallocate's contract.
7131 if (Pointer.isNullPointer()) {
7132 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7133 return true;
7134 }
7135
7136 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7137 return false;
7138
7139 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7140 return true;
7141}
7142
7143//===----------------------------------------------------------------------===//
7144// Generic Evaluation
7145//===----------------------------------------------------------------------===//
7146namespace {
7147
7148class BitCastBuffer {
7149 // FIXME: We're going to need bit-level granularity when we support
7150 // bit-fields.
7151 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7152 // we don't support a host or target where that is the case. Still, we should
7153 // use a more generic type in case we ever do.
7155
7156 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7157 "Need at least 8 bit unsigned char");
7158
7159 bool TargetIsLittleEndian;
7160
7161public:
7162 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7163 : Bytes(Width.getQuantity()),
7164 TargetIsLittleEndian(TargetIsLittleEndian) {}
7165
7166 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7167 SmallVectorImpl<unsigned char> &Output) const {
7168 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7169 // If a byte of an integer is uninitialized, then the whole integer is
7170 // uninitialized.
7171 if (!Bytes[I.getQuantity()])
7172 return false;
7173 Output.push_back(*Bytes[I.getQuantity()]);
7174 }
7175 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7176 std::reverse(Output.begin(), Output.end());
7177 return true;
7178 }
7179
7180 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7181 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7182 std::reverse(Input.begin(), Input.end());
7183
7184 size_t Index = 0;
7185 for (unsigned char Byte : Input) {
7186 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7187 Bytes[Offset.getQuantity() + Index] = Byte;
7188 ++Index;
7189 }
7190 }
7191
7192 size_t size() { return Bytes.size(); }
7193};
7194
7195/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7196/// target would represent the value at runtime.
7197class APValueToBufferConverter {
7198 EvalInfo &Info;
7199 BitCastBuffer Buffer;
7200 const CastExpr *BCE;
7201
7202 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7203 const CastExpr *BCE)
7204 : Info(Info),
7205 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7206 BCE(BCE) {}
7207
7208 bool visit(const APValue &Val, QualType Ty) {
7209 return visit(Val, Ty, CharUnits::fromQuantity(0));
7210 }
7211
7212 // Write out Val with type Ty into Buffer starting at Offset.
7213 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7214 assert((size_t)Offset.getQuantity() <= Buffer.size());
7215
7216 // As a special case, nullptr_t has an indeterminate value.
7217 if (Ty->isNullPtrType())
7218 return true;
7219
7220 // Dig through Src to find the byte at SrcOffset.
7221 switch (Val.getKind()) {
7223 case APValue::None:
7224 return true;
7225
7226 case APValue::Int:
7227 return visitInt(Val.getInt(), Ty, Offset);
7228 case APValue::Float:
7229 return visitFloat(Val.getFloat(), Ty, Offset);
7230 case APValue::Array:
7231 return visitArray(Val, Ty, Offset);
7232 case APValue::Struct:
7233 return visitRecord(Val, Ty, Offset);
7234 case APValue::Vector:
7235 return visitVector(Val, Ty, Offset);
7236
7239 return visitComplex(Val, Ty, Offset);
7241 // FIXME: We should support these.
7242
7243 case APValue::Union:
7246 Info.FFDiag(BCE->getBeginLoc(),
7247 diag::note_constexpr_bit_cast_unsupported_type)
7248 << Ty;
7249 return false;
7250 }
7251
7252 case APValue::LValue:
7253 llvm_unreachable("LValue subobject in bit_cast?");
7254 }
7255 llvm_unreachable("Unhandled APValue::ValueKind");
7256 }
7257
7258 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7259 const RecordDecl *RD = Ty->getAsRecordDecl();
7260 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7261
7262 // Visit the base classes.
7263 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7264 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7265 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7266 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7267
7268 if (!visitRecord(Val.getStructBase(I), BS.getType(),
7269 Layout.getBaseClassOffset(BaseDecl) + Offset))
7270 return false;
7271 }
7272 }
7273
7274 // Visit the fields.
7275 unsigned FieldIdx = 0;
7276 for (FieldDecl *FD : RD->fields()) {
7277 if (FD->isBitField()) {
7278 Info.FFDiag(BCE->getBeginLoc(),
7279 diag::note_constexpr_bit_cast_unsupported_bitfield);
7280 return false;
7281 }
7282
7283 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7284
7285 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7286 "only bit-fields can have sub-char alignment");
7287 CharUnits FieldOffset =
7288 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7289 QualType FieldTy = FD->getType();
7290 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7291 return false;
7292 ++FieldIdx;
7293 }
7294
7295 return true;
7296 }
7297
7298 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7299 const auto *CAT =
7300 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7301 if (!CAT)
7302 return false;
7303
7304 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7305 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7306 unsigned ArraySize = Val.getArraySize();
7307 // First, initialize the initialized elements.
7308 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7309 const APValue &SubObj = Val.getArrayInitializedElt(I);
7310 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7311 return false;
7312 }
7313
7314 // Next, initialize the rest of the array using the filler.
7315 if (Val.hasArrayFiller()) {
7316 const APValue &Filler = Val.getArrayFiller();
7317 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7318 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7319 return false;
7320 }
7321 }
7322
7323 return true;
7324 }
7325
7326 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7327 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7328 QualType EltTy = ComplexTy->getElementType();
7329 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7330 bool IsInt = Val.isComplexInt();
7331
7332 if (IsInt) {
7333 if (!visitInt(Val.getComplexIntReal(), EltTy,
7334 Offset + (0 * EltSizeChars)))
7335 return false;
7336 if (!visitInt(Val.getComplexIntImag(), EltTy,
7337 Offset + (1 * EltSizeChars)))
7338 return false;
7339 } else {
7340 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7341 Offset + (0 * EltSizeChars)))
7342 return false;
7343 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7344 Offset + (1 * EltSizeChars)))
7345 return false;
7346 }
7347
7348 return true;
7349 }
7350
7351 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7352 const VectorType *VTy = Ty->castAs<VectorType>();
7353 QualType EltTy = VTy->getElementType();
7354 unsigned NElts = VTy->getNumElements();
7355
7356 if (VTy->isExtVectorBoolType()) {
7357 // Special handling for OpenCL bool vectors:
7358 // Since these vectors are stored as packed bits, but we can't write
7359 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7360 // together into an appropriately sized APInt and write them all out at
7361 // once. Because we don't accept vectors where NElts * EltSize isn't a
7362 // multiple of the char size, there will be no padding space, so we don't
7363 // have to worry about writing data which should have been left
7364 // uninitialized.
7365 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7366
7367 llvm::APInt Res = llvm::APInt::getZero(NElts);
7368 for (unsigned I = 0; I < NElts; ++I) {
7369 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7370 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7371 "bool vector element must be 1-bit unsigned integer!");
7372
7373 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7374 }
7375
7376 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7377 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7378 Buffer.writeObject(Offset, Bytes);
7379 } else {
7380 // Iterate over each of the elements and write them out to the buffer at
7381 // the appropriate offset.
7382 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7383 for (unsigned I = 0; I < NElts; ++I) {
7384 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7385 return false;
7386 }
7387 }
7388
7389 return true;
7390 }
7391
7392 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7393 APSInt AdjustedVal = Val;
7394 unsigned Width = AdjustedVal.getBitWidth();
7395 if (Ty->isBooleanType()) {
7396 Width = Info.Ctx.getTypeSize(Ty);
7397 AdjustedVal = AdjustedVal.extend(Width);
7398 }
7399
7400 SmallVector<uint8_t, 8> Bytes(Width / 8);
7401 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7402 Buffer.writeObject(Offset, Bytes);
7403 return true;
7404 }
7405
7406 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7407 APSInt AsInt(Val.bitcastToAPInt());
7408 return visitInt(AsInt, Ty, Offset);
7409 }
7410
7411public:
7412 static std::optional<BitCastBuffer>
7413 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7414 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7415 APValueToBufferConverter Converter(Info, DstSize, BCE);
7416 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7417 return std::nullopt;
7418 return Converter.Buffer;
7419 }
7420};
7421
7422/// Write an BitCastBuffer into an APValue.
7423class BufferToAPValueConverter {
7424 EvalInfo &Info;
7425 const BitCastBuffer &Buffer;
7426 const CastExpr *BCE;
7427
7428 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7429 const CastExpr *BCE)
7430 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7431
7432 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7433 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7434 // Ideally this will be unreachable.
7435 std::nullopt_t unsupportedType(QualType Ty) {
7436 Info.FFDiag(BCE->getBeginLoc(),
7437 diag::note_constexpr_bit_cast_unsupported_type)
7438 << Ty;
7439 return std::nullopt;
7440 }
7441
7442 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7443 Info.FFDiag(BCE->getBeginLoc(),
7444 diag::note_constexpr_bit_cast_unrepresentable_value)
7445 << Ty << toString(Val, /*Radix=*/10);
7446 return std::nullopt;
7447 }
7448
7449 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7450 const EnumType *EnumSugar = nullptr) {
7451 if (T->isNullPtrType()) {
7452 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7453 return APValue((Expr *)nullptr,
7454 /*Offset=*/CharUnits::fromQuantity(NullValue),
7455 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7456 }
7457
7458 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7459
7460 // Work around floating point types that contain unused padding bytes. This
7461 // is really just `long double` on x86, which is the only fundamental type
7462 // with padding bytes.
7463 if (T->isRealFloatingType()) {
7464 const llvm::fltSemantics &Semantics =
7465 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7466 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7467 assert(NumBits % 8 == 0);
7468 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7469 if (NumBytes != SizeOf)
7470 SizeOf = NumBytes;
7471 }
7472
7474 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7475 // If this is std::byte or unsigned char, then its okay to store an
7476 // indeterminate value.
7477 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7478 bool IsUChar =
7479 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7480 T->isSpecificBuiltinType(BuiltinType::Char_U));
7481 if (!IsStdByte && !IsUChar) {
7482 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7483 Info.FFDiag(BCE->getExprLoc(),
7484 diag::note_constexpr_bit_cast_indet_dest)
7485 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7486 return std::nullopt;
7487 }
7488
7490 }
7491
7492 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7493 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7494
7496 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7497
7498 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7499 if (IntWidth != Val.getBitWidth()) {
7500 APSInt Truncated = Val.trunc(IntWidth);
7501 if (Truncated.extend(Val.getBitWidth()) != Val)
7502 return unrepresentableValue(QualType(T, 0), Val);
7503 Val = Truncated;
7504 }
7505
7506 return APValue(Val);
7507 }
7508
7509 if (T->isRealFloatingType()) {
7510 const llvm::fltSemantics &Semantics =
7511 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7512 return APValue(APFloat(Semantics, Val));
7513 }
7514
7515 return unsupportedType(QualType(T, 0));
7516 }
7517
7518 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7519 const RecordDecl *RD = RTy->getAsRecordDecl();
7520 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7521
7522 unsigned NumBases = 0;
7523 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7524 NumBases = CXXRD->getNumBases();
7525
7526 APValue ResultVal(APValue::UninitStruct(), NumBases,
7527 std::distance(RD->field_begin(), RD->field_end()));
7528
7529 // Visit the base classes.
7530 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7531 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7532 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7533 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7534
7535 std::optional<APValue> SubObj = visitType(
7536 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7537 if (!SubObj)
7538 return std::nullopt;
7539 ResultVal.getStructBase(I) = *SubObj;
7540 }
7541 }
7542
7543 // Visit the fields.
7544 unsigned FieldIdx = 0;
7545 for (FieldDecl *FD : RD->fields()) {
7546 // FIXME: We don't currently support bit-fields. A lot of the logic for
7547 // this is in CodeGen, so we need to factor it around.
7548 if (FD->isBitField()) {
7549 Info.FFDiag(BCE->getBeginLoc(),
7550 diag::note_constexpr_bit_cast_unsupported_bitfield);
7551 return std::nullopt;
7552 }
7553
7554 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7555 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7556
7557 CharUnits FieldOffset =
7558 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7559 Offset;
7560 QualType FieldTy = FD->getType();
7561 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7562 if (!SubObj)
7563 return std::nullopt;
7564 ResultVal.getStructField(FieldIdx) = *SubObj;
7565 ++FieldIdx;
7566 }
7567
7568 return ResultVal;
7569 }
7570
7571 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7572 QualType RepresentationType = Ty->getDecl()->getIntegerType();
7573 assert(!RepresentationType.isNull() &&
7574 "enum forward decl should be caught by Sema");
7575 const auto *AsBuiltin =
7576 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7577 // Recurse into the underlying type. Treat std::byte transparently as
7578 // unsigned char.
7579 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7580 }
7581
7582 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7583 size_t Size = Ty->getLimitedSize();
7584 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7585
7586 APValue ArrayValue(APValue::UninitArray(), Size, Size);
7587 for (size_t I = 0; I != Size; ++I) {
7588 std::optional<APValue> ElementValue =
7589 visitType(Ty->getElementType(), Offset + I * ElementWidth);
7590 if (!ElementValue)
7591 return std::nullopt;
7592 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7593 }
7594
7595 return ArrayValue;
7596 }
7597
7598 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
7599 QualType ElementType = Ty->getElementType();
7600 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
7601 bool IsInt = ElementType->isIntegerType();
7602
7603 std::optional<APValue> Values[2];
7604 for (unsigned I = 0; I != 2; ++I) {
7605 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
7606 if (!Values[I])
7607 return std::nullopt;
7608 }
7609
7610 if (IsInt)
7611 return APValue(Values[0]->getInt(), Values[1]->getInt());
7612 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
7613 }
7614
7615 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
7616 QualType EltTy = VTy->getElementType();
7617 unsigned NElts = VTy->getNumElements();
7618 unsigned EltSize =
7619 VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);
7620
7622 Elts.reserve(NElts);
7623 if (VTy->isExtVectorBoolType()) {
7624 // Special handling for OpenCL bool vectors:
7625 // Since these vectors are stored as packed bits, but we can't read
7626 // individual bits from the BitCastBuffer, we'll buffer all of the
7627 // elements together into an appropriately sized APInt and write them all
7628 // out at once. Because we don't accept vectors where NElts * EltSize
7629 // isn't a multiple of the char size, there will be no padding space, so
7630 // we don't have to worry about reading any padding data which didn't
7631 // actually need to be accessed.
7632 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7633
7635 Bytes.reserve(NElts / 8);
7636 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
7637 return std::nullopt;
7638
7639 APSInt SValInt(NElts, true);
7640 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
7641
7642 for (unsigned I = 0; I < NElts; ++I) {
7643 llvm::APInt Elt =
7644 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
7645 Elts.emplace_back(
7646 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
7647 }
7648 } else {
7649 // Iterate over each of the elements and read them from the buffer at
7650 // the appropriate offset.
7651 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7652 for (unsigned I = 0; I < NElts; ++I) {
7653 std::optional<APValue> EltValue =
7654 visitType(EltTy, Offset + I * EltSizeChars);
7655 if (!EltValue)
7656 return std::nullopt;
7657 Elts.push_back(std::move(*EltValue));
7658 }
7659 }
7660
7661 return APValue(Elts.data(), Elts.size());
7662 }
7663
7664 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7665 return unsupportedType(QualType(Ty, 0));
7666 }
7667
7668 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7669 QualType Can = Ty.getCanonicalType();
7670
7671 switch (Can->getTypeClass()) {
7672#define TYPE(Class, Base) \
7673 case Type::Class: \
7674 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7675#define ABSTRACT_TYPE(Class, Base)
7676#define NON_CANONICAL_TYPE(Class, Base) \
7677 case Type::Class: \
7678 llvm_unreachable("non-canonical type should be impossible!");
7679#define DEPENDENT_TYPE(Class, Base) \
7680 case Type::Class: \
7681 llvm_unreachable( \
7682 "dependent types aren't supported in the constant evaluator!");
7683#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
7684 case Type::Class: \
7685 llvm_unreachable("either dependent or not canonical!");
7686#include "clang/AST/TypeNodes.inc"
7687 }
7688 llvm_unreachable("Unhandled Type::TypeClass");
7689 }
7690
7691public:
7692 // Pull out a full value of type DstType.
7693 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7694 const CastExpr *BCE) {
7695 BufferToAPValueConverter Converter(Info, Buffer, BCE);
7696 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7697 }
7698};
7699
7700static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7701 QualType Ty, EvalInfo *Info,
7702 const ASTContext &Ctx,
7703 bool CheckingDest) {
7704 Ty = Ty.getCanonicalType();
7705
7706 auto diag = [&](int Reason) {
7707 if (Info)
7708 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7709 << CheckingDest << (Reason == 4) << Reason;
7710 return false;
7711 };
7712 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7713 if (Info)
7714 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7715 << NoteTy << Construct << Ty;
7716 return false;
7717 };
7718
7719 if (Ty->isUnionType())
7720 return diag(0);
7721 if (Ty->isPointerType())
7722 return diag(1);
7723 if (Ty->isMemberPointerType())
7724 return diag(2);
7725 if (Ty.isVolatileQualified())
7726 return diag(3);
7727
7728 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7729 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7730 for (CXXBaseSpecifier &BS : CXXRD->bases())
7731 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7732 CheckingDest))
7733 return note(1, BS.getType(), BS.getBeginLoc());
7734 }
7735 for (FieldDecl *FD : Record->fields()) {
7736 if (FD->getType()->isReferenceType())
7737 return diag(4);
7738 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7739 CheckingDest))
7740 return note(0, FD->getType(), FD->getBeginLoc());
7741 }
7742 }
7743
7744 if (Ty->isArrayType() &&
7745 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7746 Info, Ctx, CheckingDest))
7747 return false;
7748
7749 if (const auto *VTy = Ty->getAs<VectorType>()) {
7750 QualType EltTy = VTy->getElementType();
7751 unsigned NElts = VTy->getNumElements();
7752 unsigned EltSize = VTy->isExtVectorBoolType() ? 1 : Ctx.getTypeSize(EltTy);
7753
7754 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
7755 // The vector's size in bits is not a multiple of the target's byte size,
7756 // so its layout is unspecified. For now, we'll simply treat these cases
7757 // as unsupported (this should only be possible with OpenCL bool vectors
7758 // whose element count isn't a multiple of the byte size).
7759 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
7760 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
7761 return false;
7762 }
7763
7764 if (EltTy->isRealFloatingType() &&
7765 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
7766 // The layout for x86_fp80 vectors seems to be handled very inconsistently
7767 // by both clang and LLVM, so for now we won't allow bit_casts involving
7768 // it in a constexpr context.
7769 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
7770 << EltTy;
7771 return false;
7772 }
7773 }
7774
7775 return true;
7776}
7777
7778static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7779 const ASTContext &Ctx,
7780 const CastExpr *BCE) {
7781 bool DestOK = checkBitCastConstexprEligibilityType(
7782 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7783 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7784 BCE->getBeginLoc(),
7785 BCE->getSubExpr()->getType(), Info, Ctx, false);
7786 return SourceOK;
7787}
7788
7789static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7790 const APValue &SourceRValue,
7791 const CastExpr *BCE) {
7792 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7793 "no host or target supports non 8-bit chars");
7794
7795 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7796 return false;
7797
7798 // Read out SourceValue into a char buffer.
7799 std::optional<BitCastBuffer> Buffer =
7800 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7801 if (!Buffer)
7802 return false;
7803
7804 // Write out the buffer into a new APValue.
7805 std::optional<APValue> MaybeDestValue =
7806 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7807 if (!MaybeDestValue)
7808 return false;
7809
7810 DestValue = std::move(*MaybeDestValue);
7811 return true;
7812}
7813
7814static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7815 APValue &SourceValue,
7816 const CastExpr *BCE) {
7817 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7818 "no host or target supports non 8-bit chars");
7819 assert(SourceValue.isLValue() &&
7820 "LValueToRValueBitcast requires an lvalue operand!");
7821
7822 LValue SourceLValue;
7823 APValue SourceRValue;
7824 SourceLValue.setFrom(Info.Ctx, SourceValue);
7826 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7827 SourceRValue, /*WantObjectRepresentation=*/true))
7828 return false;
7829
7830 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
7831}
7832
7833template <class Derived>
7834class ExprEvaluatorBase
7835 : public ConstStmtVisitor<Derived, bool> {
7836private:
7837 Derived &getDerived() { return static_cast<Derived&>(*this); }
7838 bool DerivedSuccess(const APValue &V, const Expr *E) {
7839 return getDerived().Success(V, E);
7840 }
7841 bool DerivedZeroInitialization(const Expr *E) {
7842 return getDerived().ZeroInitialization(E);
7843 }
7844
7845 // Check whether a conditional operator with a non-constant condition is a
7846 // potential constant expression. If neither arm is a potential constant
7847 // expression, then the conditional operator is not either.
7848 template<typename ConditionalOperator>
7849 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7850 assert(Info.checkingPotentialConstantExpression());
7851
7852 // Speculatively evaluate both arms.
7854 {
7855 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7856 StmtVisitorTy::Visit(E->getFalseExpr());
7857 if (Diag.empty())
7858 return;
7859 }
7860
7861 {
7862 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7863 Diag.clear();
7864 StmtVisitorTy::Visit(E->getTrueExpr());
7865 if (Diag.empty())
7866 return;
7867 }
7868
7869 Error(E, diag::note_constexpr_conditional_never_const);
7870 }
7871
7872
7873 template<typename ConditionalOperator>
7874 bool HandleConditionalOperator(const ConditionalOperator *E) {
7875 bool BoolResult;
7876 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7877 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7878 CheckPotentialConstantConditional(E);
7879 return false;
7880 }
7881 if (Info.noteFailure()) {
7882 StmtVisitorTy::Visit(E->getTrueExpr());
7883 StmtVisitorTy::Visit(E->getFalseExpr());
7884 }
7885 return false;
7886 }
7887
7888 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7889 return StmtVisitorTy::Visit(EvalExpr);
7890 }
7891
7892protected:
7893 EvalInfo &Info;
7894 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7895 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7896
7897 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7898 return Info.CCEDiag(E, D);
7899 }
7900
7901 bool ZeroInitialization(const Expr *E) { return Error(E); }
7902
7903 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7904 unsigned BuiltinOp = E->getBuiltinCallee();
7905 return BuiltinOp != 0 &&
7906 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
7907 }
7908
7909public:
7910 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7911
7912 EvalInfo &getEvalInfo() { return Info; }
7913
7914 /// Report an evaluation error. This should only be called when an error is
7915 /// first discovered. When propagating an error, just return false.
7916 bool Error(const Expr *E, diag::kind D) {
7917 Info.FFDiag(E, D) << E->getSourceRange();
7918 return false;
7919 }
7920 bool Error(const Expr *E) {
7921 return Error(E, diag::note_invalid_subexpr_in_const_expr);
7922 }
7923
7924 bool VisitStmt(const Stmt *) {
7925 llvm_unreachable("Expression evaluator should not be called on stmts");
7926 }
7927 bool VisitExpr(const Expr *E) {
7928 return Error(E);
7929 }
7930
7931 bool VisitEmbedExpr(const EmbedExpr *E) {
7932 const auto It = E->begin();
7933 return StmtVisitorTy::Visit(*It);
7934 }
7935
7936 bool VisitPredefinedExpr(const PredefinedExpr *E) {
7937 return StmtVisitorTy::Visit(E->getFunctionName());
7938 }
7939 bool VisitConstantExpr(const ConstantExpr *E) {
7940 if (E->hasAPValueResult())
7941 return DerivedSuccess(E->getAPValueResult(), E);
7942
7943 return StmtVisitorTy::Visit(E->getSubExpr());
7944 }
7945
7946 bool VisitParenExpr(const ParenExpr *E)
7947 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7948 bool VisitUnaryExtension(const UnaryOperator *E)
7949 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7950 bool VisitUnaryPlus(const UnaryOperator *E)
7951 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7952 bool VisitChooseExpr(const ChooseExpr *E)
7953 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7954 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7955 { return StmtVisitorTy::Visit(E->getResultExpr()); }
7956 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7957 { return StmtVisitorTy::Visit(E->getReplacement()); }
7958 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7959 TempVersionRAII RAII(*Info.CurrentCall);
7960 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7961 return StmtVisitorTy::Visit(E->getExpr());
7962 }
7963 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7964 TempVersionRAII RAII(*Info.CurrentCall);
7965 // The initializer may not have been parsed yet, or might be erroneous.
7966 if (!E->getExpr())
7967 return Error(E);
7968 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7969 return StmtVisitorTy::Visit(E->getExpr());
7970 }
7971
7972 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7973 FullExpressionRAII Scope(Info);
7974 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7975 }
7976
7977 // Temporaries are registered when created, so we don't care about
7978 // CXXBindTemporaryExpr.
7979 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7980 return StmtVisitorTy::Visit(E->getSubExpr());
7981 }
7982
7983 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7984 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7985 return static_cast<Derived*>(this)->VisitCastExpr(E);
7986 }
7987 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7988 if (!Info.Ctx.getLangOpts().CPlusPlus20)
7989 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7990 return static_cast<Derived*>(this)->VisitCastExpr(E);
7991 }
7992 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7993 return static_cast<Derived*>(this)->VisitCastExpr(E);
7994 }
7995
7996 bool VisitBinaryOperator(const BinaryOperator *E) {
7997 switch (E->getOpcode()) {
7998 default:
7999 return Error(E);
8000
8001 case BO_Comma:
8002 VisitIgnoredValue(E->getLHS());
8003 return StmtVisitorTy::Visit(E->getRHS());
8004
8005 case BO_PtrMemD:
8006 case BO_PtrMemI: {
8007 LValue Obj;
8008 if (!HandleMemberPointerAccess(Info, E, Obj))
8009 return false;
8010 APValue Result;
8011 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8012 return false;
8013 return DerivedSuccess(Result, E);
8014 }
8015 }
8016 }
8017
8018 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8019 return StmtVisitorTy::Visit(E->getSemanticForm());
8020 }
8021
8022 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8023 // Evaluate and cache the common expression. We treat it as a temporary,
8024 // even though it's not quite the same thing.
8025 LValue CommonLV;
8026 if (!Evaluate(Info.CurrentCall->createTemporary(
8027 E->getOpaqueValue(),
8028 getStorageType(Info.Ctx, E->getOpaqueValue()),
8029 ScopeKind::FullExpression, CommonLV),
8030 Info, E->getCommon()))
8031 return false;
8032
8033 return HandleConditionalOperator(E);
8034 }
8035
8036 bool VisitConditionalOperator(const ConditionalOperator *E) {
8037 bool IsBcpCall = false;
8038 // If the condition (ignoring parens) is a __builtin_constant_p call,
8039 // the result is a constant expression if it can be folded without
8040 // side-effects. This is an important GNU extension. See GCC PR38377
8041 // for discussion.
8042 if (const CallExpr *CallCE =
8043 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8044 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8045 IsBcpCall = true;
8046
8047 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8048 // constant expression; we can't check whether it's potentially foldable.
8049 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8050 // it would return 'false' in this mode.
8051 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8052 return false;
8053
8054 FoldConstant Fold(Info, IsBcpCall);
8055 if (!HandleConditionalOperator(E)) {
8056 Fold.keepDiagnostics();
8057 return false;
8058 }
8059
8060 return true;
8061 }
8062
8063 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8064 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8065 Value && !Value->isAbsent())
8066 return DerivedSuccess(*Value, E);
8067
8068 const Expr *Source = E->getSourceExpr();
8069 if (!Source)
8070 return Error(E);
8071 if (Source == E) {
8072 assert(0 && "OpaqueValueExpr recursively refers to itself");
8073 return Error(E);
8074 }
8075 return StmtVisitorTy::Visit(Source);
8076 }
8077
8078 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8079 for (const Expr *SemE : E->semantics()) {
8080 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8081 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8082 // result expression: there could be two different LValues that would
8083 // refer to the same object in that case, and we can't model that.
8084 if (SemE == E->getResultExpr())
8085 return Error(E);
8086
8087 // Unique OVEs get evaluated if and when we encounter them when
8088 // emitting the rest of the semantic form, rather than eagerly.
8089 if (OVE->isUnique())
8090 continue;
8091
8092 LValue LV;
8093 if (!Evaluate(Info.CurrentCall->createTemporary(
8094 OVE, getStorageType(Info.Ctx, OVE),
8095 ScopeKind::FullExpression, LV),
8096 Info, OVE->getSourceExpr()))
8097 return false;
8098 } else if (SemE == E->getResultExpr()) {
8099 if (!StmtVisitorTy::Visit(SemE))
8100 return false;
8101 } else {
8102 if (!EvaluateIgnoredValue(Info, SemE))
8103 return false;
8104 }
8105 }
8106 return true;
8107 }
8108
8109 bool VisitCallExpr(const CallExpr *E) {
8110 APValue Result;
8111 if (!handleCallExpr(E, Result, nullptr))
8112 return false;
8113 return DerivedSuccess(Result, E);
8114 }
8115
8116 bool handleCallExpr(const CallExpr *E, APValue &Result,
8117 const LValue *ResultSlot) {
8118 CallScopeRAII CallScope(Info);
8119
8120 const Expr *Callee = E->getCallee()->IgnoreParens();
8121 QualType CalleeType = Callee->getType();
8122
8123 const FunctionDecl *FD = nullptr;
8124 LValue *This = nullptr, ThisVal;
8125 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
8126 bool HasQualifier = false;
8127
8128 CallRef Call;
8129
8130 // Extract function decl and 'this' pointer from the callee.
8131 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8132 const CXXMethodDecl *Member = nullptr;
8133 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8134 // Explicit bound member calls, such as x.f() or p->g();
8135 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
8136 return false;
8137 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8138 if (!Member)
8139 return Error(Callee);
8140 This = &ThisVal;
8141 HasQualifier = ME->hasQualifier();
8142 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8143 // Indirect bound member calls ('.*' or '->*').
8144 const ValueDecl *D =
8145 HandleMemberPointerAccess(Info, BE, ThisVal, false);
8146 if (!D)
8147 return false;
8148 Member = dyn_cast<CXXMethodDecl>(D);
8149 if (!Member)
8150 return Error(Callee);
8151 This = &ThisVal;
8152 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8153 if (!Info.getLangOpts().CPlusPlus20)
8154 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8155 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
8156 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
8157 } else
8158 return Error(Callee);
8159 FD = Member;
8160 } else if (CalleeType->isFunctionPointerType()) {
8161 LValue CalleeLV;
8162 if (!EvaluatePointer(Callee, CalleeLV, Info))
8163 return false;
8164
8165 if (!CalleeLV.getLValueOffset().isZero())
8166 return Error(Callee);
8167 if (CalleeLV.isNullPointer()) {
8168 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8169 << const_cast<Expr *>(Callee);
8170 return false;
8171 }
8172 FD = dyn_cast_or_null<FunctionDecl>(
8173 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8174 if (!FD)
8175 return Error(Callee);
8176 // Don't call function pointers which have been cast to some other type.
8177 // Per DR (no number yet), the caller and callee can differ in noexcept.
8178 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
8179 CalleeType->getPointeeType(), FD->getType())) {
8180 return Error(E);
8181 }
8182
8183 // For an (overloaded) assignment expression, evaluate the RHS before the
8184 // LHS.
8185 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8186 if (OCE && OCE->isAssignmentOp()) {
8187 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8188 Call = Info.CurrentCall->createCall(FD);
8189 bool HasThis = false;
8190 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8191 HasThis = MD->isImplicitObjectMemberFunction();
8192 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8193 /*RightToLeft=*/true))
8194 return false;
8195 }
8196
8197 // Overloaded operator calls to member functions are represented as normal
8198 // calls with '*this' as the first argument.
8199 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8200 if (MD &&
8201 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8202 // FIXME: When selecting an implicit conversion for an overloaded
8203 // operator delete, we sometimes try to evaluate calls to conversion
8204 // operators without a 'this' parameter!
8205 if (Args.empty())
8206 return Error(E);
8207
8208 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
8209 return false;
8210
8211 // If we are calling a static operator, the 'this' argument needs to be
8212 // ignored after being evaluated.
8213 if (MD->isInstance())
8214 This = &ThisVal;
8215
8216 // If this is syntactically a simple assignment using a trivial
8217 // assignment operator, start the lifetimes of union members as needed,
8218 // per C++20 [class.union]5.
8219 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8220 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8221 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal))
8222 return false;
8223
8224 Args = Args.slice(1);
8225 } else if (MD && MD->isLambdaStaticInvoker()) {
8226 // Map the static invoker for the lambda back to the call operator.
8227 // Conveniently, we don't have to slice out the 'this' argument (as is
8228 // being done for the non-static case), since a static member function
8229 // doesn't have an implicit argument passed in.
8230 const CXXRecordDecl *ClosureClass = MD->getParent();
8231 assert(
8232 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
8233 "Number of captures must be zero for conversion to function-ptr");
8234
8235 const CXXMethodDecl *LambdaCallOp =
8236 ClosureClass->getLambdaCallOperator();
8237
8238 // Set 'FD', the function that will be called below, to the call
8239 // operator. If the closure object represents a generic lambda, find
8240 // the corresponding specialization of the call operator.
8241
8242 if (ClosureClass->isGenericLambda()) {
8243 assert(MD->isFunctionTemplateSpecialization() &&
8244 "A generic lambda's static-invoker function must be a "
8245 "template specialization");
8247 FunctionTemplateDecl *CallOpTemplate =
8248 LambdaCallOp->getDescribedFunctionTemplate();
8249 void *InsertPos = nullptr;
8250 FunctionDecl *CorrespondingCallOpSpecialization =
8251 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8252 assert(CorrespondingCallOpSpecialization &&
8253 "We must always have a function call operator specialization "
8254 "that corresponds to our static invoker specialization");
8255 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8256 FD = CorrespondingCallOpSpecialization;
8257 } else
8258 FD = LambdaCallOp;
8259 } else if (FD->isReplaceableGlobalAllocationFunction()) {
8260 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
8261 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
8262 LValue Ptr;
8263 if (!HandleOperatorNewCall(Info, E, Ptr))
8264 return false;
8265 Ptr.moveInto(Result);
8266 return CallScope.destroy();
8267 } else {
8268 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8269 }
8270 }
8271 } else
8272 return Error(E);
8273
8274 // Evaluate the arguments now if we've not already done so.
8275 if (!Call) {
8276 Call = Info.CurrentCall->createCall(FD);
8277 if (!EvaluateArgs(Args, Call, Info, FD))
8278 return false;
8279 }
8280
8281 SmallVector<QualType, 4> CovariantAdjustmentPath;
8282 if (This) {
8283 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8284 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8285 // Perform virtual dispatch, if necessary.
8286 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8287 CovariantAdjustmentPath);
8288 if (!FD)
8289 return false;
8290 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8291 // Check that the 'this' pointer points to an object of the right type.
8292 // FIXME: If this is an assignment operator call, we may need to change
8293 // the active union member before we check this.
8294 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8295 return false;
8296 }
8297 }
8298
8299 // Destructor calls are different enough that they have their own codepath.
8300 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8301 assert(This && "no 'this' pointer for destructor call");
8302 return HandleDestruction(Info, E, *This,
8303 Info.Ctx.getRecordType(DD->getParent())) &&
8304 CallScope.destroy();
8305 }
8306
8307 const FunctionDecl *Definition = nullptr;
8308 Stmt *Body = FD->getBody(Definition);
8309
8310 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8311 !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8312 Body, Info, Result, ResultSlot))
8313 return false;
8314
8315 if (!CovariantAdjustmentPath.empty() &&
8316 !HandleCovariantReturnAdjustment(Info, E, Result,
8317 CovariantAdjustmentPath))
8318 return false;
8319
8320 return CallScope.destroy();
8321 }
8322
8323 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8324 return StmtVisitorTy::Visit(E->getInitializer());
8325 }
8326 bool VisitInitListExpr(const InitListExpr *E) {
8327 if (E->getNumInits() == 0)
8328 return DerivedZeroInitialization(E);
8329 if (E->getNumInits() == 1)
8330 return StmtVisitorTy::Visit(E->getInit(0));
8331 return Error(E);
8332 }
8333 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8334 return DerivedZeroInitialization(E);
8335 }
8336 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8337 return DerivedZeroInitialization(E);
8338 }
8339 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8340 return DerivedZeroInitialization(E);
8341 }
8342
8343 /// A member expression where the object is a prvalue is itself a prvalue.
8344 bool VisitMemberExpr(const MemberExpr *E) {
8345 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8346 "missing temporary materialization conversion");
8347 assert(!E->isArrow() && "missing call to bound member function?");
8348
8349 APValue Val;
8350 if (!Evaluate(Val, Info, E->getBase()))
8351 return false;
8352
8353 QualType BaseTy = E->getBase()->getType();
8354
8355 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8356 if (!FD) return Error(E);
8357 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8358 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8359 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8360
8361 // Note: there is no lvalue base here. But this case should only ever
8362 // happen in C or in C++98, where we cannot be evaluating a constexpr
8363 // constructor, which is the only case the base matters.
8364 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8365 SubobjectDesignator Designator(BaseTy);
8366 Designator.addDeclUnchecked(FD);
8367
8368 APValue Result;
8369 return extractSubobject(Info, E, Obj, Designator, Result) &&
8370 DerivedSuccess(Result, E);
8371 }
8372
8373 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8374 APValue Val;
8375 if (!Evaluate(Val, Info, E->getBase()))
8376 return false;
8377
8378 if (Val.isVector()) {
8380 E->getEncodedElementAccess(Indices);
8381 if (Indices.size() == 1) {
8382 // Return scalar.
8383 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8384 } else {
8385 // Construct new APValue vector.
8387 for (unsigned I = 0; I < Indices.size(); ++I) {
8388 Elts.push_back(Val.getVectorElt(Indices[I]));
8389 }
8390 APValue VecResult(Elts.data(), Indices.size());
8391 return DerivedSuccess(VecResult, E);
8392 }
8393 }
8394
8395 return false;
8396 }
8397
8398 bool VisitCastExpr(const CastExpr *E) {
8399 switch (E->getCastKind()) {
8400 default:
8401 break;
8402
8403 case CK_AtomicToNonAtomic: {
8404 APValue AtomicVal;
8405 // This does not need to be done in place even for class/array types:
8406 // atomic-to-non-atomic conversion implies copying the object
8407 // representation.
8408 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8409 return false;
8410 return DerivedSuccess(AtomicVal, E);
8411 }
8412
8413 case CK_NoOp:
8414 case CK_UserDefinedConversion:
8415 return StmtVisitorTy::Visit(E->getSubExpr());
8416
8417 case CK_LValueToRValue: {
8418 LValue LVal;
8419 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8420 return false;
8421 APValue RVal;
8422 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8423 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8424 LVal, RVal))
8425 return false;
8426 return DerivedSuccess(RVal, E);
8427 }
8428 case CK_LValueToRValueBitCast: {
8429 APValue DestValue, SourceValue;
8430 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8431 return false;
8432 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8433 return false;
8434 return DerivedSuccess(DestValue, E);
8435 }
8436
8437 case CK_AddressSpaceConversion: {
8438 APValue Value;
8439 if (!Evaluate(Value, Info, E->getSubExpr()))
8440 return false;
8441 return DerivedSuccess(Value, E);
8442 }
8443 }
8444
8445 return Error(E);
8446 }
8447
8448 bool VisitUnaryPostInc(const UnaryOperator *UO) {
8449 return VisitUnaryPostIncDec(UO);
8450 }
8451 bool VisitUnaryPostDec(const UnaryOperator *UO) {
8452 return VisitUnaryPostIncDec(UO);
8453 }
8454 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8455 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8456 return Error(UO);
8457
8458 LValue LVal;
8459 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8460 return false;
8461 APValue RVal;
8462 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8463 UO->isIncrementOp(), &RVal))
8464 return false;
8465 return DerivedSuccess(RVal, UO);
8466 }
8467
8468 bool VisitStmtExpr(const StmtExpr *E) {
8469 // We will have checked the full-expressions inside the statement expression
8470 // when they were completed, and don't need to check them again now.
8471 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8472 false);
8473
8474 const CompoundStmt *CS = E->getSubStmt();
8475 if (CS->body_empty())
8476 return true;
8477
8478 BlockScopeRAII Scope(Info);
8480 BE = CS->body_end();
8481 /**/; ++BI) {
8482 if (BI + 1 == BE) {
8483 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8484 if (!FinalExpr) {
8485 Info.FFDiag((*BI)->getBeginLoc(),
8486 diag::note_constexpr_stmt_expr_unsupported);
8487 return false;
8488 }
8489 return this->Visit(FinalExpr) && Scope.destroy();
8490 }
8491
8493 StmtResult Result = { ReturnValue, nullptr };
8494 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8495 if (ESR != ESR_Succeeded) {
8496 // FIXME: If the statement-expression terminated due to 'return',
8497 // 'break', or 'continue', it would be nice to propagate that to
8498 // the outer statement evaluation rather than bailing out.
8499 if (ESR != ESR_Failed)
8500 Info.FFDiag((*BI)->getBeginLoc(),
8501 diag::note_constexpr_stmt_expr_unsupported);
8502 return false;
8503 }
8504 }
8505
8506 llvm_unreachable("Return from function from the loop above.");
8507 }
8508
8509 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
8510 return StmtVisitorTy::Visit(E->getSelectedExpr());
8511 }
8512
8513 /// Visit a value which is evaluated, but whose value is ignored.
8514 void VisitIgnoredValue(const Expr *E) {
8515 EvaluateIgnoredValue(Info, E);
8516 }
8517
8518 /// Potentially visit a MemberExpr's base expression.
8519 void VisitIgnoredBaseExpression(const Expr *E) {
8520 // While MSVC doesn't evaluate the base expression, it does diagnose the
8521 // presence of side-effecting behavior.
8522 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8523 return;
8524 VisitIgnoredValue(E);
8525 }
8526};
8527
8528} // namespace
8529
8530//===----------------------------------------------------------------------===//
8531// Common base class for lvalue and temporary evaluation.
8532//===----------------------------------------------------------------------===//
8533namespace {
8534template<class Derived>
8535class LValueExprEvaluatorBase
8536 : public ExprEvaluatorBase<Derived> {
8537protected:
8538 LValue &Result;
8539 bool InvalidBaseOK;
8540 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8541 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8542
8544 Result.set(B);
8545 return true;
8546 }
8547
8548 bool evaluatePointer(const Expr *E, LValue &Result) {
8549 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8550 }
8551
8552public:
8553 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8554 : ExprEvaluatorBaseTy(Info), Result(Result),
8555 InvalidBaseOK(InvalidBaseOK) {}
8556
8557 bool Success(const APValue &V, const Expr *E) {
8558 Result.setFrom(this->Info.Ctx, V);
8559 return true;
8560 }
8561
8562 bool VisitMemberExpr(const MemberExpr *E) {
8563 // Handle non-static data members.
8564 QualType BaseTy;
8565 bool EvalOK;
8566 if (E->isArrow()) {
8567 EvalOK = evaluatePointer(E->getBase(), Result);
8568 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8569 } else if (E->getBase()->isPRValue()) {
8570 assert(E->getBase()->getType()->isRecordType());
8571 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8572 BaseTy = E->getBase()->getType();
8573 } else {
8574 EvalOK = this->Visit(E->getBase());
8575 BaseTy = E->getBase()->getType();
8576 }
8577 if (!EvalOK) {
8578 if (!InvalidBaseOK)
8579 return false;
8580 Result.setInvalid(E);
8581 return true;
8582 }
8583
8584 const ValueDecl *MD = E->getMemberDecl();
8585 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8586 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8587 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8588 (void)BaseTy;
8589 if (!HandleLValueMember(this->Info, E, Result, FD))
8590 return false;
8591 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8592 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8593 return false;
8594 } else
8595 return this->Error(E);
8596
8597 if (MD->getType()->isReferenceType()) {
8598 APValue RefValue;
8599 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8600 RefValue))
8601 return false;
8602 return Success(RefValue, E);
8603 }
8604 return true;
8605 }
8606
8607 bool VisitBinaryOperator(const BinaryOperator *E) {
8608 switch (E->getOpcode()) {
8609 default:
8610 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8611
8612 case BO_PtrMemD:
8613 case BO_PtrMemI:
8614 return HandleMemberPointerAccess(this->Info, E, Result);
8615 }
8616 }
8617
8618 bool VisitCastExpr(const CastExpr *E) {
8619 switch (E->getCastKind()) {
8620 default:
8621 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8622
8623 case CK_DerivedToBase:
8624 case CK_UncheckedDerivedToBase:
8625 if (!this->Visit(E->getSubExpr()))
8626 return false;
8627
8628 // Now figure out the necessary offset to add to the base LV to get from
8629 // the derived class to the base class.
8630 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8631 Result);
8632 }
8633 }
8634};
8635}
8636
8637//===----------------------------------------------------------------------===//
8638// LValue Evaluation
8639//
8640// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8641// function designators (in C), decl references to void objects (in C), and
8642// temporaries (if building with -Wno-address-of-temporary).
8643//
8644// LValue evaluation produces values comprising a base expression of one of the
8645// following types:
8646// - Declarations
8647// * VarDecl
8648// * FunctionDecl
8649// - Literals
8650// * CompoundLiteralExpr in C (and in global scope in C++)
8651// * StringLiteral
8652// * PredefinedExpr
8653// * ObjCStringLiteralExpr
8654// * ObjCEncodeExpr
8655// * AddrLabelExpr
8656// * BlockExpr
8657// * CallExpr for a MakeStringConstant builtin
8658// - typeid(T) expressions, as TypeInfoLValues
8659// - Locals and temporaries
8660// * MaterializeTemporaryExpr
8661// * Any Expr, with a CallIndex indicating the function in which the temporary
8662// was evaluated, for cases where the MaterializeTemporaryExpr is missing
8663// from the AST (FIXME).
8664// * A MaterializeTemporaryExpr that has static storage duration, with no
8665// CallIndex, for a lifetime-extended temporary.
8666// * The ConstantExpr that is currently being evaluated during evaluation of an
8667// immediate invocation.
8668// plus an offset in bytes.
8669//===----------------------------------------------------------------------===//
8670namespace {
8671class LValueExprEvaluator
8672 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8673public:
8674 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8675 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8676
8677 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8678 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8679
8680 bool VisitCallExpr(const CallExpr *E);
8681 bool VisitDeclRefExpr(const DeclRefExpr *E);
8682 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8683 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8684 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8685 bool VisitMemberExpr(const MemberExpr *E);
8686 bool VisitStringLiteral(const StringLiteral *E) {
8688 E, 0, Info.getASTContext().getNextStringLiteralVersion()));
8689 }
8690 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8691 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8692 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8693 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8694 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
8695 bool VisitUnaryDeref(const UnaryOperator *E);
8696 bool VisitUnaryReal(const UnaryOperator *E);
8697 bool VisitUnaryImag(const UnaryOperator *E);
8698 bool VisitUnaryPreInc(const UnaryOperator *UO) {
8699 return VisitUnaryPreIncDec(UO);
8700 }
8701 bool VisitUnaryPreDec(const UnaryOperator *UO) {
8702 return VisitUnaryPreIncDec(UO);
8703 }
8704 bool VisitBinAssign(const BinaryOperator *BO);
8705 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8706
8707 bool VisitCastExpr(const CastExpr *E) {
8708 switch (E->getCastKind()) {
8709 default:
8710 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8711
8712 case CK_LValueBitCast:
8713 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8714 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8715 if (!Visit(E->getSubExpr()))
8716 return false;
8717 Result.Designator.setInvalid();
8718 return true;
8719
8720 case CK_BaseToDerived:
8721 if (!Visit(E->getSubExpr()))
8722 return false;
8723 return HandleBaseToDerivedCast(Info, E, Result);
8724
8725 case CK_Dynamic:
8726 if (!Visit(E->getSubExpr()))
8727 return false;
8728 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8729 }
8730 }
8731};
8732} // end anonymous namespace
8733
8734/// Get an lvalue to a field of a lambda's closure type.
8735static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
8736 const CXXMethodDecl *MD, const FieldDecl *FD,
8737 bool LValueToRValueConversion) {
8738 // Static lambda function call operators can't have captures. We already
8739 // diagnosed this, so bail out here.
8740 if (MD->isStatic()) {
8741 assert(Info.CurrentCall->This == nullptr &&
8742 "This should not be set for a static call operator");
8743 return false;
8744 }
8745
8746 // Start with 'Result' referring to the complete closure object...
8748 // Self may be passed by reference or by value.
8749 const ParmVarDecl *Self = MD->getParamDecl(0);
8750 if (Self->getType()->isReferenceType()) {
8751 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
8752 Result.setFrom(Info.Ctx, *RefValue);
8753 } else {
8754 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
8755 CallStackFrame *Frame =
8756 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
8757 .first;
8758 unsigned Version = Info.CurrentCall->Arguments.Version;
8759 Result.set({VD, Frame->Index, Version});
8760 }
8761 } else
8762 Result = *Info.CurrentCall->This;
8763
8764 // ... then update it to refer to the field of the closure object
8765 // that represents the capture.
8766 if (!HandleLValueMember(Info, E, Result, FD))
8767 return false;
8768
8769 // And if the field is of reference type (or if we captured '*this' by
8770 // reference), update 'Result' to refer to what
8771 // the field refers to.
8772 if (LValueToRValueConversion) {
8773 APValue RVal;
8774 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
8775 return false;
8776 Result.setFrom(Info.Ctx, RVal);
8777 }
8778 return true;
8779}
8780
8781/// Evaluate an expression as an lvalue. This can be legitimately called on
8782/// expressions which are not glvalues, in three cases:
8783/// * function designators in C, and
8784/// * "extern void" objects
8785/// * @selector() expressions in Objective-C
8786static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8787 bool InvalidBaseOK) {
8788 assert(!E->isValueDependent());
8789 assert(E->isGLValue() || E->getType()->isFunctionType() ||
8790 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
8791 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8792}
8793
8794bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8795 const NamedDecl *D = E->getDecl();
8798 return Success(cast<ValueDecl>(D));
8799 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8800 return VisitVarDecl(E, VD);
8801 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8802 return Visit(BD->getBinding());
8803 return Error(E);
8804}
8805
8806
8807bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8808
8809 // If we are within a lambda's call operator, check whether the 'VD' referred
8810 // to within 'E' actually represents a lambda-capture that maps to a
8811 // data-member/field within the closure object, and if so, evaluate to the
8812 // field or what the field refers to.
8813 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8814 isa<DeclRefExpr>(E) &&
8815 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8816 // We don't always have a complete capture-map when checking or inferring if
8817 // the function call operator meets the requirements of a constexpr function
8818 // - but we don't need to evaluate the captures to determine constexprness
8819 // (dcl.constexpr C++17).
8820 if (Info.checkingPotentialConstantExpression())
8821 return false;
8822
8823 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8824 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
8825 return HandleLambdaCapture(Info, E, Result, MD, FD,
8826 FD->getType()->isReferenceType());
8827 }
8828 }
8829
8830 CallStackFrame *Frame = nullptr;
8831 unsigned Version = 0;
8832 if (VD->hasLocalStorage()) {
8833 // Only if a local variable was declared in the function currently being
8834 // evaluated, do we expect to be able to find its value in the current
8835 // frame. (Otherwise it was likely declared in an enclosing context and
8836 // could either have a valid evaluatable value (for e.g. a constexpr
8837 // variable) or be ill-formed (and trigger an appropriate evaluation
8838 // diagnostic)).
8839 CallStackFrame *CurrFrame = Info.CurrentCall;
8840 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8841 // Function parameters are stored in some caller's frame. (Usually the
8842 // immediate caller, but for an inherited constructor they may be more
8843 // distant.)
8844 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8845 if (CurrFrame->Arguments) {
8846 VD = CurrFrame->Arguments.getOrigParam(PVD);
8847 Frame =
8848 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8849 Version = CurrFrame->Arguments.Version;
8850 }
8851 } else {
8852 Frame = CurrFrame;
8853 Version = CurrFrame->getCurrentTemporaryVersion(VD);
8854 }
8855 }
8856 }
8857
8858 if (!VD->getType()->isReferenceType()) {
8859 if (Frame) {
8860 Result.set({VD, Frame->Index, Version});
8861 return true;
8862 }
8863 return Success(VD);
8864 }
8865
8866 if (!Info.getLangOpts().CPlusPlus11) {
8867 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8868 << VD << VD->getType();
8869 Info.Note(VD->getLocation(), diag::note_declared_at);
8870 }
8871
8872 APValue *V;
8873 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8874 return false;
8875 if (!V->hasValue()) {
8876 // FIXME: Is it possible for V to be indeterminate here? If so, we should
8877 // adjust the diagnostic to say that.
8878 if (!Info.checkingPotentialConstantExpression())
8879 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8880 return false;
8881 }
8882 return Success(*V, E);
8883}
8884
8885bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8886 if (!IsConstantEvaluatedBuiltinCall(E))
8887 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8888
8889 switch (E->getBuiltinCallee()) {
8890 default:
8891 return false;
8892 case Builtin::BIas_const:
8893 case Builtin::BIforward:
8894 case Builtin::BIforward_like:
8895 case Builtin::BImove:
8896 case Builtin::BImove_if_noexcept:
8897 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8898 return Visit(E->getArg(0));
8899 break;
8900 }
8901
8902 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8903}
8904
8905bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8906 const MaterializeTemporaryExpr *E) {
8907 // Walk through the expression to find the materialized temporary itself.
8910 const Expr *Inner =
8911 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8912
8913 // If we passed any comma operators, evaluate their LHSs.
8914 for (const Expr *E : CommaLHSs)
8915 if (!EvaluateIgnoredValue(Info, E))
8916 return false;
8917
8918 // A materialized temporary with static storage duration can appear within the
8919 // result of a constant expression evaluation, so we need to preserve its
8920 // value for use outside this evaluation.
8921 APValue *Value;
8922 if (E->getStorageDuration() == SD_Static) {
8923 if (Info.EvalMode == EvalInfo::EM_ConstantFold)
8924 return false;
8925 // FIXME: What about SD_Thread?
8926 Value = E->getOrCreateValue(true);
8927 *Value = APValue();
8928 Result.set(E);
8929 } else {
8930 Value = &Info.CurrentCall->createTemporary(
8931 E, Inner->getType(),
8932 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8933 : ScopeKind::Block,
8934 Result);
8935 }
8936
8937 QualType Type = Inner->getType();
8938
8939 // Materialize the temporary itself.
8940 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8941 *Value = APValue();
8942 return false;
8943 }
8944
8945 // Adjust our lvalue to refer to the desired subobject.
8946 for (unsigned I = Adjustments.size(); I != 0; /**/) {
8947 --I;
8948 switch (Adjustments[I].Kind) {
8950 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8951 Type, Result))
8952 return false;
8953 Type = Adjustments[I].DerivedToBase.BasePath->getType();
8954 break;
8955
8957 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8958 return false;
8959 Type = Adjustments[I].Field->getType();
8960 break;
8961
8963 if (!HandleMemberPointerAccess(this->Info, Type, Result,
8964 Adjustments[I].Ptr.RHS))
8965 return false;
8966 Type = Adjustments[I].Ptr.MPT->getPointeeType();
8967 break;
8968 }
8969 }
8970
8971 return true;
8972}
8973
8974bool
8975LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8976 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8977 "lvalue compound literal in c++?");
8978 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8979 // only see this when folding in C, so there's no standard to follow here.
8980 return Success(E);
8981}
8982
8983bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8985
8986 if (!E->isPotentiallyEvaluated()) {
8987 if (E->isTypeOperand())
8988 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8989 else
8990 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8991 } else {
8992 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8993 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8994 << E->getExprOperand()->getType()
8995 << E->getExprOperand()->getSourceRange();
8996 }
8997
8998 if (!Visit(E->getExprOperand()))
8999 return false;
9000
9001 std::optional<DynamicType> DynType =
9002 ComputeDynamicType(Info, E, Result, AK_TypeId);
9003 if (!DynType)
9004 return false;
9005
9006 TypeInfo =
9007 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
9008 }
9009
9011}
9012
9013bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9014 return Success(E->getGuidDecl());
9015}
9016
9017bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9018 // Handle static data members.
9019 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9020 VisitIgnoredBaseExpression(E->getBase());
9021 return VisitVarDecl(E, VD);
9022 }
9023
9024 // Handle static member functions.
9025 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9026 if (MD->isStatic()) {
9027 VisitIgnoredBaseExpression(E->getBase());
9028 return Success(MD);
9029 }
9030 }
9031
9032 // Handle non-static data members.
9033 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9034}
9035
9036bool LValueExprEvaluator::VisitExtVectorElementExpr(
9037 const ExtVectorElementExpr *E) {
9038 bool Success = true;
9039
9040 APValue Val;
9041 if (!Evaluate(Val, Info, E->getBase())) {
9042 if (!Info.noteFailure())
9043 return false;
9044 Success = false;
9045 }
9046
9048 E->getEncodedElementAccess(Indices);
9049 // FIXME: support accessing more than one element
9050 if (Indices.size() > 1)
9051 return false;
9052
9053 if (Success) {
9054 Result.setFrom(Info.Ctx, Val);
9055 const auto *VT = E->getBase()->getType()->castAs<VectorType>();
9056 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9057 VT->getNumElements(), Indices[0]);
9058 }
9059
9060 return Success;
9061}
9062
9063bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9064 if (E->getBase()->getType()->isSveVLSBuiltinType())
9065 return Error(E);
9066
9067 APSInt Index;
9068 bool Success = true;
9069
9070 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9071 APValue Val;
9072 if (!Evaluate(Val, Info, E->getBase())) {
9073 if (!Info.noteFailure())
9074 return false;
9075 Success = false;
9076 }
9077
9078 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9079 if (!Info.noteFailure())
9080 return false;
9081 Success = false;
9082 }
9083
9084 if (Success) {
9085 Result.setFrom(Info.Ctx, Val);
9086 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9087 VT->getNumElements(), Index.getExtValue());
9088 }
9089
9090 return Success;
9091 }
9092
9093 // C++17's rules require us to evaluate the LHS first, regardless of which
9094 // side is the base.
9095 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9096 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9097 : !EvaluateInteger(SubExpr, Index, Info)) {
9098 if (!Info.noteFailure())
9099 return false;
9100 Success = false;
9101 }
9102 }
9103
9104 return Success &&
9105 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9106}
9107
9108bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9109 return evaluatePointer(E->getSubExpr(), Result);
9110}
9111
9112bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9113 if (!Visit(E->getSubExpr()))
9114 return false;
9115 // __real is a no-op on scalar lvalues.
9116 if (E->getSubExpr()->getType()->isAnyComplexType())
9117 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9118 return true;
9119}
9120
9121bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9122 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9123 "lvalue __imag__ on scalar?");
9124 if (!Visit(E->getSubExpr()))
9125 return false;
9126 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9127 return true;
9128}
9129
9130bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9131 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9132 return Error(UO);
9133
9134 if (!this->Visit(UO->getSubExpr()))
9135 return false;
9136
9137 return handleIncDec(
9138 this->Info, UO, Result, UO->getSubExpr()->getType(),
9139 UO->isIncrementOp(), nullptr);
9140}
9141
9142bool LValueExprEvaluator::VisitCompoundAssignOperator(
9143 const CompoundAssignOperator *CAO) {
9144 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9145 return Error(CAO);
9146
9147 bool Success = true;
9148
9149 // C++17 onwards require that we evaluate the RHS first.
9150 APValue RHS;
9151 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9152 if (!Info.noteFailure())
9153 return false;
9154 Success = false;
9155 }
9156
9157 // The overall lvalue result is the result of evaluating the LHS.
9158 if (!this->Visit(CAO->getLHS()) || !Success)
9159 return false;
9160
9162 this->Info, CAO,
9163 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9164 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9165}
9166
9167bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9168 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9169 return Error(E);
9170
9171 bool Success = true;
9172
9173 // C++17 onwards require that we evaluate the RHS first.
9174 APValue NewVal;
9175 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9176 if (!Info.noteFailure())
9177 return false;
9178 Success = false;
9179 }
9180
9181 if (!this->Visit(E->getLHS()) || !Success)
9182 return false;
9183
9184 if (Info.getLangOpts().CPlusPlus20 &&
9185 !MaybeHandleUnionActiveMemberChange(Info, E->getLHS(), Result))
9186 return false;
9187
9188 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9189 NewVal);
9190}
9191
9192//===----------------------------------------------------------------------===//
9193// Pointer Evaluation
9194//===----------------------------------------------------------------------===//
9195
9196/// Attempts to compute the number of bytes available at the pointer
9197/// returned by a function with the alloc_size attribute. Returns true if we
9198/// were successful. Places an unsigned number into `Result`.
9199///
9200/// This expects the given CallExpr to be a call to a function with an
9201/// alloc_size attribute.
9203 const CallExpr *Call,
9204 llvm::APInt &Result) {
9205 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
9206
9207 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
9208 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
9209 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
9210 if (Call->getNumArgs() <= SizeArgNo)
9211 return false;
9212
9213 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
9216 return false;
9217 Into = ExprResult.Val.getInt();
9218 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
9219 return false;
9220 Into = Into.zext(BitsInSizeT);
9221 return true;
9222 };
9223
9224 APSInt SizeOfElem;
9225 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
9226 return false;
9227
9228 if (!AllocSize->getNumElemsParam().isValid()) {
9229 Result = std::move(SizeOfElem);
9230 return true;
9231 }
9232
9233 APSInt NumberOfElems;
9234 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
9235 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
9236 return false;
9237
9238 bool Overflow;
9239 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
9240 if (Overflow)
9241 return false;
9242
9243 Result = std::move(BytesAvailable);
9244 return true;
9245}
9246
9247/// Convenience function. LVal's base must be a call to an alloc_size
9248/// function.
9250 const LValue &LVal,
9251 llvm::APInt &Result) {
9252 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9253 "Can't get the size of a non alloc_size function");
9254 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9255 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9256 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
9257}
9258
9259/// Attempts to evaluate the given LValueBase as the result of a call to
9260/// a function with the alloc_size attribute. If it was possible to do so, this
9261/// function will return true, make Result's Base point to said function call,
9262/// and mark Result's Base as invalid.
9264 LValue &Result) {
9265 if (Base.isNull())
9266 return false;
9267
9268 // Because we do no form of static analysis, we only support const variables.
9269 //
9270 // Additionally, we can't support parameters, nor can we support static
9271 // variables (in the latter case, use-before-assign isn't UB; in the former,
9272 // we have no clue what they'll be assigned to).
9273 const auto *VD =
9274 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9275 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9276 return false;
9277
9278 const Expr *Init = VD->getAnyInitializer();
9279 if (!Init || Init->getType().isNull())
9280 return false;
9281
9282 const Expr *E = Init->IgnoreParens();
9283 if (!tryUnwrapAllocSizeCall(E))
9284 return false;
9285
9286 // Store E instead of E unwrapped so that the type of the LValue's base is
9287 // what the user wanted.
9288 Result.setInvalid(E);
9289
9290 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9291 Result.addUnsizedArray(Info, E, Pointee);
9292 return true;
9293}
9294
9295namespace {
9296class PointerExprEvaluator
9297 : public ExprEvaluatorBase<PointerExprEvaluator> {
9298 LValue &Result;
9299 bool InvalidBaseOK;
9300
9301 bool Success(const Expr *E) {
9302 Result.set(E);
9303 return true;
9304 }
9305
9306 bool evaluateLValue(const Expr *E, LValue &Result) {
9307 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9308 }
9309
9310 bool evaluatePointer(const Expr *E, LValue &Result) {
9311 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9312 }
9313
9314 bool visitNonBuiltinCallExpr(const CallExpr *E);
9315public:
9316
9317 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9318 : ExprEvaluatorBaseTy(info), Result(Result),
9319 InvalidBaseOK(InvalidBaseOK) {}
9320
9321 bool Success(const APValue &V, const Expr *E) {
9322 Result.setFrom(Info.Ctx, V);
9323 return true;
9324 }
9325 bool ZeroInitialization(const Expr *E) {
9326 Result.setNull(Info.Ctx, E->getType());
9327 return true;
9328 }
9329
9330 bool VisitBinaryOperator(const BinaryOperator *E);
9331 bool VisitCastExpr(const CastExpr* E);
9332 bool VisitUnaryAddrOf(const UnaryOperator *E);
9333 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9334 { return Success(E); }
9335 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9336 if (E->isExpressibleAsConstantInitializer())
9337 return Success(E);
9338 if (Info.noteFailure())
9339 EvaluateIgnoredValue(Info, E->getSubExpr());
9340 return Error(E);
9341 }
9342 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9343 { return Success(E); }
9344 bool VisitCallExpr(const CallExpr *E);
9345 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9346 bool VisitBlockExpr(const BlockExpr *E) {
9347 if (!E->getBlockDecl()->hasCaptures())
9348 return Success(E);
9349 return Error(E);
9350 }
9351 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9352 auto DiagnoseInvalidUseOfThis = [&] {
9353 if (Info.getLangOpts().CPlusPlus11)
9354 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9355 else
9356 Info.FFDiag(E);
9357 };
9358
9359 // Can't look at 'this' when checking a potential constant expression.
9360 if (Info.checkingPotentialConstantExpression())
9361 return false;
9362
9363 bool IsExplicitLambda =
9364 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9365 if (!IsExplicitLambda) {
9366 if (!Info.CurrentCall->This) {
9367 DiagnoseInvalidUseOfThis();
9368 return false;
9369 }
9370
9371 Result = *Info.CurrentCall->This;
9372 }
9373
9374 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9375 // Ensure we actually have captured 'this'. If something was wrong with
9376 // 'this' capture, the error would have been previously reported.
9377 // Otherwise we can be inside of a default initialization of an object
9378 // declared by lambda's body, so no need to return false.
9379 if (!Info.CurrentCall->LambdaThisCaptureField) {
9380 if (IsExplicitLambda && !Info.CurrentCall->This) {
9381 DiagnoseInvalidUseOfThis();
9382 return false;
9383 }
9384
9385 return true;
9386 }
9387
9388 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9389 return HandleLambdaCapture(
9390 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
9391 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9392 }
9393 return true;
9394 }
9395
9396 bool VisitCXXNewExpr(const CXXNewExpr *E);
9397
9398 bool VisitSourceLocExpr(const SourceLocExpr *E) {
9399 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9400 APValue LValResult = E->EvaluateInContext(
9401 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9402 Result.setFrom(Info.Ctx, LValResult);
9403 return true;
9404 }
9405
9406 bool VisitEmbedExpr(const EmbedExpr *E) {
9407 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
9408 return true;
9409 }
9410
9411 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9412 std::string ResultStr = E->ComputeName(Info.Ctx);
9413
9414 QualType CharTy = Info.Ctx.CharTy.withConst();
9415 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9416 ResultStr.size() + 1);
9417 QualType ArrayTy = Info.Ctx.getConstantArrayType(
9418 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9419
9420 StringLiteral *SL =
9421 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9422 /*Pascal*/ false, ArrayTy, E->getLocation());
9423
9424 evaluateLValue(SL, Result);
9425 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
9426 return true;
9427 }
9428
9429 // FIXME: Missing: @protocol, @selector
9430};
9431} // end anonymous namespace
9432
9433static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
9434 bool InvalidBaseOK) {
9435 assert(!E->isValueDependent());
9436 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
9437 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9438}
9439
9440bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9441 if (E->getOpcode() != BO_Add &&
9442 E->getOpcode() != BO_Sub)
9443 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9444
9445 const Expr *PExp = E->getLHS();
9446 const Expr *IExp = E->getRHS();
9447 if (IExp->getType()->isPointerType())
9448 std::swap(PExp, IExp);
9449
9450 bool EvalPtrOK = evaluatePointer(PExp, Result);
9451 if (!EvalPtrOK && !Info.noteFailure())
9452 return false;
9453
9454 llvm::APSInt Offset;
9455 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
9456 return false;
9457
9458 if (E->getOpcode() == BO_Sub)
9459 negateAsSigned(Offset);
9460
9461 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
9462 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
9463}
9464
9465bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9466 return evaluateLValue(E->getSubExpr(), Result);
9467}
9468
9469// Is the provided decl 'std::source_location::current'?
9471 if (!FD)
9472 return false;
9473 const IdentifierInfo *FnII = FD->getIdentifier();
9474 if (!FnII || !FnII->isStr("current"))
9475 return false;
9476
9477 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
9478 if (!RD)
9479 return false;
9480
9481 const IdentifierInfo *ClassII = RD->getIdentifier();
9482 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
9483}
9484
9485bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9486 const Expr *SubExpr = E->getSubExpr();
9487
9488 switch (E->getCastKind()) {
9489 default:
9490 break;
9491 case CK_BitCast:
9492 case CK_CPointerToObjCPointerCast:
9493 case CK_BlockPointerToObjCPointerCast:
9494 case CK_AnyPointerToBlockPointerCast:
9495 case CK_AddressSpaceConversion:
9496 if (!Visit(SubExpr))
9497 return false;
9498 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
9499 // permitted in constant expressions in C++11. Bitcasts from cv void* are
9500 // also static_casts, but we disallow them as a resolution to DR1312.
9501 if (!E->getType()->isVoidPointerType()) {
9502 // In some circumstances, we permit casting from void* to cv1 T*, when the
9503 // actual pointee object is actually a cv2 T.
9504 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
9505 !Result.IsNullPtr;
9506 bool VoidPtrCastMaybeOK =
9507 Result.IsNullPtr ||
9508 (HasValidResult &&
9509 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
9510 E->getType()->getPointeeType()));
9511 // 1. We'll allow it in std::allocator::allocate, and anything which that
9512 // calls.
9513 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9514 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9515 // We'll allow it in the body of std::source_location::current. GCC's
9516 // implementation had a parameter of type `void*`, and casts from
9517 // that back to `const __impl*` in its body.
9518 if (VoidPtrCastMaybeOK &&
9519 (Info.getStdAllocatorCaller("allocate") ||
9520 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
9521 Info.getLangOpts().CPlusPlus26)) {
9522 // Permitted.
9523 } else {
9524 if (SubExpr->getType()->isVoidPointerType() &&
9525 Info.getLangOpts().CPlusPlus) {
9526 if (HasValidResult)
9527 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
9528 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
9529 << Result.Designator.getType(Info.Ctx).getCanonicalType()
9530 << E->getType()->getPointeeType();
9531 else
9532 CCEDiag(E, diag::note_constexpr_invalid_cast)
9533 << 3 << SubExpr->getType();
9534 } else
9535 CCEDiag(E, diag::note_constexpr_invalid_cast)
9536 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9537 Result.Designator.setInvalid();
9538 }
9539 }
9540 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
9541 ZeroInitialization(E);
9542 return true;
9543
9544 case CK_DerivedToBase:
9545 case CK_UncheckedDerivedToBase:
9546 if (!evaluatePointer(E->getSubExpr(), Result))
9547 return false;
9548 if (!Result.Base && Result.Offset.isZero())
9549 return true;
9550
9551 // Now figure out the necessary offset to add to the base LV to get from
9552 // the derived class to the base class.
9553 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
9554 castAs<PointerType>()->getPointeeType(),
9555 Result);
9556
9557 case CK_BaseToDerived:
9558 if (!Visit(E->getSubExpr()))
9559 return false;
9560 if (!Result.Base && Result.Offset.isZero())
9561 return true;
9562 return HandleBaseToDerivedCast(Info, E, Result);
9563
9564 case CK_Dynamic:
9565 if (!Visit(E->getSubExpr()))
9566 return false;
9567 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
9568
9569 case CK_NullToPointer:
9570 VisitIgnoredValue(E->getSubExpr());
9571 return ZeroInitialization(E);
9572
9573 case CK_IntegralToPointer: {
9574 CCEDiag(E, diag::note_constexpr_invalid_cast)
9575 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9576
9577 APValue Value;
9578 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
9579 break;
9580
9581 if (Value.isInt()) {
9582 unsigned Size = Info.Ctx.getTypeSize(E->getType());
9583 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
9584 Result.Base = (Expr*)nullptr;
9585 Result.InvalidBase = false;
9586 Result.Offset = CharUnits::fromQuantity(N);
9587 Result.Designator.setInvalid();
9588 Result.IsNullPtr = false;
9589 return true;
9590 } else {
9591 // In rare instances, the value isn't an lvalue.
9592 // For example, when the value is the difference between the addresses of
9593 // two labels. We reject that as a constant expression because we can't
9594 // compute a valid offset to convert into a pointer.
9595 if (!Value.isLValue())
9596 return false;
9597
9598 // Cast is of an lvalue, no need to change value.
9599 Result.setFrom(Info.Ctx, Value);
9600 return true;
9601 }
9602 }
9603
9604 case CK_ArrayToPointerDecay: {
9605 if (SubExpr->isGLValue()) {
9606 if (!evaluateLValue(SubExpr, Result))
9607 return false;
9608 } else {
9609 APValue &Value = Info.CurrentCall->createTemporary(
9610 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
9611 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
9612 return false;
9613 }
9614 // The result is a pointer to the first element of the array.
9615 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
9616 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
9617 Result.addArray(Info, E, CAT);
9618 else
9619 Result.addUnsizedArray(Info, E, AT->getElementType());
9620 return true;
9621 }
9622
9623 case CK_FunctionToPointerDecay:
9624 return evaluateLValue(SubExpr, Result);
9625
9626 case CK_LValueToRValue: {
9627 LValue LVal;
9628 if (!evaluateLValue(E->getSubExpr(), LVal))
9629 return false;
9630
9631 APValue RVal;
9632 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9633 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9634 LVal, RVal))
9635 return InvalidBaseOK &&
9636 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9637 return Success(RVal, E);
9638 }
9639 }
9640
9641 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9642}
9643
9645 UnaryExprOrTypeTrait ExprKind) {
9646 // C++ [expr.alignof]p3:
9647 // When alignof is applied to a reference type, the result is the
9648 // alignment of the referenced type.
9649 T = T.getNonReferenceType();
9650
9651 if (T.getQualifiers().hasUnaligned())
9652 return CharUnits::One();
9653
9654 const bool AlignOfReturnsPreferred =
9655 Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9656
9657 // __alignof is defined to return the preferred alignment.
9658 // Before 8, clang returned the preferred alignment for alignof and _Alignof
9659 // as well.
9660 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9661 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
9662 // alignof and _Alignof are defined to return the ABI alignment.
9663 else if (ExprKind == UETT_AlignOf)
9664 return Ctx.getTypeAlignInChars(T.getTypePtr());
9665 else
9666 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9667}
9668
9670 UnaryExprOrTypeTrait ExprKind) {
9671 E = E->IgnoreParens();
9672
9673 // The kinds of expressions that we have special-case logic here for
9674 // should be kept up to date with the special checks for those
9675 // expressions in Sema.
9676
9677 // alignof decl is always accepted, even if it doesn't make sense: we default
9678 // to 1 in those cases.
9679 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9680 return Ctx.getDeclAlign(DRE->getDecl(),
9681 /*RefAsPointee*/ true);
9682
9683 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9684 return Ctx.getDeclAlign(ME->getMemberDecl(),
9685 /*RefAsPointee*/ true);
9686
9687 return GetAlignOfType(Ctx, E->getType(), ExprKind);
9688}
9689
9690static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9691 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9692 return Info.Ctx.getDeclAlign(VD);
9693 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9694 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
9695 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
9696}
9697
9698/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9699/// __builtin_is_aligned and __builtin_assume_aligned.
9700static bool getAlignmentArgument(const Expr *E, QualType ForType,
9701 EvalInfo &Info, APSInt &Alignment) {
9702 if (!EvaluateInteger(E, Alignment, Info))
9703 return false;
9704 if (Alignment < 0 || !Alignment.isPowerOf2()) {
9705 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9706 return false;
9707 }
9708 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9709 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9710 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9711 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9712 << MaxValue << ForType << Alignment;
9713 return false;
9714 }
9715 // Ensure both alignment and source value have the same bit width so that we
9716 // don't assert when computing the resulting value.
9717 APSInt ExtAlignment =
9718 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9719 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9720 "Alignment should not be changed by ext/trunc");
9721 Alignment = ExtAlignment;
9722 assert(Alignment.getBitWidth() == SrcWidth);
9723 return true;
9724}
9725
9726// To be clear: this happily visits unsupported builtins. Better name welcomed.
9727bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9728 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9729 return true;
9730
9731 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9732 return false;
9733
9734 Result.setInvalid(E);
9735 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9736 Result.addUnsizedArray(Info, E, PointeeTy);
9737 return true;
9738}
9739
9740bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9741 if (!IsConstantEvaluatedBuiltinCall(E))
9742 return visitNonBuiltinCallExpr(E);
9743 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9744}
9745
9746// Determine if T is a character type for which we guarantee that
9747// sizeof(T) == 1.
9749 return T->isCharType() || T->isChar8Type();
9750}
9751
9752bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9753 unsigned BuiltinOp) {
9755 return Success(E);
9756
9757 switch (BuiltinOp) {
9758 case Builtin::BIaddressof:
9759 case Builtin::BI__addressof:
9760 case Builtin::BI__builtin_addressof:
9761 return evaluateLValue(E->getArg(0), Result);
9762 case Builtin::BI__builtin_assume_aligned: {
9763 // We need to be very careful here because: if the pointer does not have the
9764 // asserted alignment, then the behavior is undefined, and undefined
9765 // behavior is non-constant.
9766 if (!evaluatePointer(E->getArg(0), Result))
9767 return false;
9768
9769 LValue OffsetResult(Result);
9770 APSInt Alignment;
9771 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9772 Alignment))
9773 return false;
9774 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9775
9776 if (E->getNumArgs() > 2) {
9777 APSInt Offset;
9778 if (!EvaluateInteger(E->getArg(2), Offset, Info))
9779 return false;
9780
9781 int64_t AdditionalOffset = -Offset.getZExtValue();
9782 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9783 }
9784
9785 // If there is a base object, then it must have the correct alignment.
9786 if (OffsetResult.Base) {
9787 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9788
9789 if (BaseAlignment < Align) {
9790 Result.Designator.setInvalid();
9791 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
9792 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
9793 return false;
9794 }
9795 }
9796
9797 // The offset must also have the correct alignment.
9798 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9799 Result.Designator.setInvalid();
9800
9801 (OffsetResult.Base
9802 ? CCEDiag(E->getArg(0),
9803 diag::note_constexpr_baa_insufficient_alignment)
9804 << 1
9805 : CCEDiag(E->getArg(0),
9806 diag::note_constexpr_baa_value_insufficient_alignment))
9807 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
9808 return false;
9809 }
9810
9811 return true;
9812 }
9813 case Builtin::BI__builtin_align_up:
9814 case Builtin::BI__builtin_align_down: {
9815 if (!evaluatePointer(E->getArg(0), Result))
9816 return false;
9817 APSInt Alignment;
9818 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9819 Alignment))
9820 return false;
9821 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9822 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9823 // For align_up/align_down, we can return the same value if the alignment
9824 // is known to be greater or equal to the requested value.
9825 if (PtrAlign.getQuantity() >= Alignment)
9826 return true;
9827
9828 // The alignment could be greater than the minimum at run-time, so we cannot
9829 // infer much about the resulting pointer value. One case is possible:
9830 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9831 // can infer the correct index if the requested alignment is smaller than
9832 // the base alignment so we can perform the computation on the offset.
9833 if (BaseAlignment.getQuantity() >= Alignment) {
9834 assert(Alignment.getBitWidth() <= 64 &&
9835 "Cannot handle > 64-bit address-space");
9836 uint64_t Alignment64 = Alignment.getZExtValue();
9838 BuiltinOp == Builtin::BI__builtin_align_down
9839 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9840 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9841 Result.adjustOffset(NewOffset - Result.Offset);
9842 // TODO: diagnose out-of-bounds values/only allow for arrays?
9843 return true;
9844 }
9845 // Otherwise, we cannot constant-evaluate the result.
9846 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9847 << Alignment;
9848 return false;
9849 }
9850 case Builtin::BI__builtin_operator_new:
9851 return HandleOperatorNewCall(Info, E, Result);
9852 case Builtin::BI__builtin_launder:
9853 return evaluatePointer(E->getArg(0), Result);
9854 case Builtin::BIstrchr:
9855 case Builtin::BIwcschr:
9856 case Builtin::BImemchr:
9857 case Builtin::BIwmemchr:
9858 if (Info.getLangOpts().CPlusPlus11)
9859 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9860 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9861 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
9862 else
9863 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9864 [[fallthrough]];
9865 case Builtin::BI__builtin_strchr:
9866 case Builtin::BI__builtin_wcschr:
9867 case Builtin::BI__builtin_memchr:
9868 case Builtin::BI__builtin_char_memchr:
9869 case Builtin::BI__builtin_wmemchr: {
9870 if (!Visit(E->getArg(0)))
9871 return false;
9872 APSInt Desired;
9873 if (!EvaluateInteger(E->getArg(1), Desired, Info))
9874 return false;
9875 uint64_t MaxLength = uint64_t(-1);
9876 if (BuiltinOp != Builtin::BIstrchr &&
9877 BuiltinOp != Builtin::BIwcschr &&
9878 BuiltinOp != Builtin::BI__builtin_strchr &&
9879 BuiltinOp != Builtin::BI__builtin_wcschr) {
9880 APSInt N;
9881 if (!EvaluateInteger(E->getArg(2), N, Info))
9882 return false;
9883 MaxLength = N.getZExtValue();
9884 }
9885 // We cannot find the value if there are no candidates to match against.
9886 if (MaxLength == 0u)
9887 return ZeroInitialization(E);
9888 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9889 Result.Designator.Invalid)
9890 return false;
9891 QualType CharTy = Result.Designator.getType(Info.Ctx);
9892 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9893 BuiltinOp == Builtin::BI__builtin_memchr;
9894 assert(IsRawByte ||
9895 Info.Ctx.hasSameUnqualifiedType(
9896 CharTy, E->getArg(0)->getType()->getPointeeType()));
9897 // Pointers to const void may point to objects of incomplete type.
9898 if (IsRawByte && CharTy->isIncompleteType()) {
9899 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9900 return false;
9901 }
9902 // Give up on byte-oriented matching against multibyte elements.
9903 // FIXME: We can compare the bytes in the correct order.
9904 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9905 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9906 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
9907 return false;
9908 }
9909 // Figure out what value we're actually looking for (after converting to
9910 // the corresponding unsigned type if necessary).
9911 uint64_t DesiredVal;
9912 bool StopAtNull = false;
9913 switch (BuiltinOp) {
9914 case Builtin::BIstrchr:
9915 case Builtin::BI__builtin_strchr:
9916 // strchr compares directly to the passed integer, and therefore
9917 // always fails if given an int that is not a char.
9918 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9919 E->getArg(1)->getType(),
9920 Desired),
9921 Desired))
9922 return ZeroInitialization(E);
9923 StopAtNull = true;
9924 [[fallthrough]];
9925 case Builtin::BImemchr:
9926 case Builtin::BI__builtin_memchr:
9927 case Builtin::BI__builtin_char_memchr:
9928 // memchr compares by converting both sides to unsigned char. That's also
9929 // correct for strchr if we get this far (to cope with plain char being
9930 // unsigned in the strchr case).
9931 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9932 break;
9933
9934 case Builtin::BIwcschr:
9935 case Builtin::BI__builtin_wcschr:
9936 StopAtNull = true;
9937 [[fallthrough]];
9938 case Builtin::BIwmemchr:
9939 case Builtin::BI__builtin_wmemchr:
9940 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9941 DesiredVal = Desired.getZExtValue();
9942 break;
9943 }
9944
9945 for (; MaxLength; --MaxLength) {
9946 APValue Char;
9947 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9948 !Char.isInt())
9949 return false;
9950 if (Char.getInt().getZExtValue() == DesiredVal)
9951 return true;
9952 if (StopAtNull && !Char.getInt())
9953 break;
9954 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9955 return false;
9956 }
9957 // Not found: return nullptr.
9958 return ZeroInitialization(E);
9959 }
9960
9961 case Builtin::BImemcpy:
9962 case Builtin::BImemmove:
9963 case Builtin::BIwmemcpy:
9964 case Builtin::BIwmemmove:
9965 if (Info.getLangOpts().CPlusPlus11)
9966 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9967 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9968 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
9969 else
9970 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9971 [[fallthrough]];
9972 case Builtin::BI__builtin_memcpy:
9973 case Builtin::BI__builtin_memmove:
9974 case Builtin::BI__builtin_wmemcpy:
9975 case Builtin::BI__builtin_wmemmove: {
9976 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9977 BuiltinOp == Builtin::BIwmemmove ||
9978 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9979 BuiltinOp == Builtin::BI__builtin_wmemmove;
9980 bool Move = BuiltinOp == Builtin::BImemmove ||
9981 BuiltinOp == Builtin::BIwmemmove ||
9982 BuiltinOp == Builtin::BI__builtin_memmove ||
9983 BuiltinOp == Builtin::BI__builtin_wmemmove;
9984
9985 // The result of mem* is the first argument.
9986 if (!Visit(E->getArg(0)))
9987 return false;
9988 LValue Dest = Result;
9989
9990 LValue Src;
9991 if (!EvaluatePointer(E->getArg(1), Src, Info))
9992 return false;
9993
9994 APSInt N;
9995 if (!EvaluateInteger(E->getArg(2), N, Info))
9996 return false;
9997 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9998
9999 // If the size is zero, we treat this as always being a valid no-op.
10000 // (Even if one of the src and dest pointers is null.)
10001 if (!N)
10002 return true;
10003
10004 // Otherwise, if either of the operands is null, we can't proceed. Don't
10005 // try to determine the type of the copied objects, because there aren't
10006 // any.
10007 if (!Src.Base || !Dest.Base) {
10008 APValue Val;
10009 (!Src.Base ? Src : Dest).moveInto(Val);
10010 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10011 << Move << WChar << !!Src.Base
10012 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10013 return false;
10014 }
10015 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10016 return false;
10017
10018 // We require that Src and Dest are both pointers to arrays of
10019 // trivially-copyable type. (For the wide version, the designator will be
10020 // invalid if the designated object is not a wchar_t.)
10021 QualType T = Dest.Designator.getType(Info.Ctx);
10022 QualType SrcT = Src.Designator.getType(Info.Ctx);
10023 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10024 // FIXME: Consider using our bit_cast implementation to support this.
10025 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10026 return false;
10027 }
10028 if (T->isIncompleteType()) {
10029 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10030 return false;
10031 }
10032 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10033 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10034 return false;
10035 }
10036
10037 // Figure out how many T's we're copying.
10038 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10039 if (TSize == 0)
10040 return false;
10041 if (!WChar) {
10042 uint64_t Remainder;
10043 llvm::APInt OrigN = N;
10044 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10045 if (Remainder) {
10046 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10047 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10048 << (unsigned)TSize;
10049 return false;
10050 }
10051 }
10052
10053 // Check that the copying will remain within the arrays, just so that we
10054 // can give a more meaningful diagnostic. This implicitly also checks that
10055 // N fits into 64 bits.
10056 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10057 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10058 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10059 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10060 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10061 << toString(N, 10, /*Signed*/false);
10062 return false;
10063 }
10064 uint64_t NElems = N.getZExtValue();
10065 uint64_t NBytes = NElems * TSize;
10066
10067 // Check for overlap.
10068 int Direction = 1;
10069 if (HasSameBase(Src, Dest)) {
10070 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10071 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10072 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10073 // Dest is inside the source region.
10074 if (!Move) {
10075 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10076 return false;
10077 }
10078 // For memmove and friends, copy backwards.
10079 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10080 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10081 return false;
10082 Direction = -1;
10083 } else if (!Move && SrcOffset >= DestOffset &&
10084 SrcOffset - DestOffset < NBytes) {
10085 // Src is inside the destination region for memcpy: invalid.
10086 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10087 return false;
10088 }
10089 }
10090
10091 while (true) {
10092 APValue Val;
10093 // FIXME: Set WantObjectRepresentation to true if we're copying a
10094 // char-like type?
10095 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10096 !handleAssignment(Info, E, Dest, T, Val))
10097 return false;
10098 // Do not iterate past the last element; if we're copying backwards, that
10099 // might take us off the start of the array.
10100 if (--NElems == 0)
10101 return true;
10102 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10103 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10104 return false;
10105 }
10106 }
10107
10108 default:
10109 return false;
10110 }
10111}
10112
10113static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10114 APValue &Result, const InitListExpr *ILE,
10115 QualType AllocType);
10116static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10117 APValue &Result,
10118 const CXXConstructExpr *CCE,
10119 QualType AllocType);
10120
10121bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10122 if (!Info.getLangOpts().CPlusPlus20)
10123 Info.CCEDiag(E, diag::note_constexpr_new);
10124
10125 // We cannot speculatively evaluate a delete expression.
10126 if (Info.SpeculativeEvaluationDepth)
10127 return false;
10128
10129 FunctionDecl *OperatorNew = E->getOperatorNew();
10130 QualType AllocType = E->getAllocatedType();
10131 QualType TargetType = AllocType;
10132
10133 bool IsNothrow = false;
10134 bool IsPlacement = false;
10135
10136 if (E->getNumPlacementArgs() == 1 &&
10137 E->getPlacementArg(0)->getType()->isNothrowT()) {
10138 // The only new-placement list we support is of the form (std::nothrow).
10139 //
10140 // FIXME: There is no restriction on this, but it's not clear that any
10141 // other form makes any sense. We get here for cases such as:
10142 //
10143 // new (std::align_val_t{N}) X(int)
10144 //
10145 // (which should presumably be valid only if N is a multiple of
10146 // alignof(int), and in any case can't be deallocated unless N is
10147 // alignof(X) and X has new-extended alignment).
10148 LValue Nothrow;
10149 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10150 return false;
10151 IsNothrow = true;
10152 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10153 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10154 (Info.CurrentCall->CanEvalMSConstexpr &&
10155 OperatorNew->hasAttr<MSConstexprAttr>())) {
10156 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10157 return false;
10158 if (Result.Designator.Invalid)
10159 return false;
10160 TargetType = E->getPlacementArg(0)->getType();
10161 IsPlacement = true;
10162 } else {
10163 Info.FFDiag(E, diag::note_constexpr_new_placement)
10164 << /*C++26 feature*/ 1 << E->getSourceRange();
10165 return false;
10166 }
10167 } else if (E->getNumPlacementArgs()) {
10168 Info.FFDiag(E, diag::note_constexpr_new_placement)
10169 << /*Unsupported*/ 0 << E->getSourceRange();
10170 return false;
10171 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
10172 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10173 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10174 return false;
10175 }
10176
10177 const Expr *Init = E->getInitializer();
10178 const InitListExpr *ResizedArrayILE = nullptr;
10179 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10180 bool ValueInit = false;
10181
10182 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10183 const Expr *Stripped = *ArraySize;
10184 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10185 Stripped = ICE->getSubExpr())
10186 if (ICE->getCastKind() != CK_NoOp &&
10187 ICE->getCastKind() != CK_IntegralCast)
10188 break;
10189
10190 llvm::APSInt ArrayBound;
10191 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10192 return false;
10193
10194 // C++ [expr.new]p9:
10195 // The expression is erroneous if:
10196 // -- [...] its value before converting to size_t [or] applying the
10197 // second standard conversion sequence is less than zero
10198 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10199 if (IsNothrow)
10200 return ZeroInitialization(E);
10201
10202 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10203 << ArrayBound << (*ArraySize)->getSourceRange();
10204 return false;
10205 }
10206
10207 // -- its value is such that the size of the allocated object would
10208 // exceed the implementation-defined limit
10209 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10211 Info.Ctx, AllocType, ArrayBound),
10212 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10213 if (IsNothrow)
10214 return ZeroInitialization(E);
10215 return false;
10216 }
10217
10218 // -- the new-initializer is a braced-init-list and the number of
10219 // array elements for which initializers are provided [...]
10220 // exceeds the number of elements to initialize
10221 if (!Init) {
10222 // No initialization is performed.
10223 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10224 isa<ImplicitValueInitExpr>(Init)) {
10225 ValueInit = true;
10226 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10227 ResizedArrayCCE = CCE;
10228 } else {
10229 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10230 assert(CAT && "unexpected type for array initializer");
10231
10232 unsigned Bits =
10233 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10234 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10235 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10236 if (InitBound.ugt(AllocBound)) {
10237 if (IsNothrow)
10238 return ZeroInitialization(E);
10239
10240 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10241 << toString(AllocBound, 10, /*Signed=*/false)
10242 << toString(InitBound, 10, /*Signed=*/false)
10243 << (*ArraySize)->getSourceRange();
10244 return false;
10245 }
10246
10247 // If the sizes differ, we must have an initializer list, and we need
10248 // special handling for this case when we initialize.
10249 if (InitBound != AllocBound)
10250 ResizedArrayILE = cast<InitListExpr>(Init);
10251 }
10252
10253 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10254 ArraySizeModifier::Normal, 0);
10255 } else {
10256 assert(!AllocType->isArrayType() &&
10257 "array allocation with non-array new");
10258 }
10259
10260 APValue *Val;
10261 if (IsPlacement) {
10263 struct FindObjectHandler {
10264 EvalInfo &Info;
10265 const Expr *E;
10266 QualType AllocType;
10267 const AccessKinds AccessKind;
10268 APValue *Value;
10269
10270 typedef bool result_type;
10271 bool failed() { return false; }
10272 bool found(APValue &Subobj, QualType SubobjType) {
10273 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10274 // old name of the object to be used to name the new object.
10275 unsigned SubobjectSize = 1;
10276 unsigned AllocSize = 1;
10277 if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10278 AllocSize = CAT->getZExtSize();
10279 if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10280 SubobjectSize = CAT->getZExtSize();
10281 if (SubobjectSize < AllocSize ||
10282 !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10283 Info.Ctx.getBaseElementType(AllocType))) {
10284 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10285 << SubobjType << AllocType;
10286 return false;
10287 }
10288 Value = &Subobj;
10289 return true;
10290 }
10291 bool found(APSInt &Value, QualType SubobjType) {
10292 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10293 return false;
10294 }
10295 bool found(APFloat &Value, QualType SubobjType) {
10296 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10297 return false;
10298 }
10299 } Handler = {Info, E, AllocType, AK, nullptr};
10300
10301 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10302 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10303 return false;
10304
10305 Val = Handler.Value;
10306
10307 // [basic.life]p1:
10308 // The lifetime of an object o of type T ends when [...] the storage
10309 // which the object occupies is [...] reused by an object that is not
10310 // nested within o (6.6.2).
10311 *Val = APValue();
10312 } else {
10313 // Perform the allocation and obtain a pointer to the resulting object.
10314 Val = Info.createHeapAlloc(E, AllocType, Result);
10315 if (!Val)
10316 return false;
10317 }
10318
10319 if (ValueInit) {
10320 ImplicitValueInitExpr VIE(AllocType);
10321 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10322 return false;
10323 } else if (ResizedArrayILE) {
10324 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10325 AllocType))
10326 return false;
10327 } else if (ResizedArrayCCE) {
10328 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10329 AllocType))
10330 return false;
10331 } else if (Init) {
10332 if (!EvaluateInPlace(*Val, Info, Result, Init))
10333 return false;
10334 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10335 return false;
10336 }
10337
10338 // Array new returns a pointer to the first element, not a pointer to the
10339 // array.
10340 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10341 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10342
10343 return true;
10344}
10345//===----------------------------------------------------------------------===//
10346// Member Pointer Evaluation
10347//===----------------------------------------------------------------------===//
10348
10349namespace {
10350class MemberPointerExprEvaluator
10351 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10352 MemberPtr &Result;
10353
10354 bool Success(const ValueDecl *D) {
10355 Result = MemberPtr(D);
10356 return true;
10357 }
10358public:
10359
10360 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10361 : ExprEvaluatorBaseTy(Info), Result(Result) {}
10362
10363 bool Success(const APValue &V, const Expr *E) {
10364 Result.setFrom(V);
10365 return true;
10366 }
10367 bool ZeroInitialization(const Expr *E) {
10368 return Success((const ValueDecl*)nullptr);
10369 }
10370
10371 bool VisitCastExpr(const CastExpr *E);
10372 bool VisitUnaryAddrOf(const UnaryOperator *E);
10373};
10374} // end anonymous namespace
10375
10376static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10377 EvalInfo &Info) {
10378 assert(!E->isValueDependent());
10379 assert(E->isPRValue() && E->getType()->isMemberPointerType());
10380 return MemberPointerExprEvaluator(Info, Result).Visit(E);
10381}
10382
10383bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10384 switch (E->getCastKind()) {
10385 default:
10386 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10387
10388 case CK_NullToMemberPointer:
10389 VisitIgnoredValue(E->getSubExpr());
10390 return ZeroInitialization(E);
10391
10392 case CK_BaseToDerivedMemberPointer: {
10393 if (!Visit(E->getSubExpr()))
10394 return false;
10395 if (E->path_empty())
10396 return true;
10397 // Base-to-derived member pointer casts store the path in derived-to-base
10398 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10399 // the wrong end of the derived->base arc, so stagger the path by one class.
10400 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10401 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10402 PathI != PathE; ++PathI) {
10403 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10404 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10405 if (!Result.castToDerived(Derived))
10406 return Error(E);
10407 }
10408 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
10409 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
10410 return Error(E);
10411 return true;
10412 }
10413
10414 case CK_DerivedToBaseMemberPointer:
10415 if (!Visit(E->getSubExpr()))
10416 return false;
10417 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10418 PathE = E->path_end(); PathI != PathE; ++PathI) {
10419 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10420 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10421 if (!Result.castToBase(Base))
10422 return Error(E);
10423 }
10424 return true;
10425 }
10426}
10427
10428bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10429 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
10430 // member can be formed.
10431 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
10432}
10433
10434//===----------------------------------------------------------------------===//
10435// Record Evaluation
10436//===----------------------------------------------------------------------===//
10437
10438namespace {
10439 class RecordExprEvaluator
10440 : public ExprEvaluatorBase<RecordExprEvaluator> {
10441 const LValue &This;
10442 APValue &Result;
10443 public:
10444
10445 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
10446 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
10447
10448 bool Success(const APValue &V, const Expr *E) {
10449 Result = V;
10450 return true;
10451 }
10452 bool ZeroInitialization(const Expr *E) {
10453 return ZeroInitialization(E, E->getType());
10454 }
10455 bool ZeroInitialization(const Expr *E, QualType T);
10456
10457 bool VisitCallExpr(const CallExpr *E) {
10458 return handleCallExpr(E, Result, &This);
10459 }
10460 bool VisitCastExpr(const CastExpr *E);
10461 bool VisitInitListExpr(const InitListExpr *E);
10462 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10463 return VisitCXXConstructExpr(E, E->getType());
10464 }
10465 bool VisitLambdaExpr(const LambdaExpr *E);
10466 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
10467 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
10468 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
10469 bool VisitBinCmp(const BinaryOperator *E);
10470 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10471 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10472 ArrayRef<Expr *> Args);
10473 };
10474}
10475
10476/// Perform zero-initialization on an object of non-union class type.
10477/// C++11 [dcl.init]p5:
10478/// To zero-initialize an object or reference of type T means:
10479/// [...]
10480/// -- if T is a (possibly cv-qualified) non-union class type,
10481/// each non-static data member and each base-class subobject is
10482/// zero-initialized
10483static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
10484 const RecordDecl *RD,
10485 const LValue &This, APValue &Result) {
10486 assert(!RD->isUnion() && "Expected non-union class type");
10487 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
10488 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
10489 std::distance(RD->field_begin(), RD->field_end()));
10490
10491 if (RD->isInvalidDecl()) return false;
10492 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10493
10494 if (CD) {
10495 unsigned Index = 0;
10497 End = CD->bases_end(); I != End; ++I, ++Index) {
10498 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
10499 LValue Subobject = This;
10500 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
10501 return false;
10502 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
10503 Result.getStructBase(Index)))
10504 return false;
10505 }
10506 }
10507
10508 for (const auto *I : RD->fields()) {
10509 // -- if T is a reference type, no initialization is performed.
10510 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
10511 continue;
10512
10513 LValue Subobject = This;
10514 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
10515 return false;
10516
10517 ImplicitValueInitExpr VIE(I->getType());
10518 if (!EvaluateInPlace(
10519 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
10520 return false;
10521 }
10522
10523 return true;
10524}
10525
10526bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
10527 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
10528 if (RD->isInvalidDecl()) return false;
10529 if (RD->isUnion()) {
10530 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10531 // object's first non-static named data member is zero-initialized
10533 while (I != RD->field_end() && (*I)->isUnnamedBitField())
10534 ++I;
10535 if (I == RD->field_end()) {
10536 Result = APValue((const FieldDecl*)nullptr);
10537 return true;
10538 }
10539
10540 LValue Subobject = This;
10541 if (!HandleLValueMember(Info, E, Subobject, *I))
10542 return false;
10543 Result = APValue(*I);
10544 ImplicitValueInitExpr VIE(I->getType());
10545 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
10546 }
10547
10548 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
10549 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
10550 return false;
10551 }
10552
10553 return HandleClassZeroInitialization(Info, E, RD, This, Result);
10554}
10555
10556bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
10557 switch (E->getCastKind()) {
10558 default:
10559 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10560
10561 case CK_ConstructorConversion:
10562 return Visit(E->getSubExpr());
10563
10564 case CK_DerivedToBase:
10565 case CK_UncheckedDerivedToBase: {
10566 APValue DerivedObject;
10567 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
10568 return false;
10569 if (!DerivedObject.isStruct())
10570 return Error(E->getSubExpr());
10571
10572 // Derived-to-base rvalue conversion: just slice off the derived part.
10573 APValue *Value = &DerivedObject;
10574 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
10575 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10576 PathE = E->path_end(); PathI != PathE; ++PathI) {
10577 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10578 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10579 Value = &Value->getStructBase(getBaseIndex(RD, Base));
10580 RD = Base;
10581 }
10582 Result = *Value;
10583 return true;
10584 }
10585 }
10586}
10587
10588bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10589 if (E->isTransparent())
10590 return Visit(E->getInit(0));
10591 return VisitCXXParenListOrInitListExpr(E, E->inits());
10592}
10593
10594bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10595 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
10596 const RecordDecl *RD =
10597 ExprToVisit->getType()->castAs<RecordType>()->getDecl();
10598 if (RD->isInvalidDecl()) return false;
10599 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10600 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
10601
10602 EvalInfo::EvaluatingConstructorRAII EvalObj(
10603 Info,
10604 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
10605 CXXRD && CXXRD->getNumBases());
10606
10607 if (RD->isUnion()) {
10608 const FieldDecl *Field;
10609 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
10610 Field = ILE->getInitializedFieldInUnion();
10611 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
10612 Field = PLIE->getInitializedFieldInUnion();
10613 } else {
10614 llvm_unreachable(
10615 "Expression is neither an init list nor a C++ paren list");
10616 }
10617
10618 Result = APValue(Field);
10619 if (!Field)
10620 return true;
10621
10622 // If the initializer list for a union does not contain any elements, the
10623 // first element of the union is value-initialized.
10624 // FIXME: The element should be initialized from an initializer list.
10625 // Is this difference ever observable for initializer lists which
10626 // we don't build?
10627 ImplicitValueInitExpr VIE(Field->getType());
10628 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
10629
10630 LValue Subobject = This;
10631 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
10632 return false;
10633
10634 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10635 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10636 isa<CXXDefaultInitExpr>(InitExpr));
10637
10638 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10639 if (Field->isBitField())
10640 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10641 Field);
10642 return true;
10643 }
10644
10645 return false;
10646 }
10647
10648 if (!Result.hasValue())
10649 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10650 std::distance(RD->field_begin(), RD->field_end()));
10651 unsigned ElementNo = 0;
10652 bool Success = true;
10653
10654 // Initialize base classes.
10655 if (CXXRD && CXXRD->getNumBases()) {
10656 for (const auto &Base : CXXRD->bases()) {
10657 assert(ElementNo < Args.size() && "missing init for base class");
10658 const Expr *Init = Args[ElementNo];
10659
10660 LValue Subobject = This;
10661 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10662 return false;
10663
10664 APValue &FieldVal = Result.getStructBase(ElementNo);
10665 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10666 if (!Info.noteFailure())
10667 return false;
10668 Success = false;
10669 }
10670 ++ElementNo;
10671 }
10672
10673 EvalObj.finishedConstructingBases();
10674 }
10675
10676 // Initialize members.
10677 for (const auto *Field : RD->fields()) {
10678 // Anonymous bit-fields are not considered members of the class for
10679 // purposes of aggregate initialization.
10680 if (Field->isUnnamedBitField())
10681 continue;
10682
10683 LValue Subobject = This;
10684
10685 bool HaveInit = ElementNo < Args.size();
10686
10687 // FIXME: Diagnostics here should point to the end of the initializer
10688 // list, not the start.
10689 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10690 Subobject, Field, &Layout))
10691 return false;
10692
10693 // Perform an implicit value-initialization for members beyond the end of
10694 // the initializer list.
10695 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10696 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10697
10698 if (Field->getType()->isIncompleteArrayType()) {
10699 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10700 if (!CAT->isZeroSize()) {
10701 // Bail out for now. This might sort of "work", but the rest of the
10702 // code isn't really prepared to handle it.
10703 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10704 return false;
10705 }
10706 }
10707 }
10708
10709 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10710 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10711 isa<CXXDefaultInitExpr>(Init));
10712
10713 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10714 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10715 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10716 FieldVal, Field))) {
10717 if (!Info.noteFailure())
10718 return false;
10719 Success = false;
10720 }
10721 }
10722
10723 EvalObj.finishedConstructingFields();
10724
10725 return Success;
10726}
10727
10728bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10729 QualType T) {
10730 // Note that E's type is not necessarily the type of our class here; we might
10731 // be initializing an array element instead.
10732 const CXXConstructorDecl *FD = E->getConstructor();
10733 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10734
10735 bool ZeroInit = E->requiresZeroInitialization();
10736 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10737 // If we've already performed zero-initialization, we're already done.
10738 if (Result.hasValue())
10739 return true;
10740
10741 if (ZeroInit)
10742 return ZeroInitialization(E, T);
10743
10744 return handleDefaultInitValue(T, Result);
10745 }
10746
10747 const FunctionDecl *Definition = nullptr;
10748 auto Body = FD->getBody(Definition);
10749
10750 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10751 return false;
10752
10753 // Avoid materializing a temporary for an elidable copy/move constructor.
10754 if (E->isElidable() && !ZeroInit) {
10755 // FIXME: This only handles the simplest case, where the source object
10756 // is passed directly as the first argument to the constructor.
10757 // This should also handle stepping though implicit casts and
10758 // and conversion sequences which involve two steps, with a
10759 // conversion operator followed by a converting constructor.
10760 const Expr *SrcObj = E->getArg(0);
10761 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10762 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10763 if (const MaterializeTemporaryExpr *ME =
10764 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10765 return Visit(ME->getSubExpr());
10766 }
10767
10768 if (ZeroInit && !ZeroInitialization(E, T))
10769 return false;
10770
10771 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
10772 return HandleConstructorCall(E, This, Args,
10773 cast<CXXConstructorDecl>(Definition), Info,
10774 Result);
10775}
10776
10777bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10778 const CXXInheritedCtorInitExpr *E) {
10779 if (!Info.CurrentCall) {
10780 assert(Info.checkingPotentialConstantExpression());
10781 return false;
10782 }
10783
10784 const CXXConstructorDecl *FD = E->getConstructor();
10785 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10786 return false;
10787
10788 const FunctionDecl *Definition = nullptr;
10789 auto Body = FD->getBody(Definition);
10790
10791 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10792 return false;
10793
10794 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10795 cast<CXXConstructorDecl>(Definition), Info,
10796 Result);
10797}
10798
10799bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10802 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10803
10804 LValue Array;
10805 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10806 return false;
10807
10808 assert(ArrayType && "unexpected type for array initializer");
10809
10810 // Get a pointer to the first element of the array.
10811 Array.addArray(Info, E, ArrayType);
10812
10813 // FIXME: What if the initializer_list type has base classes, etc?
10814 Result = APValue(APValue::UninitStruct(), 0, 2);
10815 Array.moveInto(Result.getStructField(0));
10816
10817 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10818 RecordDecl::field_iterator Field = Record->field_begin();
10819 assert(Field != Record->field_end() &&
10820 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10822 "Expected std::initializer_list first field to be const E *");
10823 ++Field;
10824 assert(Field != Record->field_end() &&
10825 "Expected std::initializer_list to have two fields");
10826
10827 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
10828 // Length.
10829 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10830 } else {
10831 // End pointer.
10832 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10834 "Expected std::initializer_list second field to be const E *");
10835 if (!HandleLValueArrayAdjustment(Info, E, Array,
10837 ArrayType->getZExtSize()))
10838 return false;
10839 Array.moveInto(Result.getStructField(1));
10840 }
10841
10842 assert(++Field == Record->field_end() &&
10843 "Expected std::initializer_list to only have two fields");
10844
10845 return true;
10846}
10847
10848bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10849 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10850 if (ClosureClass->isInvalidDecl())
10851 return false;
10852
10853 const size_t NumFields =
10854 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10855
10856 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10857 E->capture_init_end()) &&
10858 "The number of lambda capture initializers should equal the number of "
10859 "fields within the closure type");
10860
10861 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10862 // Iterate through all the lambda's closure object's fields and initialize
10863 // them.
10864 auto *CaptureInitIt = E->capture_init_begin();
10865 bool Success = true;
10866 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10867 for (const auto *Field : ClosureClass->fields()) {
10868 assert(CaptureInitIt != E->capture_init_end());
10869 // Get the initializer for this field
10870 Expr *const CurFieldInit = *CaptureInitIt++;
10871
10872 // If there is no initializer, either this is a VLA or an error has
10873 // occurred.
10874 if (!CurFieldInit)
10875 return Error(E);
10876
10877 LValue Subobject = This;
10878
10879 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10880 return false;
10881
10882 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10883 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10884 if (!Info.keepEvaluatingAfterFailure())
10885 return false;
10886 Success = false;
10887 }
10888 }
10889 return Success;
10890}
10891
10892static bool EvaluateRecord(const Expr *E, const LValue &This,
10893 APValue &Result, EvalInfo &Info) {
10894 assert(!E->isValueDependent());
10895 assert(E->isPRValue() && E->getType()->isRecordType() &&
10896 "can't evaluate expression as a record rvalue");
10897 return RecordExprEvaluator(Info, This, Result).Visit(E);
10898}
10899
10900//===----------------------------------------------------------------------===//
10901// Temporary Evaluation
10902//
10903// Temporaries are represented in the AST as rvalues, but generally behave like
10904// lvalues. The full-object of which the temporary is a subobject is implicitly
10905// materialized so that a reference can bind to it.
10906//===----------------------------------------------------------------------===//
10907namespace {
10908class TemporaryExprEvaluator
10909 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10910public:
10911 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10912 LValueExprEvaluatorBaseTy(Info, Result, false) {}
10913
10914 /// Visit an expression which constructs the value of this temporary.
10915 bool VisitConstructExpr(const Expr *E) {
10916 APValue &Value = Info.CurrentCall->createTemporary(
10917 E, E->getType(), ScopeKind::FullExpression, Result);
10918 return EvaluateInPlace(Value, Info, Result, E);
10919 }
10920
10921 bool VisitCastExpr(const CastExpr *E) {
10922 switch (E->getCastKind()) {
10923 default:
10924 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10925
10926 case CK_ConstructorConversion:
10927 return VisitConstructExpr(E->getSubExpr());
10928 }
10929 }
10930 bool VisitInitListExpr(const InitListExpr *E) {
10931 return VisitConstructExpr(E);
10932 }
10933 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10934 return VisitConstructExpr(E);
10935 }
10936 bool VisitCallExpr(const CallExpr *E) {
10937 return VisitConstructExpr(E);
10938 }
10939 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10940 return VisitConstructExpr(E);
10941 }
10942 bool VisitLambdaExpr(const LambdaExpr *E) {
10943 return VisitConstructExpr(E);
10944 }
10945};
10946} // end anonymous namespace
10947
10948/// Evaluate an expression of record type as a temporary.
10949static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10950 assert(!E->isValueDependent());
10951 assert(E->isPRValue() && E->getType()->isRecordType());
10952 return TemporaryExprEvaluator(Info, Result).Visit(E);
10953}
10954
10955//===----------------------------------------------------------------------===//
10956// Vector Evaluation
10957//===----------------------------------------------------------------------===//
10958
10959namespace {
10960 class VectorExprEvaluator
10961 : public ExprEvaluatorBase<VectorExprEvaluator> {
10962 APValue &Result;
10963 public:
10964
10965 VectorExprEvaluator(EvalInfo &info, APValue &Result)
10966 : ExprEvaluatorBaseTy(info), Result(Result) {}
10967
10968 bool Success(ArrayRef<APValue> V, const Expr *E) {
10969 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10970 // FIXME: remove this APValue copy.
10971 Result = APValue(V.data(), V.size());
10972 return true;
10973 }
10974 bool Success(const APValue &V, const Expr *E) {
10975 assert(V.isVector());
10976 Result = V;
10977 return true;
10978 }
10979 bool ZeroInitialization(const Expr *E);
10980
10981 bool VisitUnaryReal(const UnaryOperator *E)
10982 { return Visit(E->getSubExpr()); }
10983 bool VisitCastExpr(const CastExpr* E);
10984 bool VisitInitListExpr(const InitListExpr *E);
10985 bool VisitUnaryImag(const UnaryOperator *E);
10986 bool VisitBinaryOperator(const BinaryOperator *E);
10987 bool VisitUnaryOperator(const UnaryOperator *E);
10988 bool VisitCallExpr(const CallExpr *E);
10989 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
10990 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
10991
10992 // FIXME: Missing: conditional operator (for GNU
10993 // conditional select), ExtVectorElementExpr
10994 };
10995} // end anonymous namespace
10996
10997static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10998 assert(E->isPRValue() && E->getType()->isVectorType() &&
10999 "not a vector prvalue");
11000 return VectorExprEvaluator(Info, Result).Visit(E);
11001}
11002
11003bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11004 const VectorType *VTy = E->getType()->castAs<VectorType>();
11005 unsigned NElts = VTy->getNumElements();
11006
11007 const Expr *SE = E->getSubExpr();
11008 QualType SETy = SE->getType();
11009
11010 switch (E->getCastKind()) {
11011 case CK_VectorSplat: {
11012 APValue Val = APValue();
11013 if (SETy->isIntegerType()) {
11014 APSInt IntResult;
11015 if (!EvaluateInteger(SE, IntResult, Info))
11016 return false;
11017 Val = APValue(std::move(IntResult));
11018 } else if (SETy->isRealFloatingType()) {
11019 APFloat FloatResult(0.0);
11020 if (!EvaluateFloat(SE, FloatResult, Info))
11021 return false;
11022 Val = APValue(std::move(FloatResult));
11023 } else {
11024 return Error(E);
11025 }
11026
11027 // Splat and create vector APValue.
11028 SmallVector<APValue, 4> Elts(NElts, Val);
11029 return Success(Elts, E);
11030 }
11031 case CK_BitCast: {
11032 APValue SVal;
11033 if (!Evaluate(SVal, Info, SE))
11034 return false;
11035
11036 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11037 // Give up if the input isn't an int, float, or vector. For example, we
11038 // reject "(v4i16)(intptr_t)&a".
11039 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11040 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
11041 return false;
11042 }
11043
11044 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11045 return false;
11046
11047 return true;
11048 }
11049 case CK_HLSLVectorTruncation: {
11050 APValue Val;
11051 SmallVector<APValue, 4> Elements;
11052 if (!EvaluateVector(SE, Val, Info))
11053 return Error(E);
11054 for (unsigned I = 0; I < NElts; I++)
11055 Elements.push_back(Val.getVectorElt(I));
11056 return Success(Elements, E);
11057 }
11058 default:
11059 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11060 }
11061}
11062
11063bool
11064VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11065 const VectorType *VT = E->getType()->castAs<VectorType>();
11066 unsigned NumInits = E->getNumInits();
11067 unsigned NumElements = VT->getNumElements();
11068
11069 QualType EltTy = VT->getElementType();
11070 SmallVector<APValue, 4> Elements;
11071
11072 // The number of initializers can be less than the number of
11073 // vector elements. For OpenCL, this can be due to nested vector
11074 // initialization. For GCC compatibility, missing trailing elements
11075 // should be initialized with zeroes.
11076 unsigned CountInits = 0, CountElts = 0;
11077 while (CountElts < NumElements) {
11078 // Handle nested vector initialization.
11079 if (CountInits < NumInits
11080 && E->getInit(CountInits)->getType()->isVectorType()) {
11081 APValue v;
11082 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11083 return Error(E);
11084 unsigned vlen = v.getVectorLength();
11085 for (unsigned j = 0; j < vlen; j++)
11086 Elements.push_back(v.getVectorElt(j));
11087 CountElts += vlen;
11088 } else if (EltTy->isIntegerType()) {
11089 llvm::APSInt sInt(32);
11090 if (CountInits < NumInits) {
11091 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11092 return false;
11093 } else // trailing integer zero.
11094 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11095 Elements.push_back(APValue(sInt));
11096 CountElts++;
11097 } else {
11098 llvm::APFloat f(0.0);
11099 if (CountInits < NumInits) {
11100 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11101 return false;
11102 } else // trailing float zero.
11103 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11104 Elements.push_back(APValue(f));
11105 CountElts++;
11106 }
11107 CountInits++;
11108 }
11109 return Success(Elements, E);
11110}
11111
11112bool
11113VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11114 const auto *VT = E->getType()->castAs<VectorType>();
11115 QualType EltTy = VT->getElementType();
11116 APValue ZeroElement;
11117 if (EltTy->isIntegerType())
11118 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11119 else
11120 ZeroElement =
11121 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11122
11123 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11124 return Success(Elements, E);
11125}
11126
11127bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11128 VisitIgnoredValue(E->getSubExpr());
11129 return ZeroInitialization(E);
11130}
11131
11132bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11133 BinaryOperatorKind Op = E->getOpcode();
11134 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11135 "Operation not supported on vector types");
11136
11137 if (Op == BO_Comma)
11138 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11139
11140 Expr *LHS = E->getLHS();
11141 Expr *RHS = E->getRHS();
11142
11143 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11144 "Must both be vector types");
11145 // Checking JUST the types are the same would be fine, except shifts don't
11146 // need to have their types be the same (since you always shift by an int).
11147 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11149 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11151 "All operands must be the same size.");
11152
11153 APValue LHSValue;
11154 APValue RHSValue;
11155 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11156 if (!LHSOK && !Info.noteFailure())
11157 return false;
11158 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11159 return false;
11160
11161 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11162 return false;
11163
11164 return Success(LHSValue, E);
11165}
11166
11167static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11168 QualType ResultTy,
11170 APValue Elt) {
11171 switch (Op) {
11172 case UO_Plus:
11173 // Nothing to do here.
11174 return Elt;
11175 case UO_Minus:
11176 if (Elt.getKind() == APValue::Int) {
11177 Elt.getInt().negate();
11178 } else {
11179 assert(Elt.getKind() == APValue::Float &&
11180 "Vector can only be int or float type");
11181 Elt.getFloat().changeSign();
11182 }
11183 return Elt;
11184 case UO_Not:
11185 // This is only valid for integral types anyway, so we don't have to handle
11186 // float here.
11187 assert(Elt.getKind() == APValue::Int &&
11188 "Vector operator ~ can only be int");
11189 Elt.getInt().flipAllBits();
11190 return Elt;
11191 case UO_LNot: {
11192 if (Elt.getKind() == APValue::Int) {
11193 Elt.getInt() = !Elt.getInt();
11194 // operator ! on vectors returns -1 for 'truth', so negate it.
11195 Elt.getInt().negate();
11196 return Elt;
11197 }
11198 assert(Elt.getKind() == APValue::Float &&
11199 "Vector can only be int or float type");
11200 // Float types result in an int of the same size, but -1 for true, or 0 for
11201 // false.
11202 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11203 ResultTy->isUnsignedIntegerType()};
11204 if (Elt.getFloat().isZero())
11205 EltResult.setAllBits();
11206 else
11207 EltResult.clearAllBits();
11208
11209 return APValue{EltResult};
11210 }
11211 default:
11212 // FIXME: Implement the rest of the unary operators.
11213 return std::nullopt;
11214 }
11215}
11216
11217bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11218 Expr *SubExpr = E->getSubExpr();
11219 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11220 // This result element type differs in the case of negating a floating point
11221 // vector, since the result type is the a vector of the equivilant sized
11222 // integer.
11223 const QualType ResultEltTy = VD->getElementType();
11224 UnaryOperatorKind Op = E->getOpcode();
11225
11226 APValue SubExprValue;
11227 if (!Evaluate(SubExprValue, Info, SubExpr))
11228 return false;
11229
11230 // FIXME: This vector evaluator someday needs to be changed to be LValue
11231 // aware/keep LValue information around, rather than dealing with just vector
11232 // types directly. Until then, we cannot handle cases where the operand to
11233 // these unary operators is an LValue. The only case I've been able to see
11234 // cause this is operator++ assigning to a member expression (only valid in
11235 // altivec compilations) in C mode, so this shouldn't limit us too much.
11236 if (SubExprValue.isLValue())
11237 return false;
11238
11239 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11240 "Vector length doesn't match type?");
11241
11242 SmallVector<APValue, 4> ResultElements;
11243 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
11244 std::optional<APValue> Elt = handleVectorUnaryOperator(
11245 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
11246 if (!Elt)
11247 return false;
11248 ResultElements.push_back(*Elt);
11249 }
11250 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11251}
11252
11253static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
11254 const Expr *E, QualType SourceTy,
11255 QualType DestTy, APValue const &Original,
11256 APValue &Result) {
11257 if (SourceTy->isIntegerType()) {
11258 if (DestTy->isRealFloatingType()) {
11259 Result = APValue(APFloat(0.0));
11260 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
11261 DestTy, Result.getFloat());
11262 }
11263 if (DestTy->isIntegerType()) {
11264 Result = APValue(
11265 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
11266 return true;
11267 }
11268 } else if (SourceTy->isRealFloatingType()) {
11269 if (DestTy->isRealFloatingType()) {
11270 Result = Original;
11271 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
11272 Result.getFloat());
11273 }
11274 if (DestTy->isIntegerType()) {
11275 Result = APValue(APSInt());
11276 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
11277 DestTy, Result.getInt());
11278 }
11279 }
11280
11281 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
11282 << SourceTy << DestTy;
11283 return false;
11284}
11285
11286bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
11287 if (!IsConstantEvaluatedBuiltinCall(E))
11288 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11289
11290 switch (E->getBuiltinCallee()) {
11291 default:
11292 return false;
11293 case Builtin::BI__builtin_elementwise_popcount:
11294 case Builtin::BI__builtin_elementwise_bitreverse: {
11295 APValue Source;
11296 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
11297 return false;
11298
11299 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11300 unsigned SourceLen = Source.getVectorLength();
11301 SmallVector<APValue, 4> ResultElements;
11302 ResultElements.reserve(SourceLen);
11303
11304 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11305 APSInt Elt = Source.getVectorElt(EltNum).getInt();
11306 switch (E->getBuiltinCallee()) {
11307 case Builtin::BI__builtin_elementwise_popcount:
11308 ResultElements.push_back(APValue(
11309 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
11310 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11311 break;
11312 case Builtin::BI__builtin_elementwise_bitreverse:
11313 ResultElements.push_back(
11314 APValue(APSInt(Elt.reverseBits(),
11315 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11316 break;
11317 }
11318 }
11319
11320 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11321 }
11322 case Builtin::BI__builtin_elementwise_add_sat:
11323 case Builtin::BI__builtin_elementwise_sub_sat: {
11324 APValue SourceLHS, SourceRHS;
11325 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11326 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11327 return false;
11328
11329 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11330 unsigned SourceLen = SourceLHS.getVectorLength();
11331 SmallVector<APValue, 4> ResultElements;
11332 ResultElements.reserve(SourceLen);
11333
11334 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11335 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
11336 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
11337 switch (E->getBuiltinCallee()) {
11338 case Builtin::BI__builtin_elementwise_add_sat:
11339 ResultElements.push_back(APValue(
11340 APSInt(LHS.isSigned() ? LHS.sadd_sat(RHS) : RHS.uadd_sat(RHS),
11341 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11342 break;
11343 case Builtin::BI__builtin_elementwise_sub_sat:
11344 ResultElements.push_back(APValue(
11345 APSInt(LHS.isSigned() ? LHS.ssub_sat(RHS) : RHS.usub_sat(RHS),
11346 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11347 break;
11348 }
11349 }
11350
11351 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11352 }
11353 }
11354}
11355
11356bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
11357 APValue Source;
11358 QualType SourceVecType = E->getSrcExpr()->getType();
11359 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
11360 return false;
11361
11362 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
11363 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
11364
11365 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11366
11367 auto SourceLen = Source.getVectorLength();
11368 SmallVector<APValue, 4> ResultElements;
11369 ResultElements.reserve(SourceLen);
11370 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11371 APValue Elt;
11372 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
11373 Source.getVectorElt(EltNum), Elt))
11374 return false;
11375 ResultElements.push_back(std::move(Elt));
11376 }
11377
11378 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11379}
11380
11381static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
11382 QualType ElemType, APValue const &VecVal1,
11383 APValue const &VecVal2, unsigned EltNum,
11384 APValue &Result) {
11385 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
11386 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
11387
11388 APSInt IndexVal = E->getShuffleMaskIdx(Info.Ctx, EltNum);
11389 int64_t index = IndexVal.getExtValue();
11390 // The spec says that -1 should be treated as undef for optimizations,
11391 // but in constexpr we'd have to produce an APValue::Indeterminate,
11392 // which is prohibited from being a top-level constant value. Emit a
11393 // diagnostic instead.
11394 if (index == -1) {
11395 Info.FFDiag(
11396 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
11397 << EltNum;
11398 return false;
11399 }
11400
11401 if (index < 0 ||
11402 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
11403 llvm_unreachable("Out of bounds shuffle index");
11404
11405 if (index >= TotalElementsInInputVector1)
11406 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
11407 else
11408 Result = VecVal1.getVectorElt(index);
11409 return true;
11410}
11411
11412bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
11413 APValue VecVal1;
11414 const Expr *Vec1 = E->getExpr(0);
11415 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
11416 return false;
11417 APValue VecVal2;
11418 const Expr *Vec2 = E->getExpr(1);
11419 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
11420 return false;
11421
11422 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
11423 QualType DestElTy = DestVecTy->getElementType();
11424
11425 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
11426
11427 SmallVector<APValue, 4> ResultElements;
11428 ResultElements.reserve(TotalElementsInOutputVector);
11429 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
11430 APValue Elt;
11431 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
11432 return false;
11433 ResultElements.push_back(std::move(Elt));
11434 }
11435
11436 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11437}
11438
11439//===----------------------------------------------------------------------===//
11440// Array Evaluation
11441//===----------------------------------------------------------------------===//
11442
11443namespace {
11444 class ArrayExprEvaluator
11445 : public ExprEvaluatorBase<ArrayExprEvaluator> {
11446 const LValue &This;
11447 APValue &Result;
11448 public:
11449
11450 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
11451 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
11452
11453 bool Success(const APValue &V, const Expr *E) {
11454 assert(V.isArray() && "expected array");
11455 Result = V;
11456 return true;
11457 }
11458
11459 bool ZeroInitialization(const Expr *E) {
11460 const ConstantArrayType *CAT =
11461 Info.Ctx.getAsConstantArrayType(E->getType());
11462 if (!CAT) {
11463 if (E->getType()->isIncompleteArrayType()) {
11464 // We can be asked to zero-initialize a flexible array member; this
11465 // is represented as an ImplicitValueInitExpr of incomplete array
11466 // type. In this case, the array has zero elements.
11467 Result = APValue(APValue::UninitArray(), 0, 0);
11468 return true;
11469 }
11470 // FIXME: We could handle VLAs here.
11471 return Error(E);
11472 }
11473
11474 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
11475 if (!Result.hasArrayFiller())
11476 return true;
11477
11478 // Zero-initialize all elements.
11479 LValue Subobject = This;
11480 Subobject.addArray(Info, E, CAT);
11482 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
11483 }
11484
11485 bool VisitCallExpr(const CallExpr *E) {
11486 return handleCallExpr(E, Result, &This);
11487 }
11488 bool VisitInitListExpr(const InitListExpr *E,
11489 QualType AllocType = QualType());
11490 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
11491 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
11492 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
11493 const LValue &Subobject,
11495 bool VisitStringLiteral(const StringLiteral *E,
11496 QualType AllocType = QualType()) {
11497 expandStringLiteral(Info, E, Result, AllocType);
11498 return true;
11499 }
11500 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11501 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11502 ArrayRef<Expr *> Args,
11503 const Expr *ArrayFiller,
11504 QualType AllocType = QualType());
11505 };
11506} // end anonymous namespace
11507
11508static bool EvaluateArray(const Expr *E, const LValue &This,
11509 APValue &Result, EvalInfo &Info) {
11510 assert(!E->isValueDependent());
11511 assert(E->isPRValue() && E->getType()->isArrayType() &&
11512 "not an array prvalue");
11513 return ArrayExprEvaluator(Info, This, Result).Visit(E);
11514}
11515
11516static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
11517 APValue &Result, const InitListExpr *ILE,
11518 QualType AllocType) {
11519 assert(!ILE->isValueDependent());
11520 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
11521 "not an array prvalue");
11522 return ArrayExprEvaluator(Info, This, Result)
11523 .VisitInitListExpr(ILE, AllocType);
11524}
11525
11526static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
11527 APValue &Result,
11528 const CXXConstructExpr *CCE,
11529 QualType AllocType) {
11530 assert(!CCE->isValueDependent());
11531 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
11532 "not an array prvalue");
11533 return ArrayExprEvaluator(Info, This, Result)
11534 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
11535}
11536
11537// Return true iff the given array filler may depend on the element index.
11538static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
11539 // For now, just allow non-class value-initialization and initialization
11540 // lists comprised of them.
11541 if (isa<ImplicitValueInitExpr>(FillerExpr))
11542 return false;
11543 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
11544 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
11545 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
11546 return true;
11547 }
11548
11549 if (ILE->hasArrayFiller() &&
11550 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
11551 return true;
11552
11553 return false;
11554 }
11555 return true;
11556}
11557
11558bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
11559 QualType AllocType) {
11560 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11561 AllocType.isNull() ? E->getType() : AllocType);
11562 if (!CAT)
11563 return Error(E);
11564
11565 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
11566 // an appropriately-typed string literal enclosed in braces.
11567 if (E->isStringLiteralInit()) {
11568 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
11569 // FIXME: Support ObjCEncodeExpr here once we support it in
11570 // ArrayExprEvaluator generally.
11571 if (!SL)
11572 return Error(E);
11573 return VisitStringLiteral(SL, AllocType);
11574 }
11575 // Any other transparent list init will need proper handling of the
11576 // AllocType; we can't just recurse to the inner initializer.
11577 assert(!E->isTransparent() &&
11578 "transparent array list initialization is not string literal init?");
11579
11580 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
11581 AllocType);
11582}
11583
11584bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
11585 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
11586 QualType AllocType) {
11587 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11588 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
11589
11590 bool Success = true;
11591
11592 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
11593 "zero-initialized array shouldn't have any initialized elts");
11594 APValue Filler;
11595 if (Result.isArray() && Result.hasArrayFiller())
11596 Filler = Result.getArrayFiller();
11597
11598 unsigned NumEltsToInit = Args.size();
11599 unsigned NumElts = CAT->getZExtSize();
11600
11601 // If the initializer might depend on the array index, run it for each
11602 // array element.
11603 if (NumEltsToInit != NumElts &&
11604 MaybeElementDependentArrayFiller(ArrayFiller)) {
11605 NumEltsToInit = NumElts;
11606 } else {
11607 for (auto *Init : Args) {
11608 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
11609 NumEltsToInit += EmbedS->getDataElementCount() - 1;
11610 }
11611 if (NumEltsToInit > NumElts)
11612 NumEltsToInit = NumElts;
11613 }
11614
11615 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
11616 << NumEltsToInit << ".\n");
11617
11618 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
11619
11620 // If the array was previously zero-initialized, preserve the
11621 // zero-initialized values.
11622 if (Filler.hasValue()) {
11623 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
11624 Result.getArrayInitializedElt(I) = Filler;
11625 if (Result.hasArrayFiller())
11626 Result.getArrayFiller() = Filler;
11627 }
11628
11629 LValue Subobject = This;
11630 Subobject.addArray(Info, ExprToVisit, CAT);
11631 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
11632 if (Init->isValueDependent())
11633 return EvaluateDependentExpr(Init, Info);
11634
11635 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
11636 Subobject, Init) ||
11637 !HandleLValueArrayAdjustment(Info, Init, Subobject,
11638 CAT->getElementType(), 1)) {
11639 if (!Info.noteFailure())
11640 return false;
11641 Success = false;
11642 }
11643 return true;
11644 };
11645 unsigned ArrayIndex = 0;
11646 QualType DestTy = CAT->getElementType();
11647 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
11648 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
11649 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
11650 if (ArrayIndex >= NumEltsToInit)
11651 break;
11652 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
11653 StringLiteral *SL = EmbedS->getDataStringLiteral();
11654 for (unsigned I = EmbedS->getStartingElementPos(),
11655 N = EmbedS->getDataElementCount();
11656 I != EmbedS->getStartingElementPos() + N; ++I) {
11657 Value = SL->getCodeUnit(I);
11658 if (DestTy->isIntegerType()) {
11659 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
11660 } else {
11661 assert(DestTy->isFloatingType() && "unexpected type");
11662 const FPOptions FPO =
11663 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11664 APFloat FValue(0.0);
11665 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
11666 DestTy, FValue))
11667 return false;
11668 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
11669 }
11670 ArrayIndex++;
11671 }
11672 } else {
11673 if (!Eval(Init, ArrayIndex))
11674 return false;
11675 ++ArrayIndex;
11676 }
11677 }
11678
11679 if (!Result.hasArrayFiller())
11680 return Success;
11681
11682 // If we get here, we have a trivial filler, which we can just evaluate
11683 // once and splat over the rest of the array elements.
11684 assert(ArrayFiller && "no array filler for incomplete init list");
11685 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
11686 ArrayFiller) &&
11687 Success;
11688}
11689
11690bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
11691 LValue CommonLV;
11692 if (E->getCommonExpr() &&
11693 !Evaluate(Info.CurrentCall->createTemporary(
11694 E->getCommonExpr(),
11695 getStorageType(Info.Ctx, E->getCommonExpr()),
11696 ScopeKind::FullExpression, CommonLV),
11697 Info, E->getCommonExpr()->getSourceExpr()))
11698 return false;
11699
11700 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
11701
11702 uint64_t Elements = CAT->getZExtSize();
11703 Result = APValue(APValue::UninitArray(), Elements, Elements);
11704
11705 LValue Subobject = This;
11706 Subobject.addArray(Info, E, CAT);
11707
11708 bool Success = true;
11709 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
11710 // C++ [class.temporary]/5
11711 // There are four contexts in which temporaries are destroyed at a different
11712 // point than the end of the full-expression. [...] The second context is
11713 // when a copy constructor is called to copy an element of an array while
11714 // the entire array is copied [...]. In either case, if the constructor has
11715 // one or more default arguments, the destruction of every temporary created
11716 // in a default argument is sequenced before the construction of the next
11717 // array element, if any.
11718 FullExpressionRAII Scope(Info);
11719
11720 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
11721 Info, Subobject, E->getSubExpr()) ||
11722 !HandleLValueArrayAdjustment(Info, E, Subobject,
11723 CAT->getElementType(), 1)) {
11724 if (!Info.noteFailure())
11725 return false;
11726 Success = false;
11727 }
11728
11729 // Make sure we run the destructors too.
11730 Scope.destroy();
11731 }
11732
11733 return Success;
11734}
11735
11736bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
11737 return VisitCXXConstructExpr(E, This, &Result, E->getType());
11738}
11739
11740bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11741 const LValue &Subobject,
11742 APValue *Value,
11743 QualType Type) {
11744 bool HadZeroInit = Value->hasValue();
11745
11746 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
11747 unsigned FinalSize = CAT->getZExtSize();
11748
11749 // Preserve the array filler if we had prior zero-initialization.
11750 APValue Filler =
11751 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
11752 : APValue();
11753
11754 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
11755 if (FinalSize == 0)
11756 return true;
11757
11758 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
11759 Info, E->getExprLoc(), E->getConstructor(),
11760 E->requiresZeroInitialization());
11761 LValue ArrayElt = Subobject;
11762 ArrayElt.addArray(Info, E, CAT);
11763 // We do the whole initialization in two passes, first for just one element,
11764 // then for the whole array. It's possible we may find out we can't do const
11765 // init in the first pass, in which case we avoid allocating a potentially
11766 // large array. We don't do more passes because expanding array requires
11767 // copying the data, which is wasteful.
11768 for (const unsigned N : {1u, FinalSize}) {
11769 unsigned OldElts = Value->getArrayInitializedElts();
11770 if (OldElts == N)
11771 break;
11772
11773 // Expand the array to appropriate size.
11774 APValue NewValue(APValue::UninitArray(), N, FinalSize);
11775 for (unsigned I = 0; I < OldElts; ++I)
11776 NewValue.getArrayInitializedElt(I).swap(
11777 Value->getArrayInitializedElt(I));
11778 Value->swap(NewValue);
11779
11780 if (HadZeroInit)
11781 for (unsigned I = OldElts; I < N; ++I)
11782 Value->getArrayInitializedElt(I) = Filler;
11783
11784 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
11785 // If we have a trivial constructor, only evaluate it once and copy
11786 // the result into all the array elements.
11787 APValue &FirstResult = Value->getArrayInitializedElt(0);
11788 for (unsigned I = OldElts; I < FinalSize; ++I)
11789 Value->getArrayInitializedElt(I) = FirstResult;
11790 } else {
11791 for (unsigned I = OldElts; I < N; ++I) {
11792 if (!VisitCXXConstructExpr(E, ArrayElt,
11793 &Value->getArrayInitializedElt(I),
11794 CAT->getElementType()) ||
11795 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
11796 CAT->getElementType(), 1))
11797 return false;
11798 // When checking for const initilization any diagnostic is considered
11799 // an error.
11800 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
11801 !Info.keepEvaluatingAfterFailure())
11802 return false;
11803 }
11804 }
11805 }
11806
11807 return true;
11808 }
11809
11810 if (!Type->isRecordType())
11811 return Error(E);
11812
11813 return RecordExprEvaluator(Info, Subobject, *Value)
11814 .VisitCXXConstructExpr(E, Type);
11815}
11816
11817bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
11818 const CXXParenListInitExpr *E) {
11819 assert(E->getType()->isConstantArrayType() &&
11820 "Expression result is not a constant array type");
11821
11822 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
11823 E->getArrayFiller());
11824}
11825
11826//===----------------------------------------------------------------------===//
11827// Integer Evaluation
11828//
11829// As a GNU extension, we support casting pointers to sufficiently-wide integer
11830// types and back in constant folding. Integer values are thus represented
11831// either as an integer-valued APValue, or as an lvalue-valued APValue.
11832//===----------------------------------------------------------------------===//
11833
11834namespace {
11835class IntExprEvaluator
11836 : public ExprEvaluatorBase<IntExprEvaluator> {
11837 APValue &Result;
11838public:
11839 IntExprEvaluator(EvalInfo &info, APValue &result)
11840 : ExprEvaluatorBaseTy(info), Result(result) {}
11841
11842 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
11843 assert(E->getType()->isIntegralOrEnumerationType() &&
11844 "Invalid evaluation result.");
11845 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
11846 "Invalid evaluation result.");
11847 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11848 "Invalid evaluation result.");
11849 Result = APValue(SI);
11850 return true;
11851 }
11852 bool Success(const llvm::APSInt &SI, const Expr *E) {
11853 return Success(SI, E, Result);
11854 }
11855
11856 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
11857 assert(E->getType()->isIntegralOrEnumerationType() &&
11858 "Invalid evaluation result.");
11859 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11860 "Invalid evaluation result.");
11861 Result = APValue(APSInt(I));
11862 Result.getInt().setIsUnsigned(
11864 return true;
11865 }
11866 bool Success(const llvm::APInt &I, const Expr *E) {
11867 return Success(I, E, Result);
11868 }
11869
11870 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11871 assert(E->getType()->isIntegralOrEnumerationType() &&
11872 "Invalid evaluation result.");
11873 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
11874 return true;
11875 }
11876 bool Success(uint64_t Value, const Expr *E) {
11877 return Success(Value, E, Result);
11878 }
11879
11880 bool Success(CharUnits Size, const Expr *E) {
11881 return Success(Size.getQuantity(), E);
11882 }
11883
11884 bool Success(const APValue &V, const Expr *E) {
11885 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
11886 Result = V;
11887 return true;
11888 }
11889 return Success(V.getInt(), E);
11890 }
11891
11892 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
11893
11894 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
11895 const CallExpr *);
11896
11897 //===--------------------------------------------------------------------===//
11898 // Visitor Methods
11899 //===--------------------------------------------------------------------===//
11900
11901 bool VisitIntegerLiteral(const IntegerLiteral *E) {
11902 return Success(E->getValue(), E);
11903 }
11904 bool VisitCharacterLiteral(const CharacterLiteral *E) {
11905 return Success(E->getValue(), E);
11906 }
11907
11908 bool CheckReferencedDecl(const Expr *E, const Decl *D);
11909 bool VisitDeclRefExpr(const DeclRefExpr *E) {
11910 if (CheckReferencedDecl(E, E->getDecl()))
11911 return true;
11912
11913 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
11914 }
11915 bool VisitMemberExpr(const MemberExpr *E) {
11916 if (CheckReferencedDecl(E, E->getMemberDecl())) {
11917 VisitIgnoredBaseExpression(E->getBase());
11918 return true;
11919 }
11920
11921 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
11922 }
11923
11924 bool VisitCallExpr(const CallExpr *E);
11925 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
11926 bool VisitBinaryOperator(const BinaryOperator *E);
11927 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
11928 bool VisitUnaryOperator(const UnaryOperator *E);
11929
11930 bool VisitCastExpr(const CastExpr* E);
11931 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
11932
11933 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
11934 return Success(E->getValue(), E);
11935 }
11936
11937 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
11938 return Success(E->getValue(), E);
11939 }
11940
11941 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
11942 if (Info.ArrayInitIndex == uint64_t(-1)) {
11943 // We were asked to evaluate this subexpression independent of the
11944 // enclosing ArrayInitLoopExpr. We can't do that.
11945 Info.FFDiag(E);
11946 return false;
11947 }
11948 return Success(Info.ArrayInitIndex, E);
11949 }
11950
11951 // Note, GNU defines __null as an integer, not a pointer.
11952 bool VisitGNUNullExpr(const GNUNullExpr *E) {
11953 return ZeroInitialization(E);
11954 }
11955
11956 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11957 return Success(E->getValue(), E);
11958 }
11959
11960 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11961 return Success(E->getValue(), E);
11962 }
11963
11964 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11965 return Success(E->getValue(), E);
11966 }
11967
11968 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
11969 // This should not be evaluated during constant expr evaluation, as it
11970 // should always be in an unevaluated context (the args list of a 'gang' or
11971 // 'tile' clause).
11972 return Error(E);
11973 }
11974
11975 bool VisitUnaryReal(const UnaryOperator *E);
11976 bool VisitUnaryImag(const UnaryOperator *E);
11977
11978 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11979 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11980 bool VisitSourceLocExpr(const SourceLocExpr *E);
11981 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11982 bool VisitRequiresExpr(const RequiresExpr *E);
11983 // FIXME: Missing: array subscript of vector, member of vector
11984};
11985
11986class FixedPointExprEvaluator
11987 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11988 APValue &Result;
11989
11990 public:
11991 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11992 : ExprEvaluatorBaseTy(info), Result(result) {}
11993
11994 bool Success(const llvm::APInt &I, const Expr *E) {
11995 return Success(
11996 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11997 }
11998
11999 bool Success(uint64_t Value, const Expr *E) {
12000 return Success(
12001 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
12002 }
12003
12004 bool Success(const APValue &V, const Expr *E) {
12005 return Success(V.getFixedPoint(), E);
12006 }
12007
12008 bool Success(const APFixedPoint &V, const Expr *E) {
12009 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
12010 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
12011 "Invalid evaluation result.");
12012 Result = APValue(V);
12013 return true;
12014 }
12015
12016 bool ZeroInitialization(const Expr *E) {
12017 return Success(0, E);
12018 }
12019
12020 //===--------------------------------------------------------------------===//
12021 // Visitor Methods
12022 //===--------------------------------------------------------------------===//
12023
12024 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
12025 return Success(E->getValue(), E);
12026 }
12027
12028 bool VisitCastExpr(const CastExpr *E);
12029 bool VisitUnaryOperator(const UnaryOperator *E);
12030 bool VisitBinaryOperator(const BinaryOperator *E);
12031};
12032} // end anonymous namespace
12033
12034/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
12035/// produce either the integer value or a pointer.
12036///
12037/// GCC has a heinous extension which folds casts between pointer types and
12038/// pointer-sized integral types. We support this by allowing the evaluation of
12039/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
12040/// Some simple arithmetic on such values is supported (they are treated much
12041/// like char*).
12042static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
12043 EvalInfo &Info) {
12044 assert(!E->isValueDependent());
12045 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
12046 return IntExprEvaluator(Info, Result).Visit(E);
12047}
12048
12049static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
12050 assert(!E->isValueDependent());
12051 APValue Val;
12052 if (!EvaluateIntegerOrLValue(E, Val, Info))
12053 return false;
12054 if (!Val.isInt()) {
12055 // FIXME: It would be better to produce the diagnostic for casting
12056 // a pointer to an integer.
12057 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12058 return false;
12059 }
12060 Result = Val.getInt();
12061 return true;
12062}
12063
12064bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
12065 APValue Evaluated = E->EvaluateInContext(
12066 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
12067 return Success(Evaluated, E);
12068}
12069
12070static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
12071 EvalInfo &Info) {
12072 assert(!E->isValueDependent());
12073 if (E->getType()->isFixedPointType()) {
12074 APValue Val;
12075 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
12076 return false;
12077 if (!Val.isFixedPoint())
12078 return false;
12079
12080 Result = Val.getFixedPoint();
12081 return true;
12082 }
12083 return false;
12084}
12085
12086static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
12087 EvalInfo &Info) {
12088 assert(!E->isValueDependent());
12089 if (E->getType()->isIntegerType()) {
12090 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
12091 APSInt Val;
12092 if (!EvaluateInteger(E, Val, Info))
12093 return false;
12094 Result = APFixedPoint(Val, FXSema);
12095 return true;
12096 } else if (E->getType()->isFixedPointType()) {
12097 return EvaluateFixedPoint(E, Result, Info);
12098 }
12099 return false;
12100}
12101
12102/// Check whether the given declaration can be directly converted to an integral
12103/// rvalue. If not, no diagnostic is produced; there are other things we can
12104/// try.
12105bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
12106 // Enums are integer constant exprs.
12107 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
12108 // Check for signedness/width mismatches between E type and ECD value.
12109 bool SameSign = (ECD->getInitVal().isSigned()
12111 bool SameWidth = (ECD->getInitVal().getBitWidth()
12112 == Info.Ctx.getIntWidth(E->getType()));
12113 if (SameSign && SameWidth)
12114 return Success(ECD->getInitVal(), E);
12115 else {
12116 // Get rid of mismatch (otherwise Success assertions will fail)
12117 // by computing a new value matching the type of E.
12118 llvm::APSInt Val = ECD->getInitVal();
12119 if (!SameSign)
12120 Val.setIsSigned(!ECD->getInitVal().isSigned());
12121 if (!SameWidth)
12122 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
12123 return Success(Val, E);
12124 }
12125 }
12126 return false;
12127}
12128
12129/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
12130/// as GCC.
12132 const LangOptions &LangOpts) {
12133 assert(!T->isDependentType() && "unexpected dependent type");
12134
12135 QualType CanTy = T.getCanonicalType();
12136
12137 switch (CanTy->getTypeClass()) {
12138#define TYPE(ID, BASE)
12139#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
12140#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
12141#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
12142#include "clang/AST/TypeNodes.inc"
12143 case Type::Auto:
12144 case Type::DeducedTemplateSpecialization:
12145 llvm_unreachable("unexpected non-canonical or dependent type");
12146
12147 case Type::Builtin:
12148 switch (cast<BuiltinType>(CanTy)->getKind()) {
12149#define BUILTIN_TYPE(ID, SINGLETON_ID)
12150#define SIGNED_TYPE(ID, SINGLETON_ID) \
12151 case BuiltinType::ID: return GCCTypeClass::Integer;
12152#define FLOATING_TYPE(ID, SINGLETON_ID) \
12153 case BuiltinType::ID: return GCCTypeClass::RealFloat;
12154#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
12155 case BuiltinType::ID: break;
12156#include "clang/AST/BuiltinTypes.def"
12157 case BuiltinType::Void:
12158 return GCCTypeClass::Void;
12159
12160 case BuiltinType::Bool:
12161 return GCCTypeClass::Bool;
12162
12163 case BuiltinType::Char_U:
12164 case BuiltinType::UChar:
12165 case BuiltinType::WChar_U:
12166 case BuiltinType::Char8:
12167 case BuiltinType::Char16:
12168 case BuiltinType::Char32:
12169 case BuiltinType::UShort:
12170 case BuiltinType::UInt:
12171 case BuiltinType::ULong:
12172 case BuiltinType::ULongLong:
12173 case BuiltinType::UInt128:
12174 return GCCTypeClass::Integer;
12175
12176 case BuiltinType::UShortAccum:
12177 case BuiltinType::UAccum:
12178 case BuiltinType::ULongAccum:
12179 case BuiltinType::UShortFract:
12180 case BuiltinType::UFract:
12181 case BuiltinType::ULongFract:
12182 case BuiltinType::SatUShortAccum:
12183 case BuiltinType::SatUAccum:
12184 case BuiltinType::SatULongAccum:
12185 case BuiltinType::SatUShortFract:
12186 case BuiltinType::SatUFract:
12187 case BuiltinType::SatULongFract:
12188 return GCCTypeClass::None;
12189
12190 case BuiltinType::NullPtr:
12191
12192 case BuiltinType::ObjCId:
12193 case BuiltinType::ObjCClass:
12194 case BuiltinType::ObjCSel:
12195#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
12196 case BuiltinType::Id:
12197#include "clang/Basic/OpenCLImageTypes.def"
12198#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
12199 case BuiltinType::Id:
12200#include "clang/Basic/OpenCLExtensionTypes.def"
12201 case BuiltinType::OCLSampler:
12202 case BuiltinType::OCLEvent:
12203 case BuiltinType::OCLClkEvent:
12204 case BuiltinType::OCLQueue:
12205 case BuiltinType::OCLReserveID:
12206#define SVE_TYPE(Name, Id, SingletonId) \
12207 case BuiltinType::Id:
12208#include "clang/Basic/AArch64SVEACLETypes.def"
12209#define PPC_VECTOR_TYPE(Name, Id, Size) \
12210 case BuiltinType::Id:
12211#include "clang/Basic/PPCTypes.def"
12212#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12213#include "clang/Basic/RISCVVTypes.def"
12214#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12215#include "clang/Basic/WebAssemblyReferenceTypes.def"
12216#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
12217#include "clang/Basic/AMDGPUTypes.def"
12218#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12219#include "clang/Basic/HLSLIntangibleTypes.def"
12220 return GCCTypeClass::None;
12221
12222 case BuiltinType::Dependent:
12223 llvm_unreachable("unexpected dependent type");
12224 };
12225 llvm_unreachable("unexpected placeholder type");
12226
12227 case Type::Enum:
12228 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
12229
12230 case Type::Pointer:
12231 case Type::ConstantArray:
12232 case Type::VariableArray:
12233 case Type::IncompleteArray:
12234 case Type::FunctionNoProto:
12235 case Type::FunctionProto:
12236 case Type::ArrayParameter:
12237 return GCCTypeClass::Pointer;
12238
12239 case Type::MemberPointer:
12240 return CanTy->isMemberDataPointerType()
12241 ? GCCTypeClass::PointerToDataMember
12242 : GCCTypeClass::PointerToMemberFunction;
12243
12244 case Type::Complex:
12245 return GCCTypeClass::Complex;
12246
12247 case Type::Record:
12248 return CanTy->isUnionType() ? GCCTypeClass::Union
12249 : GCCTypeClass::ClassOrStruct;
12250
12251 case Type::Atomic:
12252 // GCC classifies _Atomic T the same as T.
12254 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
12255
12256 case Type::Vector:
12257 case Type::ExtVector:
12258 return GCCTypeClass::Vector;
12259
12260 case Type::BlockPointer:
12261 case Type::ConstantMatrix:
12262 case Type::ObjCObject:
12263 case Type::ObjCInterface:
12264 case Type::ObjCObjectPointer:
12265 case Type::Pipe:
12266 case Type::HLSLAttributedResource:
12267 // Classify all other types that don't fit into the regular
12268 // classification the same way.
12269 return GCCTypeClass::None;
12270
12271 case Type::BitInt:
12272 return GCCTypeClass::BitInt;
12273
12274 case Type::LValueReference:
12275 case Type::RValueReference:
12276 llvm_unreachable("invalid type for expression");
12277 }
12278
12279 llvm_unreachable("unexpected type class");
12280}
12281
12282/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
12283/// as GCC.
12284static GCCTypeClass
12286 // If no argument was supplied, default to None. This isn't
12287 // ideal, however it is what gcc does.
12288 if (E->getNumArgs() == 0)
12289 return GCCTypeClass::None;
12290
12291 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
12292 // being an ICE, but still folds it to a constant using the type of the first
12293 // argument.
12294 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
12295}
12296
12297/// EvaluateBuiltinConstantPForLValue - Determine the result of
12298/// __builtin_constant_p when applied to the given pointer.
12299///
12300/// A pointer is only "constant" if it is null (or a pointer cast to integer)
12301/// or it points to the first character of a string literal.
12304 if (Base.isNull()) {
12305 // A null base is acceptable.
12306 return true;
12307 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
12308 if (!isa<StringLiteral>(E))
12309 return false;
12310 return LV.getLValueOffset().isZero();
12311 } else if (Base.is<TypeInfoLValue>()) {
12312 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
12313 // evaluate to true.
12314 return true;
12315 } else {
12316 // Any other base is not constant enough for GCC.
12317 return false;
12318 }
12319}
12320
12321/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
12322/// GCC as we can manage.
12323static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
12324 // This evaluation is not permitted to have side-effects, so evaluate it in
12325 // a speculative evaluation context.
12326 SpeculativeEvaluationRAII SpeculativeEval(Info);
12327
12328 // Constant-folding is always enabled for the operand of __builtin_constant_p
12329 // (even when the enclosing evaluation context otherwise requires a strict
12330 // language-specific constant expression).
12331 FoldConstant Fold(Info, true);
12332
12333 QualType ArgType = Arg->getType();
12334
12335 // __builtin_constant_p always has one operand. The rules which gcc follows
12336 // are not precisely documented, but are as follows:
12337 //
12338 // - If the operand is of integral, floating, complex or enumeration type,
12339 // and can be folded to a known value of that type, it returns 1.
12340 // - If the operand can be folded to a pointer to the first character
12341 // of a string literal (or such a pointer cast to an integral type)
12342 // or to a null pointer or an integer cast to a pointer, it returns 1.
12343 //
12344 // Otherwise, it returns 0.
12345 //
12346 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
12347 // its support for this did not work prior to GCC 9 and is not yet well
12348 // understood.
12349 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
12350 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
12351 ArgType->isNullPtrType()) {
12352 APValue V;
12353 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
12354 Fold.keepDiagnostics();
12355 return false;
12356 }
12357
12358 // For a pointer (possibly cast to integer), there are special rules.
12359 if (V.getKind() == APValue::LValue)
12361
12362 // Otherwise, any constant value is good enough.
12363 return V.hasValue();
12364 }
12365
12366 // Anything else isn't considered to be sufficiently constant.
12367 return false;
12368}
12369
12370/// Retrieves the "underlying object type" of the given expression,
12371/// as used by __builtin_object_size.
12373 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
12374 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
12375 return VD->getType();
12376 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
12377 if (isa<CompoundLiteralExpr>(E))
12378 return E->getType();
12379 } else if (B.is<TypeInfoLValue>()) {
12380 return B.getTypeInfoType();
12381 } else if (B.is<DynamicAllocLValue>()) {
12382 return B.getDynamicAllocType();
12383 }
12384
12385 return QualType();
12386}
12387
12388/// A more selective version of E->IgnoreParenCasts for
12389/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
12390/// to change the type of E.
12391/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
12392///
12393/// Always returns an RValue with a pointer representation.
12395 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
12396
12397 const Expr *NoParens = E->IgnoreParens();
12398 const auto *Cast = dyn_cast<CastExpr>(NoParens);
12399 if (Cast == nullptr)
12400 return NoParens;
12401
12402 // We only conservatively allow a few kinds of casts, because this code is
12403 // inherently a simple solution that seeks to support the common case.
12404 auto CastKind = Cast->getCastKind();
12405 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
12406 CastKind != CK_AddressSpaceConversion)
12407 return NoParens;
12408
12409 const auto *SubExpr = Cast->getSubExpr();
12410 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
12411 return NoParens;
12412 return ignorePointerCastsAndParens(SubExpr);
12413}
12414
12415/// Checks to see if the given LValue's Designator is at the end of the LValue's
12416/// record layout. e.g.
12417/// struct { struct { int a, b; } fst, snd; } obj;
12418/// obj.fst // no
12419/// obj.snd // yes
12420/// obj.fst.a // no
12421/// obj.fst.b // no
12422/// obj.snd.a // no
12423/// obj.snd.b // yes
12424///
12425/// Please note: this function is specialized for how __builtin_object_size
12426/// views "objects".
12427///
12428/// If this encounters an invalid RecordDecl or otherwise cannot determine the
12429/// correct result, it will always return true.
12430static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
12431 assert(!LVal.Designator.Invalid);
12432
12433 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
12434 const RecordDecl *Parent = FD->getParent();
12435 Invalid = Parent->isInvalidDecl();
12436 if (Invalid || Parent->isUnion())
12437 return true;
12438 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
12439 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
12440 };
12441
12442 auto &Base = LVal.getLValueBase();
12443 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
12444 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
12445 bool Invalid;
12446 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
12447 return Invalid;
12448 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
12449 for (auto *FD : IFD->chain()) {
12450 bool Invalid;
12451 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
12452 return Invalid;
12453 }
12454 }
12455 }
12456
12457 unsigned I = 0;
12458 QualType BaseType = getType(Base);
12459 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
12460 // If we don't know the array bound, conservatively assume we're looking at
12461 // the final array element.
12462 ++I;
12463 if (BaseType->isIncompleteArrayType())
12464 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
12465 else
12466 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
12467 }
12468
12469 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
12470 const auto &Entry = LVal.Designator.Entries[I];
12471 if (BaseType->isArrayType()) {
12472 // Because __builtin_object_size treats arrays as objects, we can ignore
12473 // the index iff this is the last array in the Designator.
12474 if (I + 1 == E)
12475 return true;
12476 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
12477 uint64_t Index = Entry.getAsArrayIndex();
12478 if (Index + 1 != CAT->getZExtSize())
12479 return false;
12480 BaseType = CAT->getElementType();
12481 } else if (BaseType->isAnyComplexType()) {
12482 const auto *CT = BaseType->castAs<ComplexType>();
12483 uint64_t Index = Entry.getAsArrayIndex();
12484 if (Index != 1)
12485 return false;
12486 BaseType = CT->getElementType();
12487 } else if (auto *FD = getAsField(Entry)) {
12488 bool Invalid;
12489 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
12490 return Invalid;
12491 BaseType = FD->getType();
12492 } else {
12493 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
12494 return false;
12495 }
12496 }
12497 return true;
12498}
12499
12500/// Tests to see if the LValue has a user-specified designator (that isn't
12501/// necessarily valid). Note that this always returns 'true' if the LValue has
12502/// an unsized array as its first designator entry, because there's currently no
12503/// way to tell if the user typed *foo or foo[0].
12504static bool refersToCompleteObject(const LValue &LVal) {
12505 if (LVal.Designator.Invalid)
12506 return false;
12507
12508 if (!LVal.Designator.Entries.empty())
12509 return LVal.Designator.isMostDerivedAnUnsizedArray();
12510
12511 if (!LVal.InvalidBase)
12512 return true;
12513
12514 // If `E` is a MemberExpr, then the first part of the designator is hiding in
12515 // the LValueBase.
12516 const auto *E = LVal.Base.dyn_cast<const Expr *>();
12517 return !E || !isa<MemberExpr>(E);
12518}
12519
12520/// Attempts to detect a user writing into a piece of memory that's impossible
12521/// to figure out the size of by just using types.
12522static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
12523 const SubobjectDesignator &Designator = LVal.Designator;
12524 // Notes:
12525 // - Users can only write off of the end when we have an invalid base. Invalid
12526 // bases imply we don't know where the memory came from.
12527 // - We used to be a bit more aggressive here; we'd only be conservative if
12528 // the array at the end was flexible, or if it had 0 or 1 elements. This
12529 // broke some common standard library extensions (PR30346), but was
12530 // otherwise seemingly fine. It may be useful to reintroduce this behavior
12531 // with some sort of list. OTOH, it seems that GCC is always
12532 // conservative with the last element in structs (if it's an array), so our
12533 // current behavior is more compatible than an explicit list approach would
12534 // be.
12535 auto isFlexibleArrayMember = [&] {
12537 FAMKind StrictFlexArraysLevel =
12538 Ctx.getLangOpts().getStrictFlexArraysLevel();
12539
12540 if (Designator.isMostDerivedAnUnsizedArray())
12541 return true;
12542
12543 if (StrictFlexArraysLevel == FAMKind::Default)
12544 return true;
12545
12546 if (Designator.getMostDerivedArraySize() == 0 &&
12547 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
12548 return true;
12549
12550 if (Designator.getMostDerivedArraySize() == 1 &&
12551 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
12552 return true;
12553
12554 return false;
12555 };
12556
12557 return LVal.InvalidBase &&
12558 Designator.Entries.size() == Designator.MostDerivedPathLength &&
12559 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
12560 isDesignatorAtObjectEnd(Ctx, LVal);
12561}
12562
12563/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
12564/// Fails if the conversion would cause loss of precision.
12565static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
12566 CharUnits &Result) {
12567 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
12568 if (Int.ugt(CharUnitsMax))
12569 return false;
12570 Result = CharUnits::fromQuantity(Int.getZExtValue());
12571 return true;
12572}
12573
12574/// If we're evaluating the object size of an instance of a struct that
12575/// contains a flexible array member, add the size of the initializer.
12576static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
12577 const LValue &LV, CharUnits &Size) {
12578 if (!T.isNull() && T->isStructureType() &&
12580 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
12581 if (const auto *VD = dyn_cast<VarDecl>(V))
12582 if (VD->hasInit())
12583 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
12584}
12585
12586/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
12587/// determine how many bytes exist from the beginning of the object to either
12588/// the end of the current subobject, or the end of the object itself, depending
12589/// on what the LValue looks like + the value of Type.
12590///
12591/// If this returns false, the value of Result is undefined.
12592static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
12593 unsigned Type, const LValue &LVal,
12594 CharUnits &EndOffset) {
12595 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
12596
12597 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
12598 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
12599 return false;
12600 return HandleSizeof(Info, ExprLoc, Ty, Result);
12601 };
12602
12603 // We want to evaluate the size of the entire object. This is a valid fallback
12604 // for when Type=1 and the designator is invalid, because we're asked for an
12605 // upper-bound.
12606 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
12607 // Type=3 wants a lower bound, so we can't fall back to this.
12608 if (Type == 3 && !DetermineForCompleteObject)
12609 return false;
12610
12611 llvm::APInt APEndOffset;
12612 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12613 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12614 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12615
12616 if (LVal.InvalidBase)
12617 return false;
12618
12619 QualType BaseTy = getObjectType(LVal.getLValueBase());
12620 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
12621 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
12622 return Ret;
12623 }
12624
12625 // We want to evaluate the size of a subobject.
12626 const SubobjectDesignator &Designator = LVal.Designator;
12627
12628 // The following is a moderately common idiom in C:
12629 //
12630 // struct Foo { int a; char c[1]; };
12631 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
12632 // strcpy(&F->c[0], Bar);
12633 //
12634 // In order to not break too much legacy code, we need to support it.
12635 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
12636 // If we can resolve this to an alloc_size call, we can hand that back,
12637 // because we know for certain how many bytes there are to write to.
12638 llvm::APInt APEndOffset;
12639 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12640 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12641 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12642
12643 // If we cannot determine the size of the initial allocation, then we can't
12644 // given an accurate upper-bound. However, we are still able to give
12645 // conservative lower-bounds for Type=3.
12646 if (Type == 1)
12647 return false;
12648 }
12649
12650 CharUnits BytesPerElem;
12651 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
12652 return false;
12653
12654 // According to the GCC documentation, we want the size of the subobject
12655 // denoted by the pointer. But that's not quite right -- what we actually
12656 // want is the size of the immediately-enclosing array, if there is one.
12657 int64_t ElemsRemaining;
12658 if (Designator.MostDerivedIsArrayElement &&
12659 Designator.Entries.size() == Designator.MostDerivedPathLength) {
12660 uint64_t ArraySize = Designator.getMostDerivedArraySize();
12661 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
12662 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
12663 } else {
12664 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
12665 }
12666
12667 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
12668 return true;
12669}
12670
12671/// Tries to evaluate the __builtin_object_size for @p E. If successful,
12672/// returns true and stores the result in @p Size.
12673///
12674/// If @p WasError is non-null, this will report whether the failure to evaluate
12675/// is to be treated as an Error in IntExprEvaluator.
12676static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
12677 EvalInfo &Info, uint64_t &Size) {
12678 // Determine the denoted object.
12679 LValue LVal;
12680 {
12681 // The operand of __builtin_object_size is never evaluated for side-effects.
12682 // If there are any, but we can determine the pointed-to object anyway, then
12683 // ignore the side-effects.
12684 SpeculativeEvaluationRAII SpeculativeEval(Info);
12685 IgnoreSideEffectsRAII Fold(Info);
12686
12687 if (E->isGLValue()) {
12688 // It's possible for us to be given GLValues if we're called via
12689 // Expr::tryEvaluateObjectSize.
12690 APValue RVal;
12691 if (!EvaluateAsRValue(Info, E, RVal))
12692 return false;
12693 LVal.setFrom(Info.Ctx, RVal);
12694 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
12695 /*InvalidBaseOK=*/true))
12696 return false;
12697 }
12698
12699 // If we point to before the start of the object, there are no accessible
12700 // bytes.
12701 if (LVal.getLValueOffset().isNegative()) {
12702 Size = 0;
12703 return true;
12704 }
12705
12706 CharUnits EndOffset;
12707 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
12708 return false;
12709
12710 // If we've fallen outside of the end offset, just pretend there's nothing to
12711 // write to/read from.
12712 if (EndOffset <= LVal.getLValueOffset())
12713 Size = 0;
12714 else
12715 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
12716 return true;
12717}
12718
12719bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
12720 if (!IsConstantEvaluatedBuiltinCall(E))
12721 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12722 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
12723}
12724
12725static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
12726 APValue &Val, APSInt &Alignment) {
12727 QualType SrcTy = E->getArg(0)->getType();
12728 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
12729 return false;
12730 // Even though we are evaluating integer expressions we could get a pointer
12731 // argument for the __builtin_is_aligned() case.
12732 if (SrcTy->isPointerType()) {
12733 LValue Ptr;
12734 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
12735 return false;
12736 Ptr.moveInto(Val);
12737 } else if (!SrcTy->isIntegralOrEnumerationType()) {
12738 Info.FFDiag(E->getArg(0));
12739 return false;
12740 } else {
12741 APSInt SrcInt;
12742 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
12743 return false;
12744 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
12745 "Bit widths must be the same");
12746 Val = APValue(SrcInt);
12747 }
12748 assert(Val.hasValue());
12749 return true;
12750}
12751
12752bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
12753 unsigned BuiltinOp) {
12754 switch (BuiltinOp) {
12755 default:
12756 return false;
12757
12758 case Builtin::BI__builtin_dynamic_object_size:
12759 case Builtin::BI__builtin_object_size: {
12760 // The type was checked when we built the expression.
12761 unsigned Type =
12762 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12763 assert(Type <= 3 && "unexpected type");
12764
12765 uint64_t Size;
12766 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
12767 return Success(Size, E);
12768
12769 if (E->getArg(0)->HasSideEffects(Info.Ctx))
12770 return Success((Type & 2) ? 0 : -1, E);
12771
12772 // Expression had no side effects, but we couldn't statically determine the
12773 // size of the referenced object.
12774 switch (Info.EvalMode) {
12775 case EvalInfo::EM_ConstantExpression:
12776 case EvalInfo::EM_ConstantFold:
12777 case EvalInfo::EM_IgnoreSideEffects:
12778 // Leave it to IR generation.
12779 return Error(E);
12780 case EvalInfo::EM_ConstantExpressionUnevaluated:
12781 // Reduce it to a constant now.
12782 return Success((Type & 2) ? 0 : -1, E);
12783 }
12784
12785 llvm_unreachable("unexpected EvalMode");
12786 }
12787
12788 case Builtin::BI__builtin_os_log_format_buffer_size: {
12791 return Success(Layout.size().getQuantity(), E);
12792 }
12793
12794 case Builtin::BI__builtin_is_aligned: {
12795 APValue Src;
12796 APSInt Alignment;
12797 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12798 return false;
12799 if (Src.isLValue()) {
12800 // If we evaluated a pointer, check the minimum known alignment.
12801 LValue Ptr;
12802 Ptr.setFrom(Info.Ctx, Src);
12803 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
12804 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
12805 // We can return true if the known alignment at the computed offset is
12806 // greater than the requested alignment.
12807 assert(PtrAlign.isPowerOfTwo());
12808 assert(Alignment.isPowerOf2());
12809 if (PtrAlign.getQuantity() >= Alignment)
12810 return Success(1, E);
12811 // If the alignment is not known to be sufficient, some cases could still
12812 // be aligned at run time. However, if the requested alignment is less or
12813 // equal to the base alignment and the offset is not aligned, we know that
12814 // the run-time value can never be aligned.
12815 if (BaseAlignment.getQuantity() >= Alignment &&
12816 PtrAlign.getQuantity() < Alignment)
12817 return Success(0, E);
12818 // Otherwise we can't infer whether the value is sufficiently aligned.
12819 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
12820 // in cases where we can't fully evaluate the pointer.
12821 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
12822 << Alignment;
12823 return false;
12824 }
12825 assert(Src.isInt());
12826 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
12827 }
12828 case Builtin::BI__builtin_align_up: {
12829 APValue Src;
12830 APSInt Alignment;
12831 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12832 return false;
12833 if (!Src.isInt())
12834 return Error(E);
12835 APSInt AlignedVal =
12836 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
12837 Src.getInt().isUnsigned());
12838 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12839 return Success(AlignedVal, E);
12840 }
12841 case Builtin::BI__builtin_align_down: {
12842 APValue Src;
12843 APSInt Alignment;
12844 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12845 return false;
12846 if (!Src.isInt())
12847 return Error(E);
12848 APSInt AlignedVal =
12849 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
12850 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12851 return Success(AlignedVal, E);
12852 }
12853
12854 case Builtin::BI__builtin_bitreverse8:
12855 case Builtin::BI__builtin_bitreverse16:
12856 case Builtin::BI__builtin_bitreverse32:
12857 case Builtin::BI__builtin_bitreverse64:
12858 case Builtin::BI__builtin_elementwise_bitreverse: {
12859 APSInt Val;
12860 if (!EvaluateInteger(E->getArg(0), Val, Info))
12861 return false;
12862
12863 return Success(Val.reverseBits(), E);
12864 }
12865
12866 case Builtin::BI__builtin_bswap16:
12867 case Builtin::BI__builtin_bswap32:
12868 case Builtin::BI__builtin_bswap64: {
12869 APSInt Val;
12870 if (!EvaluateInteger(E->getArg(0), Val, Info))
12871 return false;
12872
12873 return Success(Val.byteSwap(), E);
12874 }
12875
12876 case Builtin::BI__builtin_classify_type:
12877 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
12878
12879 case Builtin::BI__builtin_clrsb:
12880 case Builtin::BI__builtin_clrsbl:
12881 case Builtin::BI__builtin_clrsbll: {
12882 APSInt Val;
12883 if (!EvaluateInteger(E->getArg(0), Val, Info))
12884 return false;
12885
12886 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
12887 }
12888
12889 case Builtin::BI__builtin_clz:
12890 case Builtin::BI__builtin_clzl:
12891 case Builtin::BI__builtin_clzll:
12892 case Builtin::BI__builtin_clzs:
12893 case Builtin::BI__builtin_clzg:
12894 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
12895 case Builtin::BI__lzcnt:
12896 case Builtin::BI__lzcnt64: {
12897 APSInt Val;
12898 if (!EvaluateInteger(E->getArg(0), Val, Info))
12899 return false;
12900
12901 std::optional<APSInt> Fallback;
12902 if (BuiltinOp == Builtin::BI__builtin_clzg && E->getNumArgs() > 1) {
12903 APSInt FallbackTemp;
12904 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
12905 return false;
12906 Fallback = FallbackTemp;
12907 }
12908
12909 if (!Val) {
12910 if (Fallback)
12911 return Success(*Fallback, E);
12912
12913 // When the argument is 0, the result of GCC builtins is undefined,
12914 // whereas for Microsoft intrinsics, the result is the bit-width of the
12915 // argument.
12916 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
12917 BuiltinOp != Builtin::BI__lzcnt &&
12918 BuiltinOp != Builtin::BI__lzcnt64;
12919
12920 if (ZeroIsUndefined)
12921 return Error(E);
12922 }
12923
12924 return Success(Val.countl_zero(), E);
12925 }
12926
12927 case Builtin::BI__builtin_constant_p: {
12928 const Expr *Arg = E->getArg(0);
12929 if (EvaluateBuiltinConstantP(Info, Arg))
12930 return Success(true, E);
12931 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
12932 // Outside a constant context, eagerly evaluate to false in the presence
12933 // of side-effects in order to avoid -Wunsequenced false-positives in
12934 // a branch on __builtin_constant_p(expr).
12935 return Success(false, E);
12936 }
12937 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12938 return false;
12939 }
12940
12941 case Builtin::BI__noop:
12942 // __noop always evaluates successfully and returns 0.
12943 return Success(0, E);
12944
12945 case Builtin::BI__builtin_is_constant_evaluated: {
12946 const auto *Callee = Info.CurrentCall->getCallee();
12947 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
12948 (Info.CallStackDepth == 1 ||
12949 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
12950 Callee->getIdentifier() &&
12951 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
12952 // FIXME: Find a better way to avoid duplicated diagnostics.
12953 if (Info.EvalStatus.Diag)
12954 Info.report((Info.CallStackDepth == 1)
12955 ? E->getExprLoc()
12956 : Info.CurrentCall->getCallRange().getBegin(),
12957 diag::warn_is_constant_evaluated_always_true_constexpr)
12958 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
12959 : "std::is_constant_evaluated");
12960 }
12961
12962 return Success(Info.InConstantContext, E);
12963 }
12964
12965 case Builtin::BI__builtin_is_within_lifetime:
12966 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
12967 return Success(*result, E);
12968 return false;
12969
12970 case Builtin::BI__builtin_ctz:
12971 case Builtin::BI__builtin_ctzl:
12972 case Builtin::BI__builtin_ctzll:
12973 case Builtin::BI__builtin_ctzs:
12974 case Builtin::BI__builtin_ctzg: {
12975 APSInt Val;
12976 if (!EvaluateInteger(E->getArg(0), Val, Info))
12977 return false;
12978
12979 std::optional<APSInt> Fallback;
12980 if (BuiltinOp == Builtin::BI__builtin_ctzg && E->getNumArgs() > 1) {
12981 APSInt FallbackTemp;
12982 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
12983 return false;
12984 Fallback = FallbackTemp;
12985 }
12986
12987 if (!Val) {
12988 if (Fallback)
12989 return Success(*Fallback, E);
12990
12991 return Error(E);
12992 }
12993
12994 return Success(Val.countr_zero(), E);
12995 }
12996
12997 case Builtin::BI__builtin_eh_return_data_regno: {
12998 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12999 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
13000 return Success(Operand, E);
13001 }
13002
13003 case Builtin::BI__builtin_expect:
13004 case Builtin::BI__builtin_expect_with_probability:
13005 return Visit(E->getArg(0));
13006
13007 case Builtin::BI__builtin_ptrauth_string_discriminator: {
13008 const auto *Literal =
13009 cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts());
13010 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
13011 return Success(Result, E);
13012 }
13013
13014 case Builtin::BI__builtin_ffs:
13015 case Builtin::BI__builtin_ffsl:
13016 case Builtin::BI__builtin_ffsll: {
13017 APSInt Val;
13018 if (!EvaluateInteger(E->getArg(0), Val, Info))
13019 return false;
13020
13021 unsigned N = Val.countr_zero();
13022 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
13023 }
13024
13025 case Builtin::BI__builtin_fpclassify: {
13026 APFloat Val(0.0);
13027 if (!EvaluateFloat(E->getArg(5), Val, Info))
13028 return false;
13029 unsigned Arg;
13030 switch (Val.getCategory()) {
13031 case APFloat::fcNaN: Arg = 0; break;
13032 case APFloat::fcInfinity: Arg = 1; break;
13033 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
13034 case APFloat::fcZero: Arg = 4; break;
13035 }
13036 return Visit(E->getArg(Arg));
13037 }
13038
13039 case Builtin::BI__builtin_isinf_sign: {
13040 APFloat Val(0.0);
13041 return EvaluateFloat(E->getArg(0), Val, Info) &&
13042 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
13043 }
13044
13045 case Builtin::BI__builtin_isinf: {
13046 APFloat Val(0.0);
13047 return EvaluateFloat(E->getArg(0), Val, Info) &&
13048 Success(Val.isInfinity() ? 1 : 0, E);
13049 }
13050
13051 case Builtin::BI__builtin_isfinite: {
13052 APFloat Val(0.0);
13053 return EvaluateFloat(E->getArg(0), Val, Info) &&
13054 Success(Val.isFinite() ? 1 : 0, E);
13055 }
13056
13057 case Builtin::BI__builtin_isnan: {
13058 APFloat Val(0.0);
13059 return EvaluateFloat(E->getArg(0), Val, Info) &&
13060 Success(Val.isNaN() ? 1 : 0, E);
13061 }
13062
13063 case Builtin::BI__builtin_isnormal: {
13064 APFloat Val(0.0);
13065 return EvaluateFloat(E->getArg(0), Val, Info) &&
13066 Success(Val.isNormal() ? 1 : 0, E);
13067 }
13068
13069 case Builtin::BI__builtin_issubnormal: {
13070 APFloat Val(0.0);
13071 return EvaluateFloat(E->getArg(0), Val, Info) &&
13072 Success(Val.isDenormal() ? 1 : 0, E);
13073 }
13074
13075 case Builtin::BI__builtin_iszero: {
13076 APFloat Val(0.0);
13077 return EvaluateFloat(E->getArg(0), Val, Info) &&
13078 Success(Val.isZero() ? 1 : 0, E);
13079 }
13080
13081 case Builtin::BI__builtin_signbit:
13082 case Builtin::BI__builtin_signbitf:
13083 case Builtin::BI__builtin_signbitl: {
13084 APFloat Val(0.0);
13085 return EvaluateFloat(E->getArg(0), Val, Info) &&
13086 Success(Val.isNegative() ? 1 : 0, E);
13087 }
13088
13089 case Builtin::BI__builtin_isgreater:
13090 case Builtin::BI__builtin_isgreaterequal:
13091 case Builtin::BI__builtin_isless:
13092 case Builtin::BI__builtin_islessequal:
13093 case Builtin::BI__builtin_islessgreater:
13094 case Builtin::BI__builtin_isunordered: {
13095 APFloat LHS(0.0);
13096 APFloat RHS(0.0);
13097 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
13098 !EvaluateFloat(E->getArg(1), RHS, Info))
13099 return false;
13100
13101 return Success(
13102 [&] {
13103 switch (BuiltinOp) {
13104 case Builtin::BI__builtin_isgreater:
13105 return LHS > RHS;
13106 case Builtin::BI__builtin_isgreaterequal:
13107 return LHS >= RHS;
13108 case Builtin::BI__builtin_isless:
13109 return LHS < RHS;
13110 case Builtin::BI__builtin_islessequal:
13111 return LHS <= RHS;
13112 case Builtin::BI__builtin_islessgreater: {
13113 APFloat::cmpResult cmp = LHS.compare(RHS);
13114 return cmp == APFloat::cmpResult::cmpLessThan ||
13115 cmp == APFloat::cmpResult::cmpGreaterThan;
13116 }
13117 case Builtin::BI__builtin_isunordered:
13118 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
13119 default:
13120 llvm_unreachable("Unexpected builtin ID: Should be a floating "
13121 "point comparison function");
13122 }
13123 }()
13124 ? 1
13125 : 0,
13126 E);
13127 }
13128
13129 case Builtin::BI__builtin_issignaling: {
13130 APFloat Val(0.0);
13131 return EvaluateFloat(E->getArg(0), Val, Info) &&
13132 Success(Val.isSignaling() ? 1 : 0, E);
13133 }
13134
13135 case Builtin::BI__builtin_isfpclass: {
13136 APSInt MaskVal;
13137 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
13138 return false;
13139 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
13140 APFloat Val(0.0);
13141 return EvaluateFloat(E->getArg(0), Val, Info) &&
13142 Success((Val.classify() & Test) ? 1 : 0, E);
13143 }
13144
13145 case Builtin::BI__builtin_parity:
13146 case Builtin::BI__builtin_parityl:
13147 case Builtin::BI__builtin_parityll: {
13148 APSInt Val;
13149 if (!EvaluateInteger(E->getArg(0), Val, Info))
13150 return false;
13151
13152 return Success(Val.popcount() % 2, E);
13153 }
13154
13155 case Builtin::BI__builtin_abs:
13156 case Builtin::BI__builtin_labs:
13157 case Builtin::BI__builtin_llabs: {
13158 APSInt Val;
13159 if (!EvaluateInteger(E->getArg(0), Val, Info))
13160 return false;
13161 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
13162 /*IsUnsigned=*/false))
13163 return false;
13164 if (Val.isNegative())
13165 Val.negate();
13166 return Success(Val, E);
13167 }
13168
13169 case Builtin::BI__builtin_popcount:
13170 case Builtin::BI__builtin_popcountl:
13171 case Builtin::BI__builtin_popcountll:
13172 case Builtin::BI__builtin_popcountg:
13173 case Builtin::BI__builtin_elementwise_popcount:
13174 case Builtin::BI__popcnt16: // Microsoft variants of popcount
13175 case Builtin::BI__popcnt:
13176 case Builtin::BI__popcnt64: {
13177 APSInt Val;
13178 if (!EvaluateInteger(E->getArg(0), Val, Info))
13179 return false;
13180
13181 return Success(Val.popcount(), E);
13182 }
13183
13184 case Builtin::BI__builtin_rotateleft8:
13185 case Builtin::BI__builtin_rotateleft16:
13186 case Builtin::BI__builtin_rotateleft32:
13187 case Builtin::BI__builtin_rotateleft64:
13188 case Builtin::BI_rotl8: // Microsoft variants of rotate right
13189 case Builtin::BI_rotl16:
13190 case Builtin::BI_rotl:
13191 case Builtin::BI_lrotl:
13192 case Builtin::BI_rotl64: {
13193 APSInt Val, Amt;
13194 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13195 !EvaluateInteger(E->getArg(1), Amt, Info))
13196 return false;
13197
13198 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
13199 }
13200
13201 case Builtin::BI__builtin_rotateright8:
13202 case Builtin::BI__builtin_rotateright16:
13203 case Builtin::BI__builtin_rotateright32:
13204 case Builtin::BI__builtin_rotateright64:
13205 case Builtin::BI_rotr8: // Microsoft variants of rotate right
13206 case Builtin::BI_rotr16:
13207 case Builtin::BI_rotr:
13208 case Builtin::BI_lrotr:
13209 case Builtin::BI_rotr64: {
13210 APSInt Val, Amt;
13211 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13212 !EvaluateInteger(E->getArg(1), Amt, Info))
13213 return false;
13214
13215 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
13216 }
13217
13218 case Builtin::BI__builtin_elementwise_add_sat: {
13219 APSInt LHS, RHS;
13220 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13221 !EvaluateInteger(E->getArg(1), RHS, Info))
13222 return false;
13223
13224 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
13225 return Success(APSInt(Result, !LHS.isSigned()), E);
13226 }
13227 case Builtin::BI__builtin_elementwise_sub_sat: {
13228 APSInt LHS, RHS;
13229 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13230 !EvaluateInteger(E->getArg(1), RHS, Info))
13231 return false;
13232
13233 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
13234 return Success(APSInt(Result, !LHS.isSigned()), E);
13235 }
13236
13237 case Builtin::BIstrlen:
13238 case Builtin::BIwcslen:
13239 // A call to strlen is not a constant expression.
13240 if (Info.getLangOpts().CPlusPlus11)
13241 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
13242 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
13243 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
13244 else
13245 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
13246 [[fallthrough]];
13247 case Builtin::BI__builtin_strlen:
13248 case Builtin::BI__builtin_wcslen: {
13249 // As an extension, we support __builtin_strlen() as a constant expression,
13250 // and support folding strlen() to a constant.
13251 uint64_t StrLen;
13252 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
13253 return Success(StrLen, E);
13254 return false;
13255 }
13256
13257 case Builtin::BIstrcmp:
13258 case Builtin::BIwcscmp:
13259 case Builtin::BIstrncmp:
13260 case Builtin::BIwcsncmp:
13261 case Builtin::BImemcmp:
13262 case Builtin::BIbcmp:
13263 case Builtin::BIwmemcmp:
13264 // A call to strlen is not a constant expression.
13265 if (Info.getLangOpts().CPlusPlus11)
13266 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
13267 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
13268 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
13269 else
13270 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
13271 [[fallthrough]];
13272 case Builtin::BI__builtin_strcmp:
13273 case Builtin::BI__builtin_wcscmp:
13274 case Builtin::BI__builtin_strncmp:
13275 case Builtin::BI__builtin_wcsncmp:
13276 case Builtin::BI__builtin_memcmp:
13277 case Builtin::BI__builtin_bcmp:
13278 case Builtin::BI__builtin_wmemcmp: {
13279 LValue String1, String2;
13280 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
13281 !EvaluatePointer(E->getArg(1), String2, Info))
13282 return false;
13283
13284 uint64_t MaxLength = uint64_t(-1);
13285 if (BuiltinOp != Builtin::BIstrcmp &&
13286 BuiltinOp != Builtin::BIwcscmp &&
13287 BuiltinOp != Builtin::BI__builtin_strcmp &&
13288 BuiltinOp != Builtin::BI__builtin_wcscmp) {
13289 APSInt N;
13290 if (!EvaluateInteger(E->getArg(2), N, Info))
13291 return false;
13292 MaxLength = N.getZExtValue();
13293 }
13294
13295 // Empty substrings compare equal by definition.
13296 if (MaxLength == 0u)
13297 return Success(0, E);
13298
13299 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
13300 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
13301 String1.Designator.Invalid || String2.Designator.Invalid)
13302 return false;
13303
13304 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
13305 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
13306
13307 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
13308 BuiltinOp == Builtin::BIbcmp ||
13309 BuiltinOp == Builtin::BI__builtin_memcmp ||
13310 BuiltinOp == Builtin::BI__builtin_bcmp;
13311
13312 assert(IsRawByte ||
13313 (Info.Ctx.hasSameUnqualifiedType(
13314 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
13315 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
13316
13317 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
13318 // 'char8_t', but no other types.
13319 if (IsRawByte &&
13320 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
13321 // FIXME: Consider using our bit_cast implementation to support this.
13322 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
13323 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
13324 << CharTy2;
13325 return false;
13326 }
13327
13328 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
13329 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
13330 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
13331 Char1.isInt() && Char2.isInt();
13332 };
13333 const auto &AdvanceElems = [&] {
13334 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
13335 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
13336 };
13337
13338 bool StopAtNull =
13339 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
13340 BuiltinOp != Builtin::BIwmemcmp &&
13341 BuiltinOp != Builtin::BI__builtin_memcmp &&
13342 BuiltinOp != Builtin::BI__builtin_bcmp &&
13343 BuiltinOp != Builtin::BI__builtin_wmemcmp);
13344 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
13345 BuiltinOp == Builtin::BIwcsncmp ||
13346 BuiltinOp == Builtin::BIwmemcmp ||
13347 BuiltinOp == Builtin::BI__builtin_wcscmp ||
13348 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
13349 BuiltinOp == Builtin::BI__builtin_wmemcmp;
13350
13351 for (; MaxLength; --MaxLength) {
13352 APValue Char1, Char2;
13353 if (!ReadCurElems(Char1, Char2))
13354 return false;
13355 if (Char1.getInt().ne(Char2.getInt())) {
13356 if (IsWide) // wmemcmp compares with wchar_t signedness.
13357 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
13358 // memcmp always compares unsigned chars.
13359 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
13360 }
13361 if (StopAtNull && !Char1.getInt())
13362 return Success(0, E);
13363 assert(!(StopAtNull && !Char2.getInt()));
13364 if (!AdvanceElems())
13365 return false;
13366 }
13367 // We hit the strncmp / memcmp limit.
13368 return Success(0, E);
13369 }
13370
13371 case Builtin::BI__atomic_always_lock_free:
13372 case Builtin::BI__atomic_is_lock_free:
13373 case Builtin::BI__c11_atomic_is_lock_free: {
13374 APSInt SizeVal;
13375 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
13376 return false;
13377
13378 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
13379 // of two less than or equal to the maximum inline atomic width, we know it
13380 // is lock-free. If the size isn't a power of two, or greater than the
13381 // maximum alignment where we promote atomics, we know it is not lock-free
13382 // (at least not in the sense of atomic_is_lock_free). Otherwise,
13383 // the answer can only be determined at runtime; for example, 16-byte
13384 // atomics have lock-free implementations on some, but not all,
13385 // x86-64 processors.
13386
13387 // Check power-of-two.
13388 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
13389 if (Size.isPowerOfTwo()) {
13390 // Check against inlining width.
13391 unsigned InlineWidthBits =
13392 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
13393 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
13394 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
13395 Size == CharUnits::One())
13396 return Success(1, E);
13397
13398 // If the pointer argument can be evaluated to a compile-time constant
13399 // integer (or nullptr), check if that value is appropriately aligned.
13400 const Expr *PtrArg = E->getArg(1);
13402 APSInt IntResult;
13403 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
13404 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
13405 Info.Ctx) &&
13406 IntResult.isAligned(Size.getAsAlign()))
13407 return Success(1, E);
13408
13409 // Otherwise, check if the type's alignment against Size.
13410 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
13411 // Drop the potential implicit-cast to 'const volatile void*', getting
13412 // the underlying type.
13413 if (ICE->getCastKind() == CK_BitCast)
13414 PtrArg = ICE->getSubExpr();
13415 }
13416
13417 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
13418 QualType PointeeType = PtrTy->getPointeeType();
13419 if (!PointeeType->isIncompleteType() &&
13420 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
13421 // OK, we will inline operations on this object.
13422 return Success(1, E);
13423 }
13424 }
13425 }
13426 }
13427
13428 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
13429 Success(0, E) : Error(E);
13430 }
13431 case Builtin::BI__builtin_addcb:
13432 case Builtin::BI__builtin_addcs:
13433 case Builtin::BI__builtin_addc:
13434 case Builtin::BI__builtin_addcl:
13435 case Builtin::BI__builtin_addcll:
13436 case Builtin::BI__builtin_subcb:
13437 case Builtin::BI__builtin_subcs:
13438 case Builtin::BI__builtin_subc:
13439 case Builtin::BI__builtin_subcl:
13440 case Builtin::BI__builtin_subcll: {
13441 LValue CarryOutLValue;
13442 APSInt LHS, RHS, CarryIn, CarryOut, Result;
13443 QualType ResultType = E->getArg(0)->getType();
13444 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13445 !EvaluateInteger(E->getArg(1), RHS, Info) ||
13446 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
13447 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
13448 return false;
13449 // Copy the number of bits and sign.
13450 Result = LHS;
13451 CarryOut = LHS;
13452
13453 bool FirstOverflowed = false;
13454 bool SecondOverflowed = false;
13455 switch (BuiltinOp) {
13456 default:
13457 llvm_unreachable("Invalid value for BuiltinOp");
13458 case Builtin::BI__builtin_addcb:
13459 case Builtin::BI__builtin_addcs:
13460 case Builtin::BI__builtin_addc:
13461 case Builtin::BI__builtin_addcl:
13462 case Builtin::BI__builtin_addcll:
13463 Result =
13464 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
13465 break;
13466 case Builtin::BI__builtin_subcb:
13467 case Builtin::BI__builtin_subcs:
13468 case Builtin::BI__builtin_subc:
13469 case Builtin::BI__builtin_subcl:
13470 case Builtin::BI__builtin_subcll:
13471 Result =
13472 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
13473 break;
13474 }
13475
13476 // It is possible for both overflows to happen but CGBuiltin uses an OR so
13477 // this is consistent.
13478 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
13479 APValue APV{CarryOut};
13480 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
13481 return false;
13482 return Success(Result, E);
13483 }
13484 case Builtin::BI__builtin_add_overflow:
13485 case Builtin::BI__builtin_sub_overflow:
13486 case Builtin::BI__builtin_mul_overflow:
13487 case Builtin::BI__builtin_sadd_overflow:
13488 case Builtin::BI__builtin_uadd_overflow:
13489 case Builtin::BI__builtin_uaddl_overflow:
13490 case Builtin::BI__builtin_uaddll_overflow:
13491 case Builtin::BI__builtin_usub_overflow:
13492 case Builtin::BI__builtin_usubl_overflow:
13493 case Builtin::BI__builtin_usubll_overflow:
13494 case Builtin::BI__builtin_umul_overflow:
13495 case Builtin::BI__builtin_umull_overflow:
13496 case Builtin::BI__builtin_umulll_overflow:
13497 case Builtin::BI__builtin_saddl_overflow:
13498 case Builtin::BI__builtin_saddll_overflow:
13499 case Builtin::BI__builtin_ssub_overflow:
13500 case Builtin::BI__builtin_ssubl_overflow:
13501 case Builtin::BI__builtin_ssubll_overflow:
13502 case Builtin::BI__builtin_smul_overflow:
13503 case Builtin::BI__builtin_smull_overflow:
13504 case Builtin::BI__builtin_smulll_overflow: {
13505 LValue ResultLValue;
13506 APSInt LHS, RHS;
13507
13508 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
13509 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13510 !EvaluateInteger(E->getArg(1), RHS, Info) ||
13511 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
13512 return false;
13513
13514 APSInt Result;
13515 bool DidOverflow = false;
13516
13517 // If the types don't have to match, enlarge all 3 to the largest of them.
13518 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
13519 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
13520 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
13521 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
13523 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
13525 uint64_t LHSSize = LHS.getBitWidth();
13526 uint64_t RHSSize = RHS.getBitWidth();
13527 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
13528 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
13529
13530 // Add an additional bit if the signedness isn't uniformly agreed to. We
13531 // could do this ONLY if there is a signed and an unsigned that both have
13532 // MaxBits, but the code to check that is pretty nasty. The issue will be
13533 // caught in the shrink-to-result later anyway.
13534 if (IsSigned && !AllSigned)
13535 ++MaxBits;
13536
13537 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
13538 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
13539 Result = APSInt(MaxBits, !IsSigned);
13540 }
13541
13542 // Find largest int.
13543 switch (BuiltinOp) {
13544 default:
13545 llvm_unreachable("Invalid value for BuiltinOp");
13546 case Builtin::BI__builtin_add_overflow:
13547 case Builtin::BI__builtin_sadd_overflow:
13548 case Builtin::BI__builtin_saddl_overflow:
13549 case Builtin::BI__builtin_saddll_overflow:
13550 case Builtin::BI__builtin_uadd_overflow:
13551 case Builtin::BI__builtin_uaddl_overflow:
13552 case Builtin::BI__builtin_uaddll_overflow:
13553 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
13554 : LHS.uadd_ov(RHS, DidOverflow);
13555 break;
13556 case Builtin::BI__builtin_sub_overflow:
13557 case Builtin::BI__builtin_ssub_overflow:
13558 case Builtin::BI__builtin_ssubl_overflow:
13559 case Builtin::BI__builtin_ssubll_overflow:
13560 case Builtin::BI__builtin_usub_overflow:
13561 case Builtin::BI__builtin_usubl_overflow:
13562 case Builtin::BI__builtin_usubll_overflow:
13563 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
13564 : LHS.usub_ov(RHS, DidOverflow);
13565 break;
13566 case Builtin::BI__builtin_mul_overflow:
13567 case Builtin::BI__builtin_smul_overflow:
13568 case Builtin::BI__builtin_smull_overflow:
13569 case Builtin::BI__builtin_smulll_overflow:
13570 case Builtin::BI__builtin_umul_overflow:
13571 case Builtin::BI__builtin_umull_overflow:
13572 case Builtin::BI__builtin_umulll_overflow:
13573 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
13574 : LHS.umul_ov(RHS, DidOverflow);
13575 break;
13576 }
13577
13578 // In the case where multiple sizes are allowed, truncate and see if
13579 // the values are the same.
13580 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
13581 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
13582 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
13583 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
13584 // since it will give us the behavior of a TruncOrSelf in the case where
13585 // its parameter <= its size. We previously set Result to be at least the
13586 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
13587 // will work exactly like TruncOrSelf.
13588 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
13589 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
13590
13591 if (!APSInt::isSameValue(Temp, Result))
13592 DidOverflow = true;
13593 Result = Temp;
13594 }
13595
13596 APValue APV{Result};
13597 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
13598 return false;
13599 return Success(DidOverflow, E);
13600 }
13601
13602 case Builtin::BI__builtin_reduce_add:
13603 case Builtin::BI__builtin_reduce_mul:
13604 case Builtin::BI__builtin_reduce_and:
13605 case Builtin::BI__builtin_reduce_or:
13606 case Builtin::BI__builtin_reduce_xor:
13607 case Builtin::BI__builtin_reduce_min:
13608 case Builtin::BI__builtin_reduce_max: {
13609 APValue Source;
13610 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
13611 return false;
13612
13613 unsigned SourceLen = Source.getVectorLength();
13614 APSInt Reduced = Source.getVectorElt(0).getInt();
13615 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
13616 switch (BuiltinOp) {
13617 default:
13618 return false;
13619 case Builtin::BI__builtin_reduce_add: {
13621 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
13622 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
13623 return false;
13624 break;
13625 }
13626 case Builtin::BI__builtin_reduce_mul: {
13628 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
13629 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
13630 return false;
13631 break;
13632 }
13633 case Builtin::BI__builtin_reduce_and: {
13634 Reduced &= Source.getVectorElt(EltNum).getInt();
13635 break;
13636 }
13637 case Builtin::BI__builtin_reduce_or: {
13638 Reduced |= Source.getVectorElt(EltNum).getInt();
13639 break;
13640 }
13641 case Builtin::BI__builtin_reduce_xor: {
13642 Reduced ^= Source.getVectorElt(EltNum).getInt();
13643 break;
13644 }
13645 case Builtin::BI__builtin_reduce_min: {
13646 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
13647 break;
13648 }
13649 case Builtin::BI__builtin_reduce_max: {
13650 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
13651 break;
13652 }
13653 }
13654 }
13655
13656 return Success(Reduced, E);
13657 }
13658
13659 case clang::X86::BI__builtin_ia32_addcarryx_u32:
13660 case clang::X86::BI__builtin_ia32_addcarryx_u64:
13661 case clang::X86::BI__builtin_ia32_subborrow_u32:
13662 case clang::X86::BI__builtin_ia32_subborrow_u64: {
13663 LValue ResultLValue;
13664 APSInt CarryIn, LHS, RHS;
13665 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
13666 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
13667 !EvaluateInteger(E->getArg(1), LHS, Info) ||
13668 !EvaluateInteger(E->getArg(2), RHS, Info) ||
13669 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
13670 return false;
13671
13672 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
13673 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
13674
13675 unsigned BitWidth = LHS.getBitWidth();
13676 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
13677 APInt ExResult =
13678 IsAdd
13679 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
13680 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
13681
13682 APInt Result = ExResult.extractBits(BitWidth, 0);
13683 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
13684
13685 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
13686 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
13687 return false;
13688 return Success(CarryOut, E);
13689 }
13690
13691 case clang::X86::BI__builtin_ia32_bextr_u32:
13692 case clang::X86::BI__builtin_ia32_bextr_u64:
13693 case clang::X86::BI__builtin_ia32_bextri_u32:
13694 case clang::X86::BI__builtin_ia32_bextri_u64: {
13695 APSInt Val, Idx;
13696 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13697 !EvaluateInteger(E->getArg(1), Idx, Info))
13698 return false;
13699
13700 unsigned BitWidth = Val.getBitWidth();
13701 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
13702 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
13703 Length = Length > BitWidth ? BitWidth : Length;
13704
13705 // Handle out of bounds cases.
13706 if (Length == 0 || Shift >= BitWidth)
13707 return Success(0, E);
13708
13709 uint64_t Result = Val.getZExtValue() >> Shift;
13710 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
13711 return Success(Result, E);
13712 }
13713
13714 case clang::X86::BI__builtin_ia32_bzhi_si:
13715 case clang::X86::BI__builtin_ia32_bzhi_di: {
13716 APSInt Val, Idx;
13717 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13718 !EvaluateInteger(E->getArg(1), Idx, Info))
13719 return false;
13720
13721 unsigned BitWidth = Val.getBitWidth();
13722 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
13723 if (Index < BitWidth)
13724 Val.clearHighBits(BitWidth - Index);
13725 return Success(Val, E);
13726 }
13727
13728 case clang::X86::BI__builtin_ia32_lzcnt_u16:
13729 case clang::X86::BI__builtin_ia32_lzcnt_u32:
13730 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
13731 APSInt Val;
13732 if (!EvaluateInteger(E->getArg(0), Val, Info))
13733 return false;
13734 return Success(Val.countLeadingZeros(), E);
13735 }
13736
13737 case clang::X86::BI__builtin_ia32_tzcnt_u16:
13738 case clang::X86::BI__builtin_ia32_tzcnt_u32:
13739 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
13740 APSInt Val;
13741 if (!EvaluateInteger(E->getArg(0), Val, Info))
13742 return false;
13743 return Success(Val.countTrailingZeros(), E);
13744 }
13745
13746 case clang::X86::BI__builtin_ia32_pdep_si:
13747 case clang::X86::BI__builtin_ia32_pdep_di: {
13748 APSInt Val, Msk;
13749 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13750 !EvaluateInteger(E->getArg(1), Msk, Info))
13751 return false;
13752
13753 unsigned BitWidth = Val.getBitWidth();
13754 APInt Result = APInt::getZero(BitWidth);
13755 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
13756 if (Msk[I])
13757 Result.setBitVal(I, Val[P++]);
13758 return Success(Result, E);
13759 }
13760
13761 case clang::X86::BI__builtin_ia32_pext_si:
13762 case clang::X86::BI__builtin_ia32_pext_di: {
13763 APSInt Val, Msk;
13764 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13765 !EvaluateInteger(E->getArg(1), Msk, Info))
13766 return false;
13767
13768 unsigned BitWidth = Val.getBitWidth();
13769 APInt Result = APInt::getZero(BitWidth);
13770 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
13771 if (Msk[I])
13772 Result.setBitVal(P++, Val[I]);
13773 return Success(Result, E);
13774 }
13775 }
13776}
13777
13778/// Determine whether this is a pointer past the end of the complete
13779/// object referred to by the lvalue.
13781 const LValue &LV) {
13782 // A null pointer can be viewed as being "past the end" but we don't
13783 // choose to look at it that way here.
13784 if (!LV.getLValueBase())
13785 return false;
13786
13787 // If the designator is valid and refers to a subobject, we're not pointing
13788 // past the end.
13789 if (!LV.getLValueDesignator().Invalid &&
13790 !LV.getLValueDesignator().isOnePastTheEnd())
13791 return false;
13792
13793 // A pointer to an incomplete type might be past-the-end if the type's size is
13794 // zero. We cannot tell because the type is incomplete.
13795 QualType Ty = getType(LV.getLValueBase());
13796 if (Ty->isIncompleteType())
13797 return true;
13798
13799 // Can't be past the end of an invalid object.
13800 if (LV.getLValueDesignator().Invalid)
13801 return false;
13802
13803 // We're a past-the-end pointer if we point to the byte after the object,
13804 // no matter what our type or path is.
13805 auto Size = Ctx.getTypeSizeInChars(Ty);
13806 return LV.getLValueOffset() == Size;
13807}
13808
13809namespace {
13810
13811/// Data recursive integer evaluator of certain binary operators.
13812///
13813/// We use a data recursive algorithm for binary operators so that we are able
13814/// to handle extreme cases of chained binary operators without causing stack
13815/// overflow.
13816class DataRecursiveIntBinOpEvaluator {
13817 struct EvalResult {
13818 APValue Val;
13819 bool Failed = false;
13820
13821 EvalResult() = default;
13822
13823 void swap(EvalResult &RHS) {
13824 Val.swap(RHS.Val);
13825 Failed = RHS.Failed;
13826 RHS.Failed = false;
13827 }
13828 };
13829
13830 struct Job {
13831 const Expr *E;
13832 EvalResult LHSResult; // meaningful only for binary operator expression.
13833 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
13834
13835 Job() = default;
13836 Job(Job &&) = default;
13837
13838 void startSpeculativeEval(EvalInfo &Info) {
13839 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
13840 }
13841
13842 private:
13843 SpeculativeEvaluationRAII SpecEvalRAII;
13844 };
13845
13847
13848 IntExprEvaluator &IntEval;
13849 EvalInfo &Info;
13850 APValue &FinalResult;
13851
13852public:
13853 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
13854 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
13855
13856 /// True if \param E is a binary operator that we are going to handle
13857 /// data recursively.
13858 /// We handle binary operators that are comma, logical, or that have operands
13859 /// with integral or enumeration type.
13860 static bool shouldEnqueue(const BinaryOperator *E) {
13861 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
13863 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13864 E->getRHS()->getType()->isIntegralOrEnumerationType());
13865 }
13866
13867 bool Traverse(const BinaryOperator *E) {
13868 enqueue(E);
13869 EvalResult PrevResult;
13870 while (!Queue.empty())
13871 process(PrevResult);
13872
13873 if (PrevResult.Failed) return false;
13874
13875 FinalResult.swap(PrevResult.Val);
13876 return true;
13877 }
13878
13879private:
13880 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
13881 return IntEval.Success(Value, E, Result);
13882 }
13883 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
13884 return IntEval.Success(Value, E, Result);
13885 }
13886 bool Error(const Expr *E) {
13887 return IntEval.Error(E);
13888 }
13889 bool Error(const Expr *E, diag::kind D) {
13890 return IntEval.Error(E, D);
13891 }
13892
13893 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
13894 return Info.CCEDiag(E, D);
13895 }
13896
13897 // Returns true if visiting the RHS is necessary, false otherwise.
13898 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
13899 bool &SuppressRHSDiags);
13900
13901 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
13902 const BinaryOperator *E, APValue &Result);
13903
13904 void EvaluateExpr(const Expr *E, EvalResult &Result) {
13905 Result.Failed = !Evaluate(Result.Val, Info, E);
13906 if (Result.Failed)
13907 Result.Val = APValue();
13908 }
13909
13910 void process(EvalResult &Result);
13911
13912 void enqueue(const Expr *E) {
13913 E = E->IgnoreParens();
13914 Queue.resize(Queue.size()+1);
13915 Queue.back().E = E;
13916 Queue.back().Kind = Job::AnyExprKind;
13917 }
13918};
13919
13920}
13921
13922bool DataRecursiveIntBinOpEvaluator::
13923 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
13924 bool &SuppressRHSDiags) {
13925 if (E->getOpcode() == BO_Comma) {
13926 // Ignore LHS but note if we could not evaluate it.
13927 if (LHSResult.Failed)
13928 return Info.noteSideEffect();
13929 return true;
13930 }
13931
13932 if (E->isLogicalOp()) {
13933 bool LHSAsBool;
13934 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
13935 // We were able to evaluate the LHS, see if we can get away with not
13936 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
13937 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
13938 Success(LHSAsBool, E, LHSResult.Val);
13939 return false; // Ignore RHS
13940 }
13941 } else {
13942 LHSResult.Failed = true;
13943
13944 // Since we weren't able to evaluate the left hand side, it
13945 // might have had side effects.
13946 if (!Info.noteSideEffect())
13947 return false;
13948
13949 // We can't evaluate the LHS; however, sometimes the result
13950 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
13951 // Don't ignore RHS and suppress diagnostics from this arm.
13952 SuppressRHSDiags = true;
13953 }
13954
13955 return true;
13956 }
13957
13958 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13959 E->getRHS()->getType()->isIntegralOrEnumerationType());
13960
13961 if (LHSResult.Failed && !Info.noteFailure())
13962 return false; // Ignore RHS;
13963
13964 return true;
13965}
13966
13967static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
13968 bool IsSub) {
13969 // Compute the new offset in the appropriate width, wrapping at 64 bits.
13970 // FIXME: When compiling for a 32-bit target, we should use 32-bit
13971 // offsets.
13972 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
13973 CharUnits &Offset = LVal.getLValueOffset();
13974 uint64_t Offset64 = Offset.getQuantity();
13975 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
13976 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
13977 : Offset64 + Index64);
13978}
13979
13980bool DataRecursiveIntBinOpEvaluator::
13981 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
13982 const BinaryOperator *E, APValue &Result) {
13983 if (E->getOpcode() == BO_Comma) {
13984 if (RHSResult.Failed)
13985 return false;
13986 Result = RHSResult.Val;
13987 return true;
13988 }
13989
13990 if (E->isLogicalOp()) {
13991 bool lhsResult, rhsResult;
13992 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
13993 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
13994
13995 if (LHSIsOK) {
13996 if (RHSIsOK) {
13997 if (E->getOpcode() == BO_LOr)
13998 return Success(lhsResult || rhsResult, E, Result);
13999 else
14000 return Success(lhsResult && rhsResult, E, Result);
14001 }
14002 } else {
14003 if (RHSIsOK) {
14004 // We can't evaluate the LHS; however, sometimes the result
14005 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
14006 if (rhsResult == (E->getOpcode() == BO_LOr))
14007 return Success(rhsResult, E, Result);
14008 }
14009 }
14010
14011 return false;
14012 }
14013
14014 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
14015 E->getRHS()->getType()->isIntegralOrEnumerationType());
14016
14017 if (LHSResult.Failed || RHSResult.Failed)
14018 return false;
14019
14020 const APValue &LHSVal = LHSResult.Val;
14021 const APValue &RHSVal = RHSResult.Val;
14022
14023 // Handle cases like (unsigned long)&a + 4.
14024 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
14025 Result = LHSVal;
14026 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
14027 return true;
14028 }
14029
14030 // Handle cases like 4 + (unsigned long)&a
14031 if (E->getOpcode() == BO_Add &&
14032 RHSVal.isLValue() && LHSVal.isInt()) {
14033 Result = RHSVal;
14034 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
14035 return true;
14036 }
14037
14038 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
14039 // Handle (intptr_t)&&A - (intptr_t)&&B.
14040 if (!LHSVal.getLValueOffset().isZero() ||
14041 !RHSVal.getLValueOffset().isZero())
14042 return false;
14043 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
14044 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
14045 if (!LHSExpr || !RHSExpr)
14046 return false;
14047 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
14048 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
14049 if (!LHSAddrExpr || !RHSAddrExpr)
14050 return false;
14051 // Make sure both labels come from the same function.
14052 if (LHSAddrExpr->getLabel()->getDeclContext() !=
14053 RHSAddrExpr->getLabel()->getDeclContext())
14054 return false;
14055 Result = APValue(LHSAddrExpr, RHSAddrExpr);
14056 return true;
14057 }
14058
14059 // All the remaining cases expect both operands to be an integer
14060 if (!LHSVal.isInt() || !RHSVal.isInt())
14061 return Error(E);
14062
14063 // Set up the width and signedness manually, in case it can't be deduced
14064 // from the operation we're performing.
14065 // FIXME: Don't do this in the cases where we can deduce it.
14066 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
14068 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
14069 RHSVal.getInt(), Value))
14070 return false;
14071 return Success(Value, E, Result);
14072}
14073
14074void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
14075 Job &job = Queue.back();
14076
14077 switch (job.Kind) {
14078 case Job::AnyExprKind: {
14079 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
14080 if (shouldEnqueue(Bop)) {
14081 job.Kind = Job::BinOpKind;
14082 enqueue(Bop->getLHS());
14083 return;
14084 }
14085 }
14086
14087 EvaluateExpr(job.E, Result);
14088 Queue.pop_back();
14089 return;
14090 }
14091
14092 case Job::BinOpKind: {
14093 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
14094 bool SuppressRHSDiags = false;
14095 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
14096 Queue.pop_back();
14097 return;
14098 }
14099 if (SuppressRHSDiags)
14100 job.startSpeculativeEval(Info);
14101 job.LHSResult.swap(Result);
14102 job.Kind = Job::BinOpVisitedLHSKind;
14103 enqueue(Bop->getRHS());
14104 return;
14105 }
14106
14107 case Job::BinOpVisitedLHSKind: {
14108 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
14109 EvalResult RHS;
14110 RHS.swap(Result);
14111 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
14112 Queue.pop_back();
14113 return;
14114 }
14115 }
14116
14117 llvm_unreachable("Invalid Job::Kind!");
14118}
14119
14120namespace {
14121enum class CmpResult {
14122 Unequal,
14123 Less,
14124 Equal,
14125 Greater,
14126 Unordered,
14127};
14128}
14129
14130template <class SuccessCB, class AfterCB>
14131static bool
14133 SuccessCB &&Success, AfterCB &&DoAfter) {
14134 assert(!E->isValueDependent());
14135 assert(E->isComparisonOp() && "expected comparison operator");
14136 assert((E->getOpcode() == BO_Cmp ||
14138 "unsupported binary expression evaluation");
14139 auto Error = [&](const Expr *E) {
14140 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14141 return false;
14142 };
14143
14144 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
14145 bool IsEquality = E->isEqualityOp();
14146
14147 QualType LHSTy = E->getLHS()->getType();
14148 QualType RHSTy = E->getRHS()->getType();
14149
14150 if (LHSTy->isIntegralOrEnumerationType() &&
14151 RHSTy->isIntegralOrEnumerationType()) {
14152 APSInt LHS, RHS;
14153 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
14154 if (!LHSOK && !Info.noteFailure())
14155 return false;
14156 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
14157 return false;
14158 if (LHS < RHS)
14159 return Success(CmpResult::Less, E);
14160 if (LHS > RHS)
14161 return Success(CmpResult::Greater, E);
14162 return Success(CmpResult::Equal, E);
14163 }
14164
14165 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
14166 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
14167 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
14168
14169 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
14170 if (!LHSOK && !Info.noteFailure())
14171 return false;
14172 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
14173 return false;
14174 if (LHSFX < RHSFX)
14175 return Success(CmpResult::Less, E);
14176 if (LHSFX > RHSFX)
14177 return Success(CmpResult::Greater, E);
14178 return Success(CmpResult::Equal, E);
14179 }
14180
14181 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
14182 ComplexValue LHS, RHS;
14183 bool LHSOK;
14184 if (E->isAssignmentOp()) {
14185 LValue LV;
14186 EvaluateLValue(E->getLHS(), LV, Info);
14187 LHSOK = false;
14188 } else if (LHSTy->isRealFloatingType()) {
14189 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
14190 if (LHSOK) {
14191 LHS.makeComplexFloat();
14192 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
14193 }
14194 } else {
14195 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
14196 }
14197 if (!LHSOK && !Info.noteFailure())
14198 return false;
14199
14200 if (E->getRHS()->getType()->isRealFloatingType()) {
14201 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
14202 return false;
14203 RHS.makeComplexFloat();
14204 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
14205 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14206 return false;
14207
14208 if (LHS.isComplexFloat()) {
14209 APFloat::cmpResult CR_r =
14210 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
14211 APFloat::cmpResult CR_i =
14212 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
14213 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
14214 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
14215 } else {
14216 assert(IsEquality && "invalid complex comparison");
14217 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
14218 LHS.getComplexIntImag() == RHS.getComplexIntImag();
14219 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
14220 }
14221 }
14222
14223 if (LHSTy->isRealFloatingType() &&
14224 RHSTy->isRealFloatingType()) {
14225 APFloat RHS(0.0), LHS(0.0);
14226
14227 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
14228 if (!LHSOK && !Info.noteFailure())
14229 return false;
14230
14231 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
14232 return false;
14233
14234 assert(E->isComparisonOp() && "Invalid binary operator!");
14235 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
14236 if (!Info.InConstantContext &&
14237 APFloatCmpResult == APFloat::cmpUnordered &&
14238 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
14239 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
14240 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
14241 return false;
14242 }
14243 auto GetCmpRes = [&]() {
14244 switch (APFloatCmpResult) {
14245 case APFloat::cmpEqual:
14246 return CmpResult::Equal;
14247 case APFloat::cmpLessThan:
14248 return CmpResult::Less;
14249 case APFloat::cmpGreaterThan:
14250 return CmpResult::Greater;
14251 case APFloat::cmpUnordered:
14252 return CmpResult::Unordered;
14253 }
14254 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
14255 };
14256 return Success(GetCmpRes(), E);
14257 }
14258
14259 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
14260 LValue LHSValue, RHSValue;
14261
14262 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
14263 if (!LHSOK && !Info.noteFailure())
14264 return false;
14265
14266 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
14267 return false;
14268
14269 // Reject differing bases from the normal codepath; we special-case
14270 // comparisons to null.
14271 if (!HasSameBase(LHSValue, RHSValue)) {
14272 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
14273 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
14274 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
14275 Info.FFDiag(E, DiagID)
14276 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
14277 return false;
14278 };
14279 // Inequalities and subtractions between unrelated pointers have
14280 // unspecified or undefined behavior.
14281 if (!IsEquality)
14282 return DiagComparison(
14283 diag::note_constexpr_pointer_comparison_unspecified);
14284 // A constant address may compare equal to the address of a symbol.
14285 // The one exception is that address of an object cannot compare equal
14286 // to a null pointer constant.
14287 // TODO: Should we restrict this to actual null pointers, and exclude the
14288 // case of zero cast to pointer type?
14289 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
14290 (!RHSValue.Base && !RHSValue.Offset.isZero()))
14291 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
14292 !RHSValue.Base);
14293 // C++2c [intro.object]/10:
14294 // Two objects [...] may have the same address if [...] they are both
14295 // potentially non-unique objects.
14296 // C++2c [intro.object]/9:
14297 // An object is potentially non-unique if it is a string literal object,
14298 // the backing array of an initializer list, or a subobject thereof.
14299 //
14300 // This makes the comparison result unspecified, so it's not a constant
14301 // expression.
14302 //
14303 // TODO: Do we need to handle the initializer list case here?
14304 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
14305 return DiagComparison(diag::note_constexpr_literal_comparison);
14306 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
14307 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
14308 !IsOpaqueConstantCall(LHSValue));
14309 // We can't tell whether weak symbols will end up pointing to the same
14310 // object.
14311 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
14312 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
14313 !IsWeakLValue(LHSValue));
14314 // We can't compare the address of the start of one object with the
14315 // past-the-end address of another object, per C++ DR1652.
14316 if (LHSValue.Base && LHSValue.Offset.isZero() &&
14317 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
14318 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
14319 true);
14320 if (RHSValue.Base && RHSValue.Offset.isZero() &&
14321 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
14322 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
14323 false);
14324 // We can't tell whether an object is at the same address as another
14325 // zero sized object.
14326 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
14327 (LHSValue.Base && isZeroSized(RHSValue)))
14328 return DiagComparison(
14329 diag::note_constexpr_pointer_comparison_zero_sized);
14330 return Success(CmpResult::Unequal, E);
14331 }
14332
14333 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
14334 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
14335
14336 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
14337 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
14338
14339 // C++11 [expr.rel]p2:
14340 // - If two pointers point to non-static data members of the same object,
14341 // or to subobjects or array elements fo such members, recursively, the
14342 // pointer to the later declared member compares greater provided the
14343 // two members have the same access control and provided their class is
14344 // not a union.
14345 // [...]
14346 // - Otherwise pointer comparisons are unspecified.
14347 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
14348 bool WasArrayIndex;
14349 unsigned Mismatch = FindDesignatorMismatch(
14350 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
14351 // At the point where the designators diverge, the comparison has a
14352 // specified value if:
14353 // - we are comparing array indices
14354 // - we are comparing fields of a union, or fields with the same access
14355 // Otherwise, the result is unspecified and thus the comparison is not a
14356 // constant expression.
14357 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
14358 Mismatch < RHSDesignator.Entries.size()) {
14359 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
14360 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
14361 if (!LF && !RF)
14362 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
14363 else if (!LF)
14364 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
14365 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
14366 << RF->getParent() << RF;
14367 else if (!RF)
14368 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
14369 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
14370 << LF->getParent() << LF;
14371 else if (!LF->getParent()->isUnion() &&
14372 LF->getAccess() != RF->getAccess())
14373 Info.CCEDiag(E,
14374 diag::note_constexpr_pointer_comparison_differing_access)
14375 << LF << LF->getAccess() << RF << RF->getAccess()
14376 << LF->getParent();
14377 }
14378 }
14379
14380 // The comparison here must be unsigned, and performed with the same
14381 // width as the pointer.
14382 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
14383 uint64_t CompareLHS = LHSOffset.getQuantity();
14384 uint64_t CompareRHS = RHSOffset.getQuantity();
14385 assert(PtrSize <= 64 && "Unexpected pointer width");
14386 uint64_t Mask = ~0ULL >> (64 - PtrSize);
14387 CompareLHS &= Mask;
14388 CompareRHS &= Mask;
14389
14390 // If there is a base and this is a relational operator, we can only
14391 // compare pointers within the object in question; otherwise, the result
14392 // depends on where the object is located in memory.
14393 if (!LHSValue.Base.isNull() && IsRelational) {
14394 QualType BaseTy = getType(LHSValue.Base);
14395 if (BaseTy->isIncompleteType())
14396 return Error(E);
14397 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
14398 uint64_t OffsetLimit = Size.getQuantity();
14399 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
14400 return Error(E);
14401 }
14402
14403 if (CompareLHS < CompareRHS)
14404 return Success(CmpResult::Less, E);
14405 if (CompareLHS > CompareRHS)
14406 return Success(CmpResult::Greater, E);
14407 return Success(CmpResult::Equal, E);
14408 }
14409
14410 if (LHSTy->isMemberPointerType()) {
14411 assert(IsEquality && "unexpected member pointer operation");
14412 assert(RHSTy->isMemberPointerType() && "invalid comparison");
14413
14414 MemberPtr LHSValue, RHSValue;
14415
14416 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
14417 if (!LHSOK && !Info.noteFailure())
14418 return false;
14419
14420 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
14421 return false;
14422
14423 // If either operand is a pointer to a weak function, the comparison is not
14424 // constant.
14425 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
14426 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
14427 << LHSValue.getDecl();
14428 return false;
14429 }
14430 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
14431 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
14432 << RHSValue.getDecl();
14433 return false;
14434 }
14435
14436 // C++11 [expr.eq]p2:
14437 // If both operands are null, they compare equal. Otherwise if only one is
14438 // null, they compare unequal.
14439 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
14440 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
14441 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
14442 }
14443
14444 // Otherwise if either is a pointer to a virtual member function, the
14445 // result is unspecified.
14446 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
14447 if (MD->isVirtual())
14448 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
14449 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
14450 if (MD->isVirtual())
14451 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
14452
14453 // Otherwise they compare equal if and only if they would refer to the
14454 // same member of the same most derived object or the same subobject if
14455 // they were dereferenced with a hypothetical object of the associated
14456 // class type.
14457 bool Equal = LHSValue == RHSValue;
14458 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
14459 }
14460
14461 if (LHSTy->isNullPtrType()) {
14462 assert(E->isComparisonOp() && "unexpected nullptr operation");
14463 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
14464 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
14465 // are compared, the result is true of the operator is <=, >= or ==, and
14466 // false otherwise.
14467 LValue Res;
14468 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
14469 !EvaluatePointer(E->getRHS(), Res, Info))
14470 return false;
14471 return Success(CmpResult::Equal, E);
14472 }
14473
14474 return DoAfter();
14475}
14476
14477bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
14478 if (!CheckLiteralType(Info, E))
14479 return false;
14480
14481 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
14483 switch (CR) {
14484 case CmpResult::Unequal:
14485 llvm_unreachable("should never produce Unequal for three-way comparison");
14486 case CmpResult::Less:
14487 CCR = ComparisonCategoryResult::Less;
14488 break;
14489 case CmpResult::Equal:
14490 CCR = ComparisonCategoryResult::Equal;
14491 break;
14492 case CmpResult::Greater:
14493 CCR = ComparisonCategoryResult::Greater;
14494 break;
14495 case CmpResult::Unordered:
14496 CCR = ComparisonCategoryResult::Unordered;
14497 break;
14498 }
14499 // Evaluation succeeded. Lookup the information for the comparison category
14500 // type and fetch the VarDecl for the result.
14501 const ComparisonCategoryInfo &CmpInfo =
14503 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
14504 // Check and evaluate the result as a constant expression.
14505 LValue LV;
14506 LV.set(VD);
14507 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14508 return false;
14509 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14510 ConstantExprKind::Normal);
14511 };
14512 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
14513 return ExprEvaluatorBaseTy::VisitBinCmp(E);
14514 });
14515}
14516
14517bool RecordExprEvaluator::VisitCXXParenListInitExpr(
14518 const CXXParenListInitExpr *E) {
14519 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
14520}
14521
14522bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14523 // We don't support assignment in C. C++ assignments don't get here because
14524 // assignment is an lvalue in C++.
14525 if (E->isAssignmentOp()) {
14526 Error(E);
14527 if (!Info.noteFailure())
14528 return false;
14529 }
14530
14531 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
14532 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
14533
14534 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
14535 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
14536 "DataRecursiveIntBinOpEvaluator should have handled integral types");
14537
14538 if (E->isComparisonOp()) {
14539 // Evaluate builtin binary comparisons by evaluating them as three-way
14540 // comparisons and then translating the result.
14541 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
14542 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
14543 "should only produce Unequal for equality comparisons");
14544 bool IsEqual = CR == CmpResult::Equal,
14545 IsLess = CR == CmpResult::Less,
14546 IsGreater = CR == CmpResult::Greater;
14547 auto Op = E->getOpcode();
14548 switch (Op) {
14549 default:
14550 llvm_unreachable("unsupported binary operator");
14551 case BO_EQ:
14552 case BO_NE:
14553 return Success(IsEqual == (Op == BO_EQ), E);
14554 case BO_LT:
14555 return Success(IsLess, E);
14556 case BO_GT:
14557 return Success(IsGreater, E);
14558 case BO_LE:
14559 return Success(IsEqual || IsLess, E);
14560 case BO_GE:
14561 return Success(IsEqual || IsGreater, E);
14562 }
14563 };
14564 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
14565 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14566 });
14567 }
14568
14569 QualType LHSTy = E->getLHS()->getType();
14570 QualType RHSTy = E->getRHS()->getType();
14571
14572 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
14573 E->getOpcode() == BO_Sub) {
14574 LValue LHSValue, RHSValue;
14575
14576 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
14577 if (!LHSOK && !Info.noteFailure())
14578 return false;
14579
14580 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
14581 return false;
14582
14583 // Reject differing bases from the normal codepath; we special-case
14584 // comparisons to null.
14585 if (!HasSameBase(LHSValue, RHSValue)) {
14586 // Handle &&A - &&B.
14587 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
14588 return Error(E);
14589 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
14590 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
14591 if (!LHSExpr || !RHSExpr)
14592 return Error(E);
14593 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
14594 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
14595 if (!LHSAddrExpr || !RHSAddrExpr)
14596 return Error(E);
14597 // Make sure both labels come from the same function.
14598 if (LHSAddrExpr->getLabel()->getDeclContext() !=
14599 RHSAddrExpr->getLabel()->getDeclContext())
14600 return Error(E);
14601 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
14602 }
14603 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
14604 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
14605
14606 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
14607 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
14608
14609 // C++11 [expr.add]p6:
14610 // Unless both pointers point to elements of the same array object, or
14611 // one past the last element of the array object, the behavior is
14612 // undefined.
14613 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
14614 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
14615 RHSDesignator))
14616 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
14617
14618 QualType Type = E->getLHS()->getType();
14619 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
14620
14621 CharUnits ElementSize;
14622 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
14623 return false;
14624
14625 // As an extension, a type may have zero size (empty struct or union in
14626 // C, array of zero length). Pointer subtraction in such cases has
14627 // undefined behavior, so is not constant.
14628 if (ElementSize.isZero()) {
14629 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
14630 << ElementType;
14631 return false;
14632 }
14633
14634 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
14635 // and produce incorrect results when it overflows. Such behavior
14636 // appears to be non-conforming, but is common, so perhaps we should
14637 // assume the standard intended for such cases to be undefined behavior
14638 // and check for them.
14639
14640 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
14641 // overflow in the final conversion to ptrdiff_t.
14642 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
14643 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
14644 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
14645 false);
14646 APSInt TrueResult = (LHS - RHS) / ElemSize;
14647 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
14648
14649 if (Result.extend(65) != TrueResult &&
14650 !HandleOverflow(Info, E, TrueResult, E->getType()))
14651 return false;
14652 return Success(Result, E);
14653 }
14654
14655 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14656}
14657
14658/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
14659/// a result as the expression's type.
14660bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
14661 const UnaryExprOrTypeTraitExpr *E) {
14662 switch(E->getKind()) {
14663 case UETT_PreferredAlignOf:
14664 case UETT_AlignOf: {
14665 if (E->isArgumentType())
14666 return Success(
14667 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
14668 else
14669 return Success(
14670 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
14671 }
14672
14673 case UETT_PtrAuthTypeDiscriminator: {
14674 if (E->getArgumentType()->isDependentType())
14675 return false;
14676 return Success(
14677 Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
14678 }
14679 case UETT_VecStep: {
14680 QualType Ty = E->getTypeOfArgument();
14681
14682 if (Ty->isVectorType()) {
14683 unsigned n = Ty->castAs<VectorType>()->getNumElements();
14684
14685 // The vec_step built-in functions that take a 3-component
14686 // vector return 4. (OpenCL 1.1 spec 6.11.12)
14687 if (n == 3)
14688 n = 4;
14689
14690 return Success(n, E);
14691 } else
14692 return Success(1, E);
14693 }
14694
14695 case UETT_DataSizeOf:
14696 case UETT_SizeOf: {
14697 QualType SrcTy = E->getTypeOfArgument();
14698 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
14699 // the result is the size of the referenced type."
14700 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
14701 SrcTy = Ref->getPointeeType();
14702
14703 CharUnits Sizeof;
14704 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
14705 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
14706 : SizeOfType::SizeOf)) {
14707 return false;
14708 }
14709 return Success(Sizeof, E);
14710 }
14711 case UETT_OpenMPRequiredSimdAlign:
14712 assert(E->isArgumentType());
14713 return Success(
14714 Info.Ctx.toCharUnitsFromBits(
14715 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
14716 .getQuantity(),
14717 E);
14718 case UETT_VectorElements: {
14719 QualType Ty = E->getTypeOfArgument();
14720 // If the vector has a fixed size, we can determine the number of elements
14721 // at compile time.
14722 if (const auto *VT = Ty->getAs<VectorType>())
14723 return Success(VT->getNumElements(), E);
14724
14725 assert(Ty->isSizelessVectorType());
14726 if (Info.InConstantContext)
14727 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
14728 << E->getSourceRange();
14729
14730 return false;
14731 }
14732 }
14733
14734 llvm_unreachable("unknown expr/type trait");
14735}
14736
14737bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
14738 CharUnits Result;
14739 unsigned n = OOE->getNumComponents();
14740 if (n == 0)
14741 return Error(OOE);
14742 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
14743 for (unsigned i = 0; i != n; ++i) {
14744 OffsetOfNode ON = OOE->getComponent(i);
14745 switch (ON.getKind()) {
14746 case OffsetOfNode::Array: {
14747 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
14748 APSInt IdxResult;
14749 if (!EvaluateInteger(Idx, IdxResult, Info))
14750 return false;
14751 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
14752 if (!AT)
14753 return Error(OOE);
14754 CurrentType = AT->getElementType();
14755 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
14756 Result += IdxResult.getSExtValue() * ElementSize;
14757 break;
14758 }
14759
14760 case OffsetOfNode::Field: {
14761 FieldDecl *MemberDecl = ON.getField();
14762 const RecordType *RT = CurrentType->getAs<RecordType>();
14763 if (!RT)
14764 return Error(OOE);
14765 RecordDecl *RD = RT->getDecl();
14766 if (RD->isInvalidDecl()) return false;
14767 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
14768 unsigned i = MemberDecl->getFieldIndex();
14769 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
14770 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
14771 CurrentType = MemberDecl->getType().getNonReferenceType();
14772 break;
14773 }
14774
14776 llvm_unreachable("dependent __builtin_offsetof");
14777
14778 case OffsetOfNode::Base: {
14779 CXXBaseSpecifier *BaseSpec = ON.getBase();
14780 if (BaseSpec->isVirtual())
14781 return Error(OOE);
14782
14783 // Find the layout of the class whose base we are looking into.
14784 const RecordType *RT = CurrentType->getAs<RecordType>();
14785 if (!RT)
14786 return Error(OOE);
14787 RecordDecl *RD = RT->getDecl();
14788 if (RD->isInvalidDecl()) return false;
14789 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
14790
14791 // Find the base class itself.
14792 CurrentType = BaseSpec->getType();
14793 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
14794 if (!BaseRT)
14795 return Error(OOE);
14796
14797 // Add the offset to the base.
14798 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
14799 break;
14800 }
14801 }
14802 }
14803 return Success(Result, OOE);
14804}
14805
14806bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14807 switch (E->getOpcode()) {
14808 default:
14809 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
14810 // See C99 6.6p3.
14811 return Error(E);
14812 case UO_Extension:
14813 // FIXME: Should extension allow i-c-e extension expressions in its scope?
14814 // If so, we could clear the diagnostic ID.
14815 return Visit(E->getSubExpr());
14816 case UO_Plus:
14817 // The result is just the value.
14818 return Visit(E->getSubExpr());
14819 case UO_Minus: {
14820 if (!Visit(E->getSubExpr()))
14821 return false;
14822 if (!Result.isInt()) return Error(E);
14823 const APSInt &Value = Result.getInt();
14824 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
14825 if (Info.checkingForUndefinedBehavior())
14826 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14827 diag::warn_integer_constant_overflow)
14828 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
14829 /*UpperCase=*/true, /*InsertSeparators=*/true)
14830 << E->getType() << E->getSourceRange();
14831
14832 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
14833 E->getType()))
14834 return false;
14835 }
14836 return Success(-Value, E);
14837 }
14838 case UO_Not: {
14839 if (!Visit(E->getSubExpr()))
14840 return false;
14841 if (!Result.isInt()) return Error(E);
14842 return Success(~Result.getInt(), E);
14843 }
14844 case UO_LNot: {
14845 bool bres;
14846 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
14847 return false;
14848 return Success(!bres, E);
14849 }
14850 }
14851}
14852
14853/// HandleCast - This is used to evaluate implicit or explicit casts where the
14854/// result type is integer.
14855bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
14856 const Expr *SubExpr = E->getSubExpr();
14857 QualType DestType = E->getType();
14858 QualType SrcType = SubExpr->getType();
14859
14860 switch (E->getCastKind()) {
14861 case CK_BaseToDerived:
14862 case CK_DerivedToBase:
14863 case CK_UncheckedDerivedToBase:
14864 case CK_Dynamic:
14865 case CK_ToUnion:
14866 case CK_ArrayToPointerDecay:
14867 case CK_FunctionToPointerDecay:
14868 case CK_NullToPointer:
14869 case CK_NullToMemberPointer:
14870 case CK_BaseToDerivedMemberPointer:
14871 case CK_DerivedToBaseMemberPointer:
14872 case CK_ReinterpretMemberPointer:
14873 case CK_ConstructorConversion:
14874 case CK_IntegralToPointer:
14875 case CK_ToVoid:
14876 case CK_VectorSplat:
14877 case CK_IntegralToFloating:
14878 case CK_FloatingCast:
14879 case CK_CPointerToObjCPointerCast:
14880 case CK_BlockPointerToObjCPointerCast:
14881 case CK_AnyPointerToBlockPointerCast:
14882 case CK_ObjCObjectLValueCast:
14883 case CK_FloatingRealToComplex:
14884 case CK_FloatingComplexToReal:
14885 case CK_FloatingComplexCast:
14886 case CK_FloatingComplexToIntegralComplex:
14887 case CK_IntegralRealToComplex:
14888 case CK_IntegralComplexCast:
14889 case CK_IntegralComplexToFloatingComplex:
14890 case CK_BuiltinFnToFnPtr:
14891 case CK_ZeroToOCLOpaqueType:
14892 case CK_NonAtomicToAtomic:
14893 case CK_AddressSpaceConversion:
14894 case CK_IntToOCLSampler:
14895 case CK_FloatingToFixedPoint:
14896 case CK_FixedPointToFloating:
14897 case CK_FixedPointCast:
14898 case CK_IntegralToFixedPoint:
14899 case CK_MatrixCast:
14900 llvm_unreachable("invalid cast kind for integral value");
14901
14902 case CK_BitCast:
14903 case CK_Dependent:
14904 case CK_LValueBitCast:
14905 case CK_ARCProduceObject:
14906 case CK_ARCConsumeObject:
14907 case CK_ARCReclaimReturnedObject:
14908 case CK_ARCExtendBlockObject:
14909 case CK_CopyAndAutoreleaseBlockObject:
14910 return Error(E);
14911
14912 case CK_UserDefinedConversion:
14913 case CK_LValueToRValue:
14914 case CK_AtomicToNonAtomic:
14915 case CK_NoOp:
14916 case CK_LValueToRValueBitCast:
14917 case CK_HLSLArrayRValue:
14918 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14919
14920 case CK_MemberPointerToBoolean:
14921 case CK_PointerToBoolean:
14922 case CK_IntegralToBoolean:
14923 case CK_FloatingToBoolean:
14924 case CK_BooleanToSignedIntegral:
14925 case CK_FloatingComplexToBoolean:
14926 case CK_IntegralComplexToBoolean: {
14927 bool BoolResult;
14928 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
14929 return false;
14930 uint64_t IntResult = BoolResult;
14931 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
14932 IntResult = (uint64_t)-1;
14933 return Success(IntResult, E);
14934 }
14935
14936 case CK_FixedPointToIntegral: {
14937 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
14938 if (!EvaluateFixedPoint(SubExpr, Src, Info))
14939 return false;
14940 bool Overflowed;
14941 llvm::APSInt Result = Src.convertToInt(
14942 Info.Ctx.getIntWidth(DestType),
14943 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
14944 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
14945 return false;
14946 return Success(Result, E);
14947 }
14948
14949 case CK_FixedPointToBoolean: {
14950 // Unsigned padding does not affect this.
14951 APValue Val;
14952 if (!Evaluate(Val, Info, SubExpr))
14953 return false;
14954 return Success(Val.getFixedPoint().getBoolValue(), E);
14955 }
14956
14957 case CK_IntegralCast: {
14958 if (!Visit(SubExpr))
14959 return false;
14960
14961 if (!Result.isInt()) {
14962 // Allow casts of address-of-label differences if they are no-ops
14963 // or narrowing. (The narrowing case isn't actually guaranteed to
14964 // be constant-evaluatable except in some narrow cases which are hard
14965 // to detect here. We let it through on the assumption the user knows
14966 // what they are doing.)
14967 if (Result.isAddrLabelDiff())
14968 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
14969 // Only allow casts of lvalues if they are lossless.
14970 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
14971 }
14972
14973 if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
14974 Info.EvalMode == EvalInfo::EM_ConstantExpression &&
14975 DestType->isEnumeralType()) {
14976
14977 bool ConstexprVar = true;
14978
14979 // We know if we are here that we are in a context that we might require
14980 // a constant expression or a context that requires a constant
14981 // value. But if we are initializing a value we don't know if it is a
14982 // constexpr variable or not. We can check the EvaluatingDecl to determine
14983 // if it constexpr or not. If not then we don't want to emit a diagnostic.
14984 if (const auto *VD = dyn_cast_or_null<VarDecl>(
14985 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
14986 ConstexprVar = VD->isConstexpr();
14987
14988 const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());
14989 const EnumDecl *ED = ET->getDecl();
14990 // Check that the value is within the range of the enumeration values.
14991 //
14992 // This corressponds to [expr.static.cast]p10 which says:
14993 // A value of integral or enumeration type can be explicitly converted
14994 // to a complete enumeration type ... If the enumeration type does not
14995 // have a fixed underlying type, the value is unchanged if the original
14996 // value is within the range of the enumeration values ([dcl.enum]), and
14997 // otherwise, the behavior is undefined.
14998 //
14999 // This was resolved as part of DR2338 which has CD5 status.
15000 if (!ED->isFixed()) {
15001 llvm::APInt Min;
15002 llvm::APInt Max;
15003
15004 ED->getValueRange(Max, Min);
15005 --Max;
15006
15007 if (ED->getNumNegativeBits() && ConstexprVar &&
15008 (Max.slt(Result.getInt().getSExtValue()) ||
15009 Min.sgt(Result.getInt().getSExtValue())))
15010 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
15011 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
15012 << Max.getSExtValue() << ED;
15013 else if (!ED->getNumNegativeBits() && ConstexprVar &&
15014 Max.ult(Result.getInt().getZExtValue()))
15015 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
15016 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
15017 << Max.getZExtValue() << ED;
15018 }
15019 }
15020
15021 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
15022 Result.getInt()), E);
15023 }
15024
15025 case CK_PointerToIntegral: {
15026 CCEDiag(E, diag::note_constexpr_invalid_cast)
15027 << 2 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
15028
15029 LValue LV;
15030 if (!EvaluatePointer(SubExpr, LV, Info))
15031 return false;
15032
15033 if (LV.getLValueBase()) {
15034 // Only allow based lvalue casts if they are lossless.
15035 // FIXME: Allow a larger integer size than the pointer size, and allow
15036 // narrowing back down to pointer width in subsequent integral casts.
15037 // FIXME: Check integer type's active bits, not its type size.
15038 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
15039 return Error(E);
15040
15041 LV.Designator.setInvalid();
15042 LV.moveInto(Result);
15043 return true;
15044 }
15045
15046 APSInt AsInt;
15047 APValue V;
15048 LV.moveInto(V);
15049 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
15050 llvm_unreachable("Can't cast this!");
15051
15052 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
15053 }
15054
15055 case CK_IntegralComplexToReal: {
15056 ComplexValue C;
15057 if (!EvaluateComplex(SubExpr, C, Info))
15058 return false;
15059 return Success(C.getComplexIntReal(), E);
15060 }
15061
15062 case CK_FloatingToIntegral: {
15063 APFloat F(0.0);
15064 if (!EvaluateFloat(SubExpr, F, Info))
15065 return false;
15066
15067 APSInt Value;
15068 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
15069 return false;
15070 return Success(Value, E);
15071 }
15072 case CK_HLSLVectorTruncation: {
15073 APValue Val;
15074 if (!EvaluateVector(SubExpr, Val, Info))
15075 return Error(E);
15076 return Success(Val.getVectorElt(0), E);
15077 }
15078 }
15079
15080 llvm_unreachable("unknown cast resulting in integral value");
15081}
15082
15083bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
15084 if (E->getSubExpr()->getType()->isAnyComplexType()) {
15085 ComplexValue LV;
15086 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
15087 return false;
15088 if (!LV.isComplexInt())
15089 return Error(E);
15090 return Success(LV.getComplexIntReal(), E);
15091 }
15092
15093 return Visit(E->getSubExpr());
15094}
15095
15096bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
15097 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
15098 ComplexValue LV;
15099 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
15100 return false;
15101 if (!LV.isComplexInt())
15102 return Error(E);
15103 return Success(LV.getComplexIntImag(), E);
15104 }
15105
15106 VisitIgnoredValue(E->getSubExpr());
15107 return Success(0, E);
15108}
15109
15110bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
15111 return Success(E->getPackLength(), E);
15112}
15113
15114bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
15115 return Success(E->getValue(), E);
15116}
15117
15118bool IntExprEvaluator::VisitConceptSpecializationExpr(
15120 return Success(E->isSatisfied(), E);
15121}
15122
15123bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
15124 return Success(E->isSatisfied(), E);
15125}
15126
15127bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15128 switch (E->getOpcode()) {
15129 default:
15130 // Invalid unary operators
15131 return Error(E);
15132 case UO_Plus:
15133 // The result is just the value.
15134 return Visit(E->getSubExpr());
15135 case UO_Minus: {
15136 if (!Visit(E->getSubExpr())) return false;
15137 if (!Result.isFixedPoint())
15138 return Error(E);
15139 bool Overflowed;
15140 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
15141 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
15142 return false;
15143 return Success(Negated, E);
15144 }
15145 case UO_LNot: {
15146 bool bres;
15147 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
15148 return false;
15149 return Success(!bres, E);
15150 }
15151 }
15152}
15153
15154bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
15155 const Expr *SubExpr = E->getSubExpr();
15156 QualType DestType = E->getType();
15157 assert(DestType->isFixedPointType() &&
15158 "Expected destination type to be a fixed point type");
15159 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
15160
15161 switch (E->getCastKind()) {
15162 case CK_FixedPointCast: {
15163 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
15164 if (!EvaluateFixedPoint(SubExpr, Src, Info))
15165 return false;
15166 bool Overflowed;
15167 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
15168 if (Overflowed) {
15169 if (Info.checkingForUndefinedBehavior())
15170 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15171 diag::warn_fixedpoint_constant_overflow)
15172 << Result.toString() << E->getType();
15173 if (!HandleOverflow(Info, E, Result, E->getType()))
15174 return false;
15175 }
15176 return Success(Result, E);
15177 }
15178 case CK_IntegralToFixedPoint: {
15179 APSInt Src;
15180 if (!EvaluateInteger(SubExpr, Src, Info))
15181 return false;
15182
15183 bool Overflowed;
15184 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
15185 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
15186
15187 if (Overflowed) {
15188 if (Info.checkingForUndefinedBehavior())
15189 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15190 diag::warn_fixedpoint_constant_overflow)
15191 << IntResult.toString() << E->getType();
15192 if (!HandleOverflow(Info, E, IntResult, E->getType()))
15193 return false;
15194 }
15195
15196 return Success(IntResult, E);
15197 }
15198 case CK_FloatingToFixedPoint: {
15199 APFloat Src(0.0);
15200 if (!EvaluateFloat(SubExpr, Src, Info))
15201 return false;
15202
15203 bool Overflowed;
15204 APFixedPoint Result = APFixedPoint::getFromFloatValue(
15205 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
15206
15207 if (Overflowed) {
15208 if (Info.checkingForUndefinedBehavior())
15209 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15210 diag::warn_fixedpoint_constant_overflow)
15211 << Result.toString() << E->getType();
15212 if (!HandleOverflow(Info, E, Result, E->getType()))
15213 return false;
15214 }
15215
15216 return Success(Result, E);
15217 }
15218 case CK_NoOp:
15219 case CK_LValueToRValue:
15220 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15221 default:
15222 return Error(E);
15223 }
15224}
15225
15226bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15227 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15228 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15229
15230 const Expr *LHS = E->getLHS();
15231 const Expr *RHS = E->getRHS();
15232 FixedPointSemantics ResultFXSema =
15233 Info.Ctx.getFixedPointSemantics(E->getType());
15234
15235 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
15236 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
15237 return false;
15238 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
15239 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
15240 return false;
15241
15242 bool OpOverflow = false, ConversionOverflow = false;
15243 APFixedPoint Result(LHSFX.getSemantics());
15244 switch (E->getOpcode()) {
15245 case BO_Add: {
15246 Result = LHSFX.add(RHSFX, &OpOverflow)
15247 .convert(ResultFXSema, &ConversionOverflow);
15248 break;
15249 }
15250 case BO_Sub: {
15251 Result = LHSFX.sub(RHSFX, &OpOverflow)
15252 .convert(ResultFXSema, &ConversionOverflow);
15253 break;
15254 }
15255 case BO_Mul: {
15256 Result = LHSFX.mul(RHSFX, &OpOverflow)
15257 .convert(ResultFXSema, &ConversionOverflow);
15258 break;
15259 }
15260 case BO_Div: {
15261 if (RHSFX.getValue() == 0) {
15262 Info.FFDiag(E, diag::note_expr_divide_by_zero);
15263 return false;
15264 }
15265 Result = LHSFX.div(RHSFX, &OpOverflow)
15266 .convert(ResultFXSema, &ConversionOverflow);
15267 break;
15268 }
15269 case BO_Shl:
15270 case BO_Shr: {
15271 FixedPointSemantics LHSSema = LHSFX.getSemantics();
15272 llvm::APSInt RHSVal = RHSFX.getValue();
15273
15274 unsigned ShiftBW =
15275 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
15276 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
15277 // Embedded-C 4.1.6.2.2:
15278 // The right operand must be nonnegative and less than the total number
15279 // of (nonpadding) bits of the fixed-point operand ...
15280 if (RHSVal.isNegative())
15281 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
15282 else if (Amt != RHSVal)
15283 Info.CCEDiag(E, diag::note_constexpr_large_shift)
15284 << RHSVal << E->getType() << ShiftBW;
15285
15286 if (E->getOpcode() == BO_Shl)
15287 Result = LHSFX.shl(Amt, &OpOverflow);
15288 else
15289 Result = LHSFX.shr(Amt, &OpOverflow);
15290 break;
15291 }
15292 default:
15293 return false;
15294 }
15295 if (OpOverflow || ConversionOverflow) {
15296 if (Info.checkingForUndefinedBehavior())
15297 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15298 diag::warn_fixedpoint_constant_overflow)
15299 << Result.toString() << E->getType();
15300 if (!HandleOverflow(Info, E, Result, E->getType()))
15301 return false;
15302 }
15303 return Success(Result, E);
15304}
15305
15306//===----------------------------------------------------------------------===//
15307// Float Evaluation
15308//===----------------------------------------------------------------------===//
15309
15310namespace {
15311class FloatExprEvaluator
15312 : public ExprEvaluatorBase<FloatExprEvaluator> {
15313 APFloat &Result;
15314public:
15315 FloatExprEvaluator(EvalInfo &info, APFloat &result)
15316 : ExprEvaluatorBaseTy(info), Result(result) {}
15317
15318 bool Success(const APValue &V, const Expr *e) {
15319 Result = V.getFloat();
15320 return true;
15321 }
15322
15323 bool ZeroInitialization(const Expr *E) {
15324 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
15325 return true;
15326 }
15327
15328 bool VisitCallExpr(const CallExpr *E);
15329
15330 bool VisitUnaryOperator(const UnaryOperator *E);
15331 bool VisitBinaryOperator(const BinaryOperator *E);
15332 bool VisitFloatingLiteral(const FloatingLiteral *E);
15333 bool VisitCastExpr(const CastExpr *E);
15334
15335 bool VisitUnaryReal(const UnaryOperator *E);
15336 bool VisitUnaryImag(const UnaryOperator *E);
15337
15338 // FIXME: Missing: array subscript of vector, member of vector
15339};
15340} // end anonymous namespace
15341
15342static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
15343 assert(!E->isValueDependent());
15344 assert(E->isPRValue() && E->getType()->isRealFloatingType());
15345 return FloatExprEvaluator(Info, Result).Visit(E);
15346}
15347
15348static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
15349 QualType ResultTy,
15350 const Expr *Arg,
15351 bool SNaN,
15352 llvm::APFloat &Result) {
15353 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
15354 if (!S) return false;
15355
15356 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
15357
15358 llvm::APInt fill;
15359
15360 // Treat empty strings as if they were zero.
15361 if (S->getString().empty())
15362 fill = llvm::APInt(32, 0);
15363 else if (S->getString().getAsInteger(0, fill))
15364 return false;
15365
15366 if (Context.getTargetInfo().isNan2008()) {
15367 if (SNaN)
15368 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
15369 else
15370 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
15371 } else {
15372 // Prior to IEEE 754-2008, architectures were allowed to choose whether
15373 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
15374 // a different encoding to what became a standard in 2008, and for pre-
15375 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
15376 // sNaN. This is now known as "legacy NaN" encoding.
15377 if (SNaN)
15378 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
15379 else
15380 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
15381 }
15382
15383 return true;
15384}
15385
15386bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
15387 if (!IsConstantEvaluatedBuiltinCall(E))
15388 return ExprEvaluatorBaseTy::VisitCallExpr(E);
15389
15390 switch (E->getBuiltinCallee()) {
15391 default:
15392 return false;
15393
15394 case Builtin::BI__builtin_huge_val:
15395 case Builtin::BI__builtin_huge_valf:
15396 case Builtin::BI__builtin_huge_vall:
15397 case Builtin::BI__builtin_huge_valf16:
15398 case Builtin::BI__builtin_huge_valf128:
15399 case Builtin::BI__builtin_inf:
15400 case Builtin::BI__builtin_inff:
15401 case Builtin::BI__builtin_infl:
15402 case Builtin::BI__builtin_inff16:
15403 case Builtin::BI__builtin_inff128: {
15404 const llvm::fltSemantics &Sem =
15405 Info.Ctx.getFloatTypeSemantics(E->getType());
15406 Result = llvm::APFloat::getInf(Sem);
15407 return true;
15408 }
15409
15410 case Builtin::BI__builtin_nans:
15411 case Builtin::BI__builtin_nansf:
15412 case Builtin::BI__builtin_nansl:
15413 case Builtin::BI__builtin_nansf16:
15414 case Builtin::BI__builtin_nansf128:
15415 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
15416 true, Result))
15417 return Error(E);
15418 return true;
15419
15420 case Builtin::BI__builtin_nan:
15421 case Builtin::BI__builtin_nanf:
15422 case Builtin::BI__builtin_nanl:
15423 case Builtin::BI__builtin_nanf16:
15424 case Builtin::BI__builtin_nanf128:
15425 // If this is __builtin_nan() turn this into a nan, otherwise we
15426 // can't constant fold it.
15427 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
15428 false, Result))
15429 return Error(E);
15430 return true;
15431
15432 case Builtin::BI__builtin_fabs:
15433 case Builtin::BI__builtin_fabsf:
15434 case Builtin::BI__builtin_fabsl:
15435 case Builtin::BI__builtin_fabsf128:
15436 // The C standard says "fabs raises no floating-point exceptions,
15437 // even if x is a signaling NaN. The returned value is independent of
15438 // the current rounding direction mode." Therefore constant folding can
15439 // proceed without regard to the floating point settings.
15440 // Reference, WG14 N2478 F.10.4.3
15441 if (!EvaluateFloat(E->getArg(0), Result, Info))
15442 return false;
15443
15444 if (Result.isNegative())
15445 Result.changeSign();
15446 return true;
15447
15448 case Builtin::BI__arithmetic_fence:
15449 return EvaluateFloat(E->getArg(0), Result, Info);
15450
15451 // FIXME: Builtin::BI__builtin_powi
15452 // FIXME: Builtin::BI__builtin_powif
15453 // FIXME: Builtin::BI__builtin_powil
15454
15455 case Builtin::BI__builtin_copysign:
15456 case Builtin::BI__builtin_copysignf:
15457 case Builtin::BI__builtin_copysignl:
15458 case Builtin::BI__builtin_copysignf128: {
15459 APFloat RHS(0.);
15460 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15461 !EvaluateFloat(E->getArg(1), RHS, Info))
15462 return false;
15463 Result.copySign(RHS);
15464 return true;
15465 }
15466
15467 case Builtin::BI__builtin_fmax:
15468 case Builtin::BI__builtin_fmaxf:
15469 case Builtin::BI__builtin_fmaxl:
15470 case Builtin::BI__builtin_fmaxf16:
15471 case Builtin::BI__builtin_fmaxf128: {
15472 // TODO: Handle sNaN.
15473 APFloat RHS(0.);
15474 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15475 !EvaluateFloat(E->getArg(1), RHS, Info))
15476 return false;
15477 // When comparing zeroes, return +0.0 if one of the zeroes is positive.
15478 if (Result.isZero() && RHS.isZero() && Result.isNegative())
15479 Result = RHS;
15480 else if (Result.isNaN() || RHS > Result)
15481 Result = RHS;
15482 return true;
15483 }
15484
15485 case Builtin::BI__builtin_fmin:
15486 case Builtin::BI__builtin_fminf:
15487 case Builtin::BI__builtin_fminl:
15488 case Builtin::BI__builtin_fminf16:
15489 case Builtin::BI__builtin_fminf128: {
15490 // TODO: Handle sNaN.
15491 APFloat RHS(0.);
15492 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15493 !EvaluateFloat(E->getArg(1), RHS, Info))
15494 return false;
15495 // When comparing zeroes, return -0.0 if one of the zeroes is negative.
15496 if (Result.isZero() && RHS.isZero() && RHS.isNegative())
15497 Result = RHS;
15498 else if (Result.isNaN() || RHS < Result)
15499 Result = RHS;
15500 return true;
15501 }
15502
15503 case Builtin::BI__builtin_fmaximum_num:
15504 case Builtin::BI__builtin_fmaximum_numf:
15505 case Builtin::BI__builtin_fmaximum_numl:
15506 case Builtin::BI__builtin_fmaximum_numf16:
15507 case Builtin::BI__builtin_fmaximum_numf128: {
15508 APFloat RHS(0.);
15509 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15510 !EvaluateFloat(E->getArg(1), RHS, Info))
15511 return false;
15512 Result = maximumnum(Result, RHS);
15513 return true;
15514 }
15515
15516 case Builtin::BI__builtin_fminimum_num:
15517 case Builtin::BI__builtin_fminimum_numf:
15518 case Builtin::BI__builtin_fminimum_numl:
15519 case Builtin::BI__builtin_fminimum_numf16:
15520 case Builtin::BI__builtin_fminimum_numf128: {
15521 APFloat RHS(0.);
15522 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15523 !EvaluateFloat(E->getArg(1), RHS, Info))
15524 return false;
15525 Result = minimumnum(Result, RHS);
15526 return true;
15527 }
15528 }
15529}
15530
15531bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
15532 if (E->getSubExpr()->getType()->isAnyComplexType()) {
15533 ComplexValue CV;
15534 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
15535 return false;
15536 Result = CV.FloatReal;
15537 return true;
15538 }
15539
15540 return Visit(E->getSubExpr());
15541}
15542
15543bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
15544 if (E->getSubExpr()->getType()->isAnyComplexType()) {
15545 ComplexValue CV;
15546 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
15547 return false;
15548 Result = CV.FloatImag;
15549 return true;
15550 }
15551
15552 VisitIgnoredValue(E->getSubExpr());
15553 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
15554 Result = llvm::APFloat::getZero(Sem);
15555 return true;
15556}
15557
15558bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15559 switch (E->getOpcode()) {
15560 default: return Error(E);
15561 case UO_Plus:
15562 return EvaluateFloat(E->getSubExpr(), Result, Info);
15563 case UO_Minus:
15564 // In C standard, WG14 N2478 F.3 p4
15565 // "the unary - raises no floating point exceptions,
15566 // even if the operand is signalling."
15567 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
15568 return false;
15569 Result.changeSign();
15570 return true;
15571 }
15572}
15573
15574bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15575 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15576 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15577
15578 APFloat RHS(0.0);
15579 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
15580 if (!LHSOK && !Info.noteFailure())
15581 return false;
15582 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
15583 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
15584}
15585
15586bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
15587 Result = E->getValue();
15588 return true;
15589}
15590
15591bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
15592 const Expr* SubExpr = E->getSubExpr();
15593
15594 switch (E->getCastKind()) {
15595 default:
15596 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15597
15598 case CK_IntegralToFloating: {
15599 APSInt IntResult;
15600 const FPOptions FPO = E->getFPFeaturesInEffect(
15601 Info.Ctx.getLangOpts());
15602 return EvaluateInteger(SubExpr, IntResult, Info) &&
15603 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
15604 IntResult, E->getType(), Result);
15605 }
15606
15607 case CK_FixedPointToFloating: {
15608 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
15609 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
15610 return false;
15611 Result =
15612 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
15613 return true;
15614 }
15615
15616 case CK_FloatingCast: {
15617 if (!Visit(SubExpr))
15618 return false;
15619 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
15620 Result);
15621 }
15622
15623 case CK_FloatingComplexToReal: {
15624 ComplexValue V;
15625 if (!EvaluateComplex(SubExpr, V, Info))
15626 return false;
15627 Result = V.getComplexFloatReal();
15628 return true;
15629 }
15630 case CK_HLSLVectorTruncation: {
15631 APValue Val;
15632 if (!EvaluateVector(SubExpr, Val, Info))
15633 return Error(E);
15634 return Success(Val.getVectorElt(0), E);
15635 }
15636 }
15637}
15638
15639//===----------------------------------------------------------------------===//
15640// Complex Evaluation (for float and integer)
15641//===----------------------------------------------------------------------===//
15642
15643namespace {
15644class ComplexExprEvaluator
15645 : public ExprEvaluatorBase<ComplexExprEvaluator> {
15646 ComplexValue &Result;
15647
15648public:
15649 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
15650 : ExprEvaluatorBaseTy(info), Result(Result) {}
15651
15652 bool Success(const APValue &V, const Expr *e) {
15653 Result.setFrom(V);
15654 return true;
15655 }
15656
15657 bool ZeroInitialization(const Expr *E);
15658
15659 //===--------------------------------------------------------------------===//
15660 // Visitor Methods
15661 //===--------------------------------------------------------------------===//
15662
15663 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
15664 bool VisitCastExpr(const CastExpr *E);
15665 bool VisitBinaryOperator(const BinaryOperator *E);
15666 bool VisitUnaryOperator(const UnaryOperator *E);
15667 bool VisitInitListExpr(const InitListExpr *E);
15668 bool VisitCallExpr(const CallExpr *E);
15669};
15670} // end anonymous namespace
15671
15672static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
15673 EvalInfo &Info) {
15674 assert(!E->isValueDependent());
15675 assert(E->isPRValue() && E->getType()->isAnyComplexType());
15676 return ComplexExprEvaluator(Info, Result).Visit(E);
15677}
15678
15679bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
15680 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
15681 if (ElemTy->isRealFloatingType()) {
15682 Result.makeComplexFloat();
15683 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
15684 Result.FloatReal = Zero;
15685 Result.FloatImag = Zero;
15686 } else {
15687 Result.makeComplexInt();
15688 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
15689 Result.IntReal = Zero;
15690 Result.IntImag = Zero;
15691 }
15692 return true;
15693}
15694
15695bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
15696 const Expr* SubExpr = E->getSubExpr();
15697
15698 if (SubExpr->getType()->isRealFloatingType()) {
15699 Result.makeComplexFloat();
15700 APFloat &Imag = Result.FloatImag;
15701 if (!EvaluateFloat(SubExpr, Imag, Info))
15702 return false;
15703
15704 Result.FloatReal = APFloat(Imag.getSemantics());
15705 return true;
15706 } else {
15707 assert(SubExpr->getType()->isIntegerType() &&
15708 "Unexpected imaginary literal.");
15709
15710 Result.makeComplexInt();
15711 APSInt &Imag = Result.IntImag;
15712 if (!EvaluateInteger(SubExpr, Imag, Info))
15713 return false;
15714
15715 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
15716 return true;
15717 }
15718}
15719
15720bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
15721
15722 switch (E->getCastKind()) {
15723 case CK_BitCast:
15724 case CK_BaseToDerived:
15725 case CK_DerivedToBase:
15726 case CK_UncheckedDerivedToBase:
15727 case CK_Dynamic:
15728 case CK_ToUnion:
15729 case CK_ArrayToPointerDecay:
15730 case CK_FunctionToPointerDecay:
15731 case CK_NullToPointer:
15732 case CK_NullToMemberPointer:
15733 case CK_BaseToDerivedMemberPointer:
15734 case CK_DerivedToBaseMemberPointer:
15735 case CK_MemberPointerToBoolean:
15736 case CK_ReinterpretMemberPointer:
15737 case CK_ConstructorConversion:
15738 case CK_IntegralToPointer:
15739 case CK_PointerToIntegral:
15740 case CK_PointerToBoolean:
15741 case CK_ToVoid:
15742 case CK_VectorSplat:
15743 case CK_IntegralCast:
15744 case CK_BooleanToSignedIntegral:
15745 case CK_IntegralToBoolean:
15746 case CK_IntegralToFloating:
15747 case CK_FloatingToIntegral:
15748 case CK_FloatingToBoolean:
15749 case CK_FloatingCast:
15750 case CK_CPointerToObjCPointerCast:
15751 case CK_BlockPointerToObjCPointerCast:
15752 case CK_AnyPointerToBlockPointerCast:
15753 case CK_ObjCObjectLValueCast:
15754 case CK_FloatingComplexToReal:
15755 case CK_FloatingComplexToBoolean:
15756 case CK_IntegralComplexToReal:
15757 case CK_IntegralComplexToBoolean:
15758 case CK_ARCProduceObject:
15759 case CK_ARCConsumeObject:
15760 case CK_ARCReclaimReturnedObject:
15761 case CK_ARCExtendBlockObject:
15762 case CK_CopyAndAutoreleaseBlockObject:
15763 case CK_BuiltinFnToFnPtr:
15764 case CK_ZeroToOCLOpaqueType:
15765 case CK_NonAtomicToAtomic:
15766 case CK_AddressSpaceConversion:
15767 case CK_IntToOCLSampler:
15768 case CK_FloatingToFixedPoint:
15769 case CK_FixedPointToFloating:
15770 case CK_FixedPointCast:
15771 case CK_FixedPointToBoolean:
15772 case CK_FixedPointToIntegral:
15773 case CK_IntegralToFixedPoint:
15774 case CK_MatrixCast:
15775 case CK_HLSLVectorTruncation:
15776 llvm_unreachable("invalid cast kind for complex value");
15777
15778 case CK_LValueToRValue:
15779 case CK_AtomicToNonAtomic:
15780 case CK_NoOp:
15781 case CK_LValueToRValueBitCast:
15782 case CK_HLSLArrayRValue:
15783 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15784
15785 case CK_Dependent:
15786 case CK_LValueBitCast:
15787 case CK_UserDefinedConversion:
15788 return Error(E);
15789
15790 case CK_FloatingRealToComplex: {
15791 APFloat &Real = Result.FloatReal;
15792 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
15793 return false;
15794
15795 Result.makeComplexFloat();
15796 Result.FloatImag = APFloat(Real.getSemantics());
15797 return true;
15798 }
15799
15800 case CK_FloatingComplexCast: {
15801 if (!Visit(E->getSubExpr()))
15802 return false;
15803
15804 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15805 QualType From
15806 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15807
15808 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
15809 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
15810 }
15811
15812 case CK_FloatingComplexToIntegralComplex: {
15813 if (!Visit(E->getSubExpr()))
15814 return false;
15815
15816 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15817 QualType From
15818 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15819 Result.makeComplexInt();
15820 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
15821 To, Result.IntReal) &&
15822 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
15823 To, Result.IntImag);
15824 }
15825
15826 case CK_IntegralRealToComplex: {
15827 APSInt &Real = Result.IntReal;
15828 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
15829 return false;
15830
15831 Result.makeComplexInt();
15832 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
15833 return true;
15834 }
15835
15836 case CK_IntegralComplexCast: {
15837 if (!Visit(E->getSubExpr()))
15838 return false;
15839
15840 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15841 QualType From
15842 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15843
15844 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
15845 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
15846 return true;
15847 }
15848
15849 case CK_IntegralComplexToFloatingComplex: {
15850 if (!Visit(E->getSubExpr()))
15851 return false;
15852
15853 const FPOptions FPO = E->getFPFeaturesInEffect(
15854 Info.Ctx.getLangOpts());
15855 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15856 QualType From
15857 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15858 Result.makeComplexFloat();
15859 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
15860 To, Result.FloatReal) &&
15861 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
15862 To, Result.FloatImag);
15863 }
15864 }
15865
15866 llvm_unreachable("unknown cast resulting in complex value");
15867}
15868
15869void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
15870 APFloat &ResR, APFloat &ResI) {
15871 // This is an implementation of complex multiplication according to the
15872 // constraints laid out in C11 Annex G. The implementation uses the
15873 // following naming scheme:
15874 // (a + ib) * (c + id)
15875
15876 APFloat AC = A * C;
15877 APFloat BD = B * D;
15878 APFloat AD = A * D;
15879 APFloat BC = B * C;
15880 ResR = AC - BD;
15881 ResI = AD + BC;
15882 if (ResR.isNaN() && ResI.isNaN()) {
15883 bool Recalc = false;
15884 if (A.isInfinity() || B.isInfinity()) {
15885 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
15886 A);
15887 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
15888 B);
15889 if (C.isNaN())
15890 C = APFloat::copySign(APFloat(C.getSemantics()), C);
15891 if (D.isNaN())
15892 D = APFloat::copySign(APFloat(D.getSemantics()), D);
15893 Recalc = true;
15894 }
15895 if (C.isInfinity() || D.isInfinity()) {
15896 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
15897 C);
15898 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
15899 D);
15900 if (A.isNaN())
15901 A = APFloat::copySign(APFloat(A.getSemantics()), A);
15902 if (B.isNaN())
15903 B = APFloat::copySign(APFloat(B.getSemantics()), B);
15904 Recalc = true;
15905 }
15906 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
15907 BC.isInfinity())) {
15908 if (A.isNaN())
15909 A = APFloat::copySign(APFloat(A.getSemantics()), A);
15910 if (B.isNaN())
15911 B = APFloat::copySign(APFloat(B.getSemantics()), B);
15912 if (C.isNaN())
15913 C = APFloat::copySign(APFloat(C.getSemantics()), C);
15914 if (D.isNaN())
15915 D = APFloat::copySign(APFloat(D.getSemantics()), D);
15916 Recalc = true;
15917 }
15918 if (Recalc) {
15919 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
15920 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
15921 }
15922 }
15923}
15924
15925void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
15926 APFloat &ResR, APFloat &ResI) {
15927 // This is an implementation of complex division according to the
15928 // constraints laid out in C11 Annex G. The implementation uses the
15929 // following naming scheme:
15930 // (a + ib) / (c + id)
15931
15932 int DenomLogB = 0;
15933 APFloat MaxCD = maxnum(abs(C), abs(D));
15934 if (MaxCD.isFinite()) {
15935 DenomLogB = ilogb(MaxCD);
15936 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
15937 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
15938 }
15939 APFloat Denom = C * C + D * D;
15940 ResR =
15941 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
15942 ResI =
15943 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
15944 if (ResR.isNaN() && ResI.isNaN()) {
15945 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
15946 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
15947 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
15948 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
15949 D.isFinite()) {
15950 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
15951 A);
15952 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
15953 B);
15954 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
15955 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
15956 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
15957 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
15958 C);
15959 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
15960 D);
15961 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
15962 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
15963 }
15964 }
15965}
15966
15967bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15968 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15969 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15970
15971 // Track whether the LHS or RHS is real at the type system level. When this is
15972 // the case we can simplify our evaluation strategy.
15973 bool LHSReal = false, RHSReal = false;
15974
15975 bool LHSOK;
15976 if (E->getLHS()->getType()->isRealFloatingType()) {
15977 LHSReal = true;
15978 APFloat &Real = Result.FloatReal;
15979 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
15980 if (LHSOK) {
15981 Result.makeComplexFloat();
15982 Result.FloatImag = APFloat(Real.getSemantics());
15983 }
15984 } else {
15985 LHSOK = Visit(E->getLHS());
15986 }
15987 if (!LHSOK && !Info.noteFailure())
15988 return false;
15989
15990 ComplexValue RHS;
15991 if (E->getRHS()->getType()->isRealFloatingType()) {
15992 RHSReal = true;
15993 APFloat &Real = RHS.FloatReal;
15994 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
15995 return false;
15996 RHS.makeComplexFloat();
15997 RHS.FloatImag = APFloat(Real.getSemantics());
15998 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
15999 return false;
16000
16001 assert(!(LHSReal && RHSReal) &&
16002 "Cannot have both operands of a complex operation be real.");
16003 switch (E->getOpcode()) {
16004 default: return Error(E);
16005 case BO_Add:
16006 if (Result.isComplexFloat()) {
16007 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
16008 APFloat::rmNearestTiesToEven);
16009 if (LHSReal)
16010 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
16011 else if (!RHSReal)
16012 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
16013 APFloat::rmNearestTiesToEven);
16014 } else {
16015 Result.getComplexIntReal() += RHS.getComplexIntReal();
16016 Result.getComplexIntImag() += RHS.getComplexIntImag();
16017 }
16018 break;
16019 case BO_Sub:
16020 if (Result.isComplexFloat()) {
16021 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
16022 APFloat::rmNearestTiesToEven);
16023 if (LHSReal) {
16024 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
16025 Result.getComplexFloatImag().changeSign();
16026 } else if (!RHSReal) {
16027 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
16028 APFloat::rmNearestTiesToEven);
16029 }
16030 } else {
16031 Result.getComplexIntReal() -= RHS.getComplexIntReal();
16032 Result.getComplexIntImag() -= RHS.getComplexIntImag();
16033 }
16034 break;
16035 case BO_Mul:
16036 if (Result.isComplexFloat()) {
16037 // This is an implementation of complex multiplication according to the
16038 // constraints laid out in C11 Annex G. The implementation uses the
16039 // following naming scheme:
16040 // (a + ib) * (c + id)
16041 ComplexValue LHS = Result;
16042 APFloat &A = LHS.getComplexFloatReal();
16043 APFloat &B = LHS.getComplexFloatImag();
16044 APFloat &C = RHS.getComplexFloatReal();
16045 APFloat &D = RHS.getComplexFloatImag();
16046 APFloat &ResR = Result.getComplexFloatReal();
16047 APFloat &ResI = Result.getComplexFloatImag();
16048 if (LHSReal) {
16049 assert(!RHSReal && "Cannot have two real operands for a complex op!");
16050 ResR = A;
16051 ResI = A;
16052 // ResR = A * C;
16053 // ResI = A * D;
16054 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
16055 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
16056 return false;
16057 } else if (RHSReal) {
16058 // ResR = C * A;
16059 // ResI = C * B;
16060 ResR = C;
16061 ResI = C;
16062 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
16063 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
16064 return false;
16065 } else {
16066 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
16067 }
16068 } else {
16069 ComplexValue LHS = Result;
16070 Result.getComplexIntReal() =
16071 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
16072 LHS.getComplexIntImag() * RHS.getComplexIntImag());
16073 Result.getComplexIntImag() =
16074 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
16075 LHS.getComplexIntImag() * RHS.getComplexIntReal());
16076 }
16077 break;
16078 case BO_Div:
16079 if (Result.isComplexFloat()) {
16080 // This is an implementation of complex division according to the
16081 // constraints laid out in C11 Annex G. The implementation uses the
16082 // following naming scheme:
16083 // (a + ib) / (c + id)
16084 ComplexValue LHS = Result;
16085 APFloat &A = LHS.getComplexFloatReal();
16086 APFloat &B = LHS.getComplexFloatImag();
16087 APFloat &C = RHS.getComplexFloatReal();
16088 APFloat &D = RHS.getComplexFloatImag();
16089 APFloat &ResR = Result.getComplexFloatReal();
16090 APFloat &ResI = Result.getComplexFloatImag();
16091 if (RHSReal) {
16092 ResR = A;
16093 ResI = B;
16094 // ResR = A / C;
16095 // ResI = B / C;
16096 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
16097 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
16098 return false;
16099 } else {
16100 if (LHSReal) {
16101 // No real optimizations we can do here, stub out with zero.
16102 B = APFloat::getZero(A.getSemantics());
16103 }
16104 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
16105 }
16106 } else {
16107 ComplexValue LHS = Result;
16108 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
16109 RHS.getComplexIntImag() * RHS.getComplexIntImag();
16110 if (Den.isZero())
16111 return Error(E, diag::note_expr_divide_by_zero);
16112
16113 Result.getComplexIntReal() =
16114 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
16115 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
16116 Result.getComplexIntImag() =
16117 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
16118 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
16119 }
16120 break;
16121 }
16122
16123 return true;
16124}
16125
16126bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
16127 // Get the operand value into 'Result'.
16128 if (!Visit(E->getSubExpr()))
16129 return false;
16130
16131 switch (E->getOpcode()) {
16132 default:
16133 return Error(E);
16134 case UO_Extension:
16135 return true;
16136 case UO_Plus:
16137 // The result is always just the subexpr.
16138 return true;
16139 case UO_Minus:
16140 if (Result.isComplexFloat()) {
16141 Result.getComplexFloatReal().changeSign();
16142 Result.getComplexFloatImag().changeSign();
16143 }
16144 else {
16145 Result.getComplexIntReal() = -Result.getComplexIntReal();
16146 Result.getComplexIntImag() = -Result.getComplexIntImag();
16147 }
16148 return true;
16149 case UO_Not:
16150 if (Result.isComplexFloat())
16151 Result.getComplexFloatImag().changeSign();
16152 else
16153 Result.getComplexIntImag() = -Result.getComplexIntImag();
16154 return true;
16155 }
16156}
16157
16158bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
16159 if (E->getNumInits() == 2) {
16160 if (E->getType()->isComplexType()) {
16161 Result.makeComplexFloat();
16162 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
16163 return false;
16164 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
16165 return false;
16166 } else {
16167 Result.makeComplexInt();
16168 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
16169 return false;
16170 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
16171 return false;
16172 }
16173 return true;
16174 }
16175 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
16176}
16177
16178bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
16179 if (!IsConstantEvaluatedBuiltinCall(E))
16180 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16181
16182 switch (E->getBuiltinCallee()) {
16183 case Builtin::BI__builtin_complex:
16184 Result.makeComplexFloat();
16185 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
16186 return false;
16187 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
16188 return false;
16189 return true;
16190
16191 default:
16192 return false;
16193 }
16194}
16195
16196//===----------------------------------------------------------------------===//
16197// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
16198// implicit conversion.
16199//===----------------------------------------------------------------------===//
16200
16201namespace {
16202class AtomicExprEvaluator :
16203 public ExprEvaluatorBase<AtomicExprEvaluator> {
16204 const LValue *This;
16205 APValue &Result;
16206public:
16207 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
16208 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
16209
16210 bool Success(const APValue &V, const Expr *E) {
16211 Result = V;
16212 return true;
16213 }
16214
16215 bool ZeroInitialization(const Expr *E) {
16218 // For atomic-qualified class (and array) types in C++, initialize the
16219 // _Atomic-wrapped subobject directly, in-place.
16220 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
16221 : Evaluate(Result, Info, &VIE);
16222 }
16223
16224 bool VisitCastExpr(const CastExpr *E) {
16225 switch (E->getCastKind()) {
16226 default:
16227 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16228 case CK_NullToPointer:
16229 VisitIgnoredValue(E->getSubExpr());
16230 return ZeroInitialization(E);
16231 case CK_NonAtomicToAtomic:
16232 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
16233 : Evaluate(Result, Info, E->getSubExpr());
16234 }
16235 }
16236};
16237} // end anonymous namespace
16238
16239static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
16240 EvalInfo &Info) {
16241 assert(!E->isValueDependent());
16242 assert(E->isPRValue() && E->getType()->isAtomicType());
16243 return AtomicExprEvaluator(Info, This, Result).Visit(E);
16244}
16245
16246//===----------------------------------------------------------------------===//
16247// Void expression evaluation, primarily for a cast to void on the LHS of a
16248// comma operator
16249//===----------------------------------------------------------------------===//
16250
16251namespace {
16252class VoidExprEvaluator
16253 : public ExprEvaluatorBase<VoidExprEvaluator> {
16254public:
16255 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
16256
16257 bool Success(const APValue &V, const Expr *e) { return true; }
16258
16259 bool ZeroInitialization(const Expr *E) { return true; }
16260
16261 bool VisitCastExpr(const CastExpr *E) {
16262 switch (E->getCastKind()) {
16263 default:
16264 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16265 case CK_ToVoid:
16266 VisitIgnoredValue(E->getSubExpr());
16267 return true;
16268 }
16269 }
16270
16271 bool VisitCallExpr(const CallExpr *E) {
16272 if (!IsConstantEvaluatedBuiltinCall(E))
16273 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16274
16275 switch (E->getBuiltinCallee()) {
16276 case Builtin::BI__assume:
16277 case Builtin::BI__builtin_assume:
16278 // The argument is not evaluated!
16279 return true;
16280
16281 case Builtin::BI__builtin_operator_delete:
16282 return HandleOperatorDeleteCall(Info, E);
16283
16284 default:
16285 return false;
16286 }
16287 }
16288
16289 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
16290};
16291} // end anonymous namespace
16292
16293bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
16294 // We cannot speculatively evaluate a delete expression.
16295 if (Info.SpeculativeEvaluationDepth)
16296 return false;
16297
16298 FunctionDecl *OperatorDelete = E->getOperatorDelete();
16299 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
16300 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
16301 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
16302 return false;
16303 }
16304
16305 const Expr *Arg = E->getArgument();
16306
16307 LValue Pointer;
16308 if (!EvaluatePointer(Arg, Pointer, Info))
16309 return false;
16310 if (Pointer.Designator.Invalid)
16311 return false;
16312
16313 // Deleting a null pointer has no effect.
16314 if (Pointer.isNullPointer()) {
16315 // This is the only case where we need to produce an extension warning:
16316 // the only other way we can succeed is if we find a dynamic allocation,
16317 // and we will have warned when we allocated it in that case.
16318 if (!Info.getLangOpts().CPlusPlus20)
16319 Info.CCEDiag(E, diag::note_constexpr_new);
16320 return true;
16321 }
16322
16323 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
16324 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
16325 if (!Alloc)
16326 return false;
16327 QualType AllocType = Pointer.Base.getDynamicAllocType();
16328
16329 // For the non-array case, the designator must be empty if the static type
16330 // does not have a virtual destructor.
16331 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
16333 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
16334 << Arg->getType()->getPointeeType() << AllocType;
16335 return false;
16336 }
16337
16338 // For a class type with a virtual destructor, the selected operator delete
16339 // is the one looked up when building the destructor.
16340 if (!E->isArrayForm() && !E->isGlobalDelete()) {
16341 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
16342 if (VirtualDelete &&
16343 !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
16344 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
16345 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
16346 return false;
16347 }
16348 }
16349
16350 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
16351 (*Alloc)->Value, AllocType))
16352 return false;
16353
16354 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
16355 // The element was already erased. This means the destructor call also
16356 // deleted the object.
16357 // FIXME: This probably results in undefined behavior before we get this
16358 // far, and should be diagnosed elsewhere first.
16359 Info.FFDiag(E, diag::note_constexpr_double_delete);
16360 return false;
16361 }
16362
16363 return true;
16364}
16365
16366static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
16367 assert(!E->isValueDependent());
16368 assert(E->isPRValue() && E->getType()->isVoidType());
16369 return VoidExprEvaluator(Info).Visit(E);
16370}
16371
16372//===----------------------------------------------------------------------===//
16373// Top level Expr::EvaluateAsRValue method.
16374//===----------------------------------------------------------------------===//
16375
16376static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
16377 assert(!E->isValueDependent());
16378 // In C, function designators are not lvalues, but we evaluate them as if they
16379 // are.
16380 QualType T = E->getType();
16381 if (E->isGLValue() || T->isFunctionType()) {
16382 LValue LV;
16383 if (!EvaluateLValue(E, LV, Info))
16384 return false;
16385 LV.moveInto(Result);
16386 } else if (T->isVectorType()) {
16387 if (!EvaluateVector(E, Result, Info))
16388 return false;
16389 } else if (T->isIntegralOrEnumerationType()) {
16390 if (!IntExprEvaluator(Info, Result).Visit(E))
16391 return false;
16392 } else if (T->hasPointerRepresentation()) {
16393 LValue LV;
16394 if (!EvaluatePointer(E, LV, Info))
16395 return false;
16396 LV.moveInto(Result);
16397 } else if (T->isRealFloatingType()) {
16398 llvm::APFloat F(0.0);
16399 if (!EvaluateFloat(E, F, Info))
16400 return false;
16401 Result = APValue(F);
16402 } else if (T->isAnyComplexType()) {
16403 ComplexValue C;
16404 if (!EvaluateComplex(E, C, Info))
16405 return false;
16406 C.moveInto(Result);
16407 } else if (T->isFixedPointType()) {
16408 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
16409 } else if (T->isMemberPointerType()) {
16410 MemberPtr P;
16411 if (!EvaluateMemberPointer(E, P, Info))
16412 return false;
16413 P.moveInto(Result);
16414 return true;
16415 } else if (T->isArrayType()) {
16416 LValue LV;
16417 APValue &Value =
16418 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
16419 if (!EvaluateArray(E, LV, Value, Info))
16420 return false;
16421 Result = Value;
16422 } else if (T->isRecordType()) {
16423 LValue LV;
16424 APValue &Value =
16425 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
16426 if (!EvaluateRecord(E, LV, Value, Info))
16427 return false;
16428 Result = Value;
16429 } else if (T->isVoidType()) {
16430 if (!Info.getLangOpts().CPlusPlus11)
16431 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
16432 << E->getType();
16433 if (!EvaluateVoid(E, Info))
16434 return false;
16435 } else if (T->isAtomicType()) {
16436 QualType Unqual = T.getAtomicUnqualifiedType();
16437 if (Unqual->isArrayType() || Unqual->isRecordType()) {
16438 LValue LV;
16439 APValue &Value = Info.CurrentCall->createTemporary(
16440 E, Unqual, ScopeKind::FullExpression, LV);
16441 if (!EvaluateAtomic(E, &LV, Value, Info))
16442 return false;
16443 Result = Value;
16444 } else {
16445 if (!EvaluateAtomic(E, nullptr, Result, Info))
16446 return false;
16447 }
16448 } else if (Info.getLangOpts().CPlusPlus11) {
16449 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
16450 return false;
16451 } else {
16452 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16453 return false;
16454 }
16455
16456 return true;
16457}
16458
16459/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
16460/// cases, the in-place evaluation is essential, since later initializers for
16461/// an object can indirectly refer to subobjects which were initialized earlier.
16462static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
16463 const Expr *E, bool AllowNonLiteralTypes) {
16464 assert(!E->isValueDependent());
16465
16466 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
16467 return false;
16468
16469 if (E->isPRValue()) {
16470 // Evaluate arrays and record types in-place, so that later initializers can
16471 // refer to earlier-initialized members of the object.
16472 QualType T = E->getType();
16473 if (T->isArrayType())
16474 return EvaluateArray(E, This, Result, Info);
16475 else if (T->isRecordType())
16476 return EvaluateRecord(E, This, Result, Info);
16477 else if (T->isAtomicType()) {
16478 QualType Unqual = T.getAtomicUnqualifiedType();
16479 if (Unqual->isArrayType() || Unqual->isRecordType())
16480 return EvaluateAtomic(E, &This, Result, Info);
16481 }
16482 }
16483
16484 // For any other type, in-place evaluation is unimportant.
16485 return Evaluate(Result, Info, E);
16486}
16487
16488/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
16489/// lvalue-to-rvalue cast if it is an lvalue.
16490static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
16491 assert(!E->isValueDependent());
16492
16493 if (E->getType().isNull())
16494 return false;
16495
16496 if (!CheckLiteralType(Info, E))
16497 return false;
16498
16499 if (Info.EnableNewConstInterp) {
16500 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
16501 return false;
16502 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
16503 ConstantExprKind::Normal);
16504 }
16505
16506 if (!::Evaluate(Result, Info, E))
16507 return false;
16508
16509 // Implicit lvalue-to-rvalue cast.
16510 if (E->isGLValue()) {
16511 LValue LV;
16512 LV.setFrom(Info.Ctx, Result);
16513 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
16514 return false;
16515 }
16516
16517 // Check this core constant expression is a constant expression.
16518 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
16519 ConstantExprKind::Normal) &&
16520 CheckMemoryLeaks(Info);
16521}
16522
16523static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
16524 const ASTContext &Ctx, bool &IsConst) {
16525 // Fast-path evaluations of integer literals, since we sometimes see files
16526 // containing vast quantities of these.
16527 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
16528 Result.Val = APValue(APSInt(L->getValue(),
16529 L->getType()->isUnsignedIntegerType()));
16530 IsConst = true;
16531 return true;
16532 }
16533
16534 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
16535 Result.Val = APValue(APSInt(APInt(1, L->getValue())));
16536 IsConst = true;
16537 return true;
16538 }
16539
16540 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
16541 Result.Val = APValue(FL->getValue());
16542 IsConst = true;
16543 return true;
16544 }
16545
16546 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
16547 Result.Val = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
16548 IsConst = true;
16549 return true;
16550 }
16551
16552 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
16553 if (CE->hasAPValueResult()) {
16554 APValue APV = CE->getAPValueResult();
16555 if (!APV.isLValue()) {
16556 Result.Val = std::move(APV);
16557 IsConst = true;
16558 return true;
16559 }
16560 }
16561
16562 // The SubExpr is usually just an IntegerLiteral.
16563 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
16564 }
16565
16566 // This case should be rare, but we need to check it before we check on
16567 // the type below.
16568 if (Exp->getType().isNull()) {
16569 IsConst = false;
16570 return true;
16571 }
16572
16573 return false;
16574}
16575
16578 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
16579 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
16580}
16581
16582static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
16583 const ASTContext &Ctx, EvalInfo &Info) {
16584 assert(!E->isValueDependent());
16585 bool IsConst;
16586 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
16587 return IsConst;
16588
16589 return EvaluateAsRValue(Info, E, Result.Val);
16590}
16591
16593 const ASTContext &Ctx,
16594 Expr::SideEffectsKind AllowSideEffects,
16595 EvalInfo &Info) {
16596 assert(!E->isValueDependent());
16598 return false;
16599
16600 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
16601 !ExprResult.Val.isInt() ||
16602 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16603 return false;
16604
16605 return true;
16606}
16607
16609 const ASTContext &Ctx,
16610 Expr::SideEffectsKind AllowSideEffects,
16611 EvalInfo &Info) {
16612 assert(!E->isValueDependent());
16613 if (!E->getType()->isFixedPointType())
16614 return false;
16615
16616 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
16617 return false;
16618
16619 if (!ExprResult.Val.isFixedPoint() ||
16620 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16621 return false;
16622
16623 return true;
16624}
16625
16626/// EvaluateAsRValue - Return true if this is a constant which we can fold using
16627/// any crazy technique (that has nothing to do with language standards) that
16628/// we want to. If this function returns true, it returns the folded constant
16629/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
16630/// will be applied to the result.
16632 bool InConstantContext) const {
16633 assert(!isValueDependent() &&
16634 "Expression evaluator can't be called on a dependent expression.");
16635 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
16636 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16637 Info.InConstantContext = InConstantContext;
16638 return ::EvaluateAsRValue(this, Result, Ctx, Info);
16639}
16640
16641bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
16642 bool InConstantContext) const {
16643 assert(!isValueDependent() &&
16644 "Expression evaluator can't be called on a dependent expression.");
16645 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
16646 EvalResult Scratch;
16647 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
16648 HandleConversionToBool(Scratch.Val, Result);
16649}
16650
16652 SideEffectsKind AllowSideEffects,
16653 bool InConstantContext) const {
16654 assert(!isValueDependent() &&
16655 "Expression evaluator can't be called on a dependent expression.");
16656 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
16657 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16658 Info.InConstantContext = InConstantContext;
16659 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
16660}
16661
16663 SideEffectsKind AllowSideEffects,
16664 bool InConstantContext) const {
16665 assert(!isValueDependent() &&
16666 "Expression evaluator can't be called on a dependent expression.");
16667 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
16668 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16669 Info.InConstantContext = InConstantContext;
16670 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
16671}
16672
16673bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
16674 SideEffectsKind AllowSideEffects,
16675 bool InConstantContext) const {
16676 assert(!isValueDependent() &&
16677 "Expression evaluator can't be called on a dependent expression.");
16678
16679 if (!getType()->isRealFloatingType())
16680 return false;
16681
16682 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
16684 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
16685 !ExprResult.Val.isFloat() ||
16686 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16687 return false;
16688
16689 Result = ExprResult.Val.getFloat();
16690 return true;
16691}
16692
16694 bool InConstantContext) const {
16695 assert(!isValueDependent() &&
16696 "Expression evaluator can't be called on a dependent expression.");
16697
16698 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
16699 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
16700 Info.InConstantContext = InConstantContext;
16701 LValue LV;
16702 CheckedTemporaries CheckedTemps;
16703 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
16704 Result.HasSideEffects ||
16705 !CheckLValueConstantExpression(Info, getExprLoc(),
16706 Ctx.getLValueReferenceType(getType()), LV,
16707 ConstantExprKind::Normal, CheckedTemps))
16708 return false;
16709
16710 LV.moveInto(Result.Val);
16711 return true;
16712}
16713
16715 APValue DestroyedValue, QualType Type,
16717 bool IsConstantDestruction) {
16718 EvalInfo Info(Ctx, EStatus,
16719 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
16720 : EvalInfo::EM_ConstantFold);
16721 Info.setEvaluatingDecl(Base, DestroyedValue,
16722 EvalInfo::EvaluatingDeclKind::Dtor);
16723 Info.InConstantContext = IsConstantDestruction;
16724
16725 LValue LVal;
16726 LVal.set(Base);
16727
16728 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
16729 EStatus.HasSideEffects)
16730 return false;
16731
16732 if (!Info.discardCleanups())
16733 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16734
16735 return true;
16736}
16737
16739 ConstantExprKind Kind) const {
16740 assert(!isValueDependent() &&
16741 "Expression evaluator can't be called on a dependent expression.");
16742 bool IsConst;
16743 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue())
16744 return true;
16745
16746 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
16747 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
16748 EvalInfo Info(Ctx, Result, EM);
16749 Info.InConstantContext = true;
16750
16751 if (Info.EnableNewConstInterp) {
16752 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
16753 return false;
16754 return CheckConstantExpression(Info, getExprLoc(),
16755 getStorageType(Ctx, this), Result.Val, Kind);
16756 }
16757
16758 // The type of the object we're initializing is 'const T' for a class NTTP.
16759 QualType T = getType();
16760 if (Kind == ConstantExprKind::ClassTemplateArgument)
16761 T.addConst();
16762
16763 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
16764 // represent the result of the evaluation. CheckConstantExpression ensures
16765 // this doesn't escape.
16766 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
16767 APValue::LValueBase Base(&BaseMTE);
16768 Info.setEvaluatingDecl(Base, Result.Val);
16769
16770 if (Info.EnableNewConstInterp) {
16771 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, this, Result.Val))
16772 return false;
16773 } else {
16774 LValue LVal;
16775 LVal.set(Base);
16776 // C++23 [intro.execution]/p5
16777 // A full-expression is [...] a constant-expression
16778 // So we need to make sure temporary objects are destroyed after having
16779 // evaluating the expression (per C++23 [class.temporary]/p4).
16780 FullExpressionRAII Scope(Info);
16781 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
16782 Result.HasSideEffects || !Scope.destroy())
16783 return false;
16784
16785 if (!Info.discardCleanups())
16786 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16787 }
16788
16789 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
16790 Result.Val, Kind))
16791 return false;
16792 if (!CheckMemoryLeaks(Info))
16793 return false;
16794
16795 // If this is a class template argument, it's required to have constant
16796 // destruction too.
16797 if (Kind == ConstantExprKind::ClassTemplateArgument &&
16798 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
16799 true) ||
16800 Result.HasSideEffects)) {
16801 // FIXME: Prefix a note to indicate that the problem is lack of constant
16802 // destruction.
16803 return false;
16804 }
16805
16806 return true;
16807}
16808
16810 const VarDecl *VD,
16812 bool IsConstantInitialization) const {
16813 assert(!isValueDependent() &&
16814 "Expression evaluator can't be called on a dependent expression.");
16815
16816 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
16817 std::string Name;
16818 llvm::raw_string_ostream OS(Name);
16819 VD->printQualifiedName(OS);
16820 return Name;
16821 });
16822
16823 Expr::EvalStatus EStatus;
16824 EStatus.Diag = &Notes;
16825
16826 EvalInfo Info(Ctx, EStatus,
16827 (IsConstantInitialization &&
16828 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
16829 ? EvalInfo::EM_ConstantExpression
16830 : EvalInfo::EM_ConstantFold);
16831 Info.setEvaluatingDecl(VD, Value);
16832 Info.InConstantContext = IsConstantInitialization;
16833
16834 SourceLocation DeclLoc = VD->getLocation();
16835 QualType DeclTy = VD->getType();
16836
16837 if (Info.EnableNewConstInterp) {
16838 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
16839 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
16840 return false;
16841
16842 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
16843 ConstantExprKind::Normal);
16844 } else {
16845 LValue LVal;
16846 LVal.set(VD);
16847
16848 {
16849 // C++23 [intro.execution]/p5
16850 // A full-expression is ... an init-declarator ([dcl.decl]) or a
16851 // mem-initializer.
16852 // So we need to make sure temporary objects are destroyed after having
16853 // evaluated the expression (per C++23 [class.temporary]/p4).
16854 //
16855 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
16856 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
16857 // outermost FullExpr, such as ExprWithCleanups.
16858 FullExpressionRAII Scope(Info);
16859 if (!EvaluateInPlace(Value, Info, LVal, this,
16860 /*AllowNonLiteralTypes=*/true) ||
16861 EStatus.HasSideEffects)
16862 return false;
16863 }
16864
16865 // At this point, any lifetime-extended temporaries are completely
16866 // initialized.
16867 Info.performLifetimeExtension();
16868
16869 if (!Info.discardCleanups())
16870 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16871 }
16872
16873 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
16874 ConstantExprKind::Normal) &&
16875 CheckMemoryLeaks(Info);
16876}
16877
16880 Expr::EvalStatus EStatus;
16881 EStatus.Diag = &Notes;
16882
16883 // Only treat the destruction as constant destruction if we formally have
16884 // constant initialization (or are usable in a constant expression).
16885 bool IsConstantDestruction = hasConstantInitialization();
16886
16887 // Make a copy of the value for the destructor to mutate, if we know it.
16888 // Otherwise, treat the value as default-initialized; if the destructor works
16889 // anyway, then the destruction is constant (and must be essentially empty).
16890 APValue DestroyedValue;
16891 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
16892 DestroyedValue = *getEvaluatedValue();
16893 else if (!handleDefaultInitValue(getType(), DestroyedValue))
16894 return false;
16895
16896 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
16897 getType(), getLocation(), EStatus,
16898 IsConstantDestruction) ||
16899 EStatus.HasSideEffects)
16900 return false;
16901
16902 ensureEvaluatedStmt()->HasConstantDestruction = true;
16903 return true;
16904}
16905
16906/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
16907/// constant folded, but discard the result.
16909 assert(!isValueDependent() &&
16910 "Expression evaluator can't be called on a dependent expression.");
16911
16912 EvalResult Result;
16913 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
16914 !hasUnacceptableSideEffect(Result, SEK);
16915}
16916
16919 assert(!isValueDependent() &&
16920 "Expression evaluator can't be called on a dependent expression.");
16921
16922 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
16923 EvalResult EVResult;
16924 EVResult.Diag = Diag;
16925 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16926 Info.InConstantContext = true;
16927
16928 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
16929 (void)Result;
16930 assert(Result && "Could not evaluate expression");
16931 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
16932
16933 return EVResult.Val.getInt();
16934}
16935
16938 assert(!isValueDependent() &&
16939 "Expression evaluator can't be called on a dependent expression.");
16940
16941 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
16942 EvalResult EVResult;
16943 EVResult.Diag = Diag;
16944 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16945 Info.InConstantContext = true;
16946 Info.CheckingForUndefinedBehavior = true;
16947
16948 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
16949 (void)Result;
16950 assert(Result && "Could not evaluate expression");
16951 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
16952
16953 return EVResult.Val.getInt();
16954}
16955
16957 assert(!isValueDependent() &&
16958 "Expression evaluator can't be called on a dependent expression.");
16959
16960 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
16961 bool IsConst;
16962 EvalResult EVResult;
16963 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
16964 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16965 Info.CheckingForUndefinedBehavior = true;
16966 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
16967 }
16968}
16969
16971 assert(Val.isLValue());
16972 return IsGlobalLValue(Val.getLValueBase());
16973}
16974
16975/// isIntegerConstantExpr - this recursive routine will test if an expression is
16976/// an integer constant expression.
16977
16978/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
16979/// comma, etc
16980
16981// CheckICE - This function does the fundamental ICE checking: the returned
16982// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
16983// and a (possibly null) SourceLocation indicating the location of the problem.
16984//
16985// Note that to reduce code duplication, this helper does no evaluation
16986// itself; the caller checks whether the expression is evaluatable, and
16987// in the rare cases where CheckICE actually cares about the evaluated
16988// value, it calls into Evaluate.
16989
16990namespace {
16991
16992enum ICEKind {
16993 /// This expression is an ICE.
16994 IK_ICE,
16995 /// This expression is not an ICE, but if it isn't evaluated, it's
16996 /// a legal subexpression for an ICE. This return value is used to handle
16997 /// the comma operator in C99 mode, and non-constant subexpressions.
16998 IK_ICEIfUnevaluated,
16999 /// This expression is not an ICE, and is not a legal subexpression for one.
17000 IK_NotICE
17001};
17002
17003struct ICEDiag {
17004 ICEKind Kind;
17006
17007 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
17008};
17009
17010}
17011
17012static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
17013
17014static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
17015
17016static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
17017 Expr::EvalResult EVResult;
17018 Expr::EvalStatus Status;
17019 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17020
17021 Info.InConstantContext = true;
17022 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
17023 !EVResult.Val.isInt())
17024 return ICEDiag(IK_NotICE, E->getBeginLoc());
17025
17026 return NoDiag();
17027}
17028
17029static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
17030 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
17032 return ICEDiag(IK_NotICE, E->getBeginLoc());
17033
17034 switch (E->getStmtClass()) {
17035#define ABSTRACT_STMT(Node)
17036#define STMT(Node, Base) case Expr::Node##Class:
17037#define EXPR(Node, Base)
17038#include "clang/AST/StmtNodes.inc"
17039 case Expr::PredefinedExprClass:
17040 case Expr::FloatingLiteralClass:
17041 case Expr::ImaginaryLiteralClass:
17042 case Expr::StringLiteralClass:
17043 case Expr::ArraySubscriptExprClass:
17044 case Expr::MatrixSubscriptExprClass:
17045 case Expr::ArraySectionExprClass:
17046 case Expr::OMPArrayShapingExprClass:
17047 case Expr::OMPIteratorExprClass:
17048 case Expr::MemberExprClass:
17049 case Expr::CompoundAssignOperatorClass:
17050 case Expr::CompoundLiteralExprClass:
17051 case Expr::ExtVectorElementExprClass:
17052 case Expr::DesignatedInitExprClass:
17053 case Expr::ArrayInitLoopExprClass:
17054 case Expr::ArrayInitIndexExprClass:
17055 case Expr::NoInitExprClass:
17056 case Expr::DesignatedInitUpdateExprClass:
17057 case Expr::ImplicitValueInitExprClass:
17058 case Expr::ParenListExprClass:
17059 case Expr::VAArgExprClass:
17060 case Expr::AddrLabelExprClass:
17061 case Expr::StmtExprClass:
17062 case Expr::CXXMemberCallExprClass:
17063 case Expr::CUDAKernelCallExprClass:
17064 case Expr::CXXAddrspaceCastExprClass:
17065 case Expr::CXXDynamicCastExprClass:
17066 case Expr::CXXTypeidExprClass:
17067 case Expr::CXXUuidofExprClass:
17068 case Expr::MSPropertyRefExprClass:
17069 case Expr::MSPropertySubscriptExprClass:
17070 case Expr::CXXNullPtrLiteralExprClass:
17071 case Expr::UserDefinedLiteralClass:
17072 case Expr::CXXThisExprClass:
17073 case Expr::CXXThrowExprClass:
17074 case Expr::CXXNewExprClass:
17075 case Expr::CXXDeleteExprClass:
17076 case Expr::CXXPseudoDestructorExprClass:
17077 case Expr::UnresolvedLookupExprClass:
17078 case Expr::TypoExprClass:
17079 case Expr::RecoveryExprClass:
17080 case Expr::DependentScopeDeclRefExprClass:
17081 case Expr::CXXConstructExprClass:
17082 case Expr::CXXInheritedCtorInitExprClass:
17083 case Expr::CXXStdInitializerListExprClass:
17084 case Expr::CXXBindTemporaryExprClass:
17085 case Expr::ExprWithCleanupsClass:
17086 case Expr::CXXTemporaryObjectExprClass:
17087 case Expr::CXXUnresolvedConstructExprClass:
17088 case Expr::CXXDependentScopeMemberExprClass:
17089 case Expr::UnresolvedMemberExprClass:
17090 case Expr::ObjCStringLiteralClass:
17091 case Expr::ObjCBoxedExprClass:
17092 case Expr::ObjCArrayLiteralClass:
17093 case Expr::ObjCDictionaryLiteralClass:
17094 case Expr::ObjCEncodeExprClass:
17095 case Expr::ObjCMessageExprClass:
17096 case Expr::ObjCSelectorExprClass:
17097 case Expr::ObjCProtocolExprClass:
17098 case Expr::ObjCIvarRefExprClass:
17099 case Expr::ObjCPropertyRefExprClass:
17100 case Expr::ObjCSubscriptRefExprClass:
17101 case Expr::ObjCIsaExprClass:
17102 case Expr::ObjCAvailabilityCheckExprClass:
17103 case Expr::ShuffleVectorExprClass:
17104 case Expr::ConvertVectorExprClass:
17105 case Expr::BlockExprClass:
17106 case Expr::NoStmtClass:
17107 case Expr::OpaqueValueExprClass:
17108 case Expr::PackExpansionExprClass:
17109 case Expr::SubstNonTypeTemplateParmPackExprClass:
17110 case Expr::FunctionParmPackExprClass:
17111 case Expr::AsTypeExprClass:
17112 case Expr::ObjCIndirectCopyRestoreExprClass:
17113 case Expr::MaterializeTemporaryExprClass:
17114 case Expr::PseudoObjectExprClass:
17115 case Expr::AtomicExprClass:
17116 case Expr::LambdaExprClass:
17117 case Expr::CXXFoldExprClass:
17118 case Expr::CoawaitExprClass:
17119 case Expr::DependentCoawaitExprClass:
17120 case Expr::CoyieldExprClass:
17121 case Expr::SYCLUniqueStableNameExprClass:
17122 case Expr::CXXParenListInitExprClass:
17123 case Expr::HLSLOutArgExprClass:
17124 return ICEDiag(IK_NotICE, E->getBeginLoc());
17125
17126 case Expr::InitListExprClass: {
17127 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
17128 // form "T x = { a };" is equivalent to "T x = a;".
17129 // Unless we're initializing a reference, T is a scalar as it is known to be
17130 // of integral or enumeration type.
17131 if (E->isPRValue())
17132 if (cast<InitListExpr>(E)->getNumInits() == 1)
17133 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
17134 return ICEDiag(IK_NotICE, E->getBeginLoc());
17135 }
17136
17137 case Expr::SizeOfPackExprClass:
17138 case Expr::GNUNullExprClass:
17139 case Expr::SourceLocExprClass:
17140 case Expr::EmbedExprClass:
17141 case Expr::OpenACCAsteriskSizeExprClass:
17142 return NoDiag();
17143
17144 case Expr::PackIndexingExprClass:
17145 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
17146
17147 case Expr::SubstNonTypeTemplateParmExprClass:
17148 return
17149 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
17150
17151 case Expr::ConstantExprClass:
17152 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
17153
17154 case Expr::ParenExprClass:
17155 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
17156 case Expr::GenericSelectionExprClass:
17157 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
17158 case Expr::IntegerLiteralClass:
17159 case Expr::FixedPointLiteralClass:
17160 case Expr::CharacterLiteralClass:
17161 case Expr::ObjCBoolLiteralExprClass:
17162 case Expr::CXXBoolLiteralExprClass:
17163 case Expr::CXXScalarValueInitExprClass:
17164 case Expr::TypeTraitExprClass:
17165 case Expr::ConceptSpecializationExprClass:
17166 case Expr::RequiresExprClass:
17167 case Expr::ArrayTypeTraitExprClass:
17168 case Expr::ExpressionTraitExprClass:
17169 case Expr::CXXNoexceptExprClass:
17170 return NoDiag();
17171 case Expr::CallExprClass:
17172 case Expr::CXXOperatorCallExprClass: {
17173 // C99 6.6/3 allows function calls within unevaluated subexpressions of
17174 // constant expressions, but they can never be ICEs because an ICE cannot
17175 // contain an operand of (pointer to) function type.
17176 const CallExpr *CE = cast<CallExpr>(E);
17177 if (CE->getBuiltinCallee())
17178 return CheckEvalInICE(E, Ctx);
17179 return ICEDiag(IK_NotICE, E->getBeginLoc());
17180 }
17181 case Expr::CXXRewrittenBinaryOperatorClass:
17182 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
17183 Ctx);
17184 case Expr::DeclRefExprClass: {
17185 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
17186 if (isa<EnumConstantDecl>(D))
17187 return NoDiag();
17188
17189 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
17190 // integer variables in constant expressions:
17191 //
17192 // C++ 7.1.5.1p2
17193 // A variable of non-volatile const-qualified integral or enumeration
17194 // type initialized by an ICE can be used in ICEs.
17195 //
17196 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
17197 // that mode, use of reference variables should not be allowed.
17198 const VarDecl *VD = dyn_cast<VarDecl>(D);
17199 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
17200 !VD->getType()->isReferenceType())
17201 return NoDiag();
17202
17203 return ICEDiag(IK_NotICE, E->getBeginLoc());
17204 }
17205 case Expr::UnaryOperatorClass: {
17206 const UnaryOperator *Exp = cast<UnaryOperator>(E);
17207 switch (Exp->getOpcode()) {
17208 case UO_PostInc:
17209 case UO_PostDec:
17210 case UO_PreInc:
17211 case UO_PreDec:
17212 case UO_AddrOf:
17213 case UO_Deref:
17214 case UO_Coawait:
17215 // C99 6.6/3 allows increment and decrement within unevaluated
17216 // subexpressions of constant expressions, but they can never be ICEs
17217 // because an ICE cannot contain an lvalue operand.
17218 return ICEDiag(IK_NotICE, E->getBeginLoc());
17219 case UO_Extension:
17220 case UO_LNot:
17221 case UO_Plus:
17222 case UO_Minus:
17223 case UO_Not:
17224 case UO_Real:
17225 case UO_Imag:
17226 return CheckICE(Exp->getSubExpr(), Ctx);
17227 }
17228 llvm_unreachable("invalid unary operator class");
17229 }
17230 case Expr::OffsetOfExprClass: {
17231 // Note that per C99, offsetof must be an ICE. And AFAIK, using
17232 // EvaluateAsRValue matches the proposed gcc behavior for cases like
17233 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
17234 // compliance: we should warn earlier for offsetof expressions with
17235 // array subscripts that aren't ICEs, and if the array subscripts
17236 // are ICEs, the value of the offsetof must be an integer constant.
17237 return CheckEvalInICE(E, Ctx);
17238 }
17239 case Expr::UnaryExprOrTypeTraitExprClass: {
17240 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
17241 if ((Exp->getKind() == UETT_SizeOf) &&
17243 return ICEDiag(IK_NotICE, E->getBeginLoc());
17244 return NoDiag();
17245 }
17246 case Expr::BinaryOperatorClass: {
17247 const BinaryOperator *Exp = cast<BinaryOperator>(E);
17248 switch (Exp->getOpcode()) {
17249 case BO_PtrMemD:
17250 case BO_PtrMemI:
17251 case BO_Assign:
17252 case BO_MulAssign:
17253 case BO_DivAssign:
17254 case BO_RemAssign:
17255 case BO_AddAssign:
17256 case BO_SubAssign:
17257 case BO_ShlAssign:
17258 case BO_ShrAssign:
17259 case BO_AndAssign:
17260 case BO_XorAssign:
17261 case BO_OrAssign:
17262 // C99 6.6/3 allows assignments within unevaluated subexpressions of
17263 // constant expressions, but they can never be ICEs because an ICE cannot
17264 // contain an lvalue operand.
17265 return ICEDiag(IK_NotICE, E->getBeginLoc());
17266
17267 case BO_Mul:
17268 case BO_Div:
17269 case BO_Rem:
17270 case BO_Add:
17271 case BO_Sub:
17272 case BO_Shl:
17273 case BO_Shr:
17274 case BO_LT:
17275 case BO_GT:
17276 case BO_LE:
17277 case BO_GE:
17278 case BO_EQ:
17279 case BO_NE:
17280 case BO_And:
17281 case BO_Xor:
17282 case BO_Or:
17283 case BO_Comma:
17284 case BO_Cmp: {
17285 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
17286 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
17287 if (Exp->getOpcode() == BO_Div ||
17288 Exp->getOpcode() == BO_Rem) {
17289 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
17290 // we don't evaluate one.
17291 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
17292 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
17293 if (REval == 0)
17294 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
17295 if (REval.isSigned() && REval.isAllOnes()) {
17296 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
17297 if (LEval.isMinSignedValue())
17298 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
17299 }
17300 }
17301 }
17302 if (Exp->getOpcode() == BO_Comma) {
17303 if (Ctx.getLangOpts().C99) {
17304 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
17305 // if it isn't evaluated.
17306 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
17307 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
17308 } else {
17309 // In both C89 and C++, commas in ICEs are illegal.
17310 return ICEDiag(IK_NotICE, E->getBeginLoc());
17311 }
17312 }
17313 return Worst(LHSResult, RHSResult);
17314 }
17315 case BO_LAnd:
17316 case BO_LOr: {
17317 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
17318 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
17319 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
17320 // Rare case where the RHS has a comma "side-effect"; we need
17321 // to actually check the condition to see whether the side
17322 // with the comma is evaluated.
17323 if ((Exp->getOpcode() == BO_LAnd) !=
17324 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
17325 return RHSResult;
17326 return NoDiag();
17327 }
17328
17329 return Worst(LHSResult, RHSResult);
17330 }
17331 }
17332 llvm_unreachable("invalid binary operator kind");
17333 }
17334 case Expr::ImplicitCastExprClass:
17335 case Expr::CStyleCastExprClass:
17336 case Expr::CXXFunctionalCastExprClass:
17337 case Expr::CXXStaticCastExprClass:
17338 case Expr::CXXReinterpretCastExprClass:
17339 case Expr::CXXConstCastExprClass:
17340 case Expr::ObjCBridgedCastExprClass: {
17341 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
17342 if (isa<ExplicitCastExpr>(E)) {
17343 if (const FloatingLiteral *FL
17344 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
17345 unsigned DestWidth = Ctx.getIntWidth(E->getType());
17346 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
17347 APSInt IgnoredVal(DestWidth, !DestSigned);
17348 bool Ignored;
17349 // If the value does not fit in the destination type, the behavior is
17350 // undefined, so we are not required to treat it as a constant
17351 // expression.
17352 if (FL->getValue().convertToInteger(IgnoredVal,
17353 llvm::APFloat::rmTowardZero,
17354 &Ignored) & APFloat::opInvalidOp)
17355 return ICEDiag(IK_NotICE, E->getBeginLoc());
17356 return NoDiag();
17357 }
17358 }
17359 switch (cast<CastExpr>(E)->getCastKind()) {
17360 case CK_LValueToRValue:
17361 case CK_AtomicToNonAtomic:
17362 case CK_NonAtomicToAtomic:
17363 case CK_NoOp:
17364 case CK_IntegralToBoolean:
17365 case CK_IntegralCast:
17366 return CheckICE(SubExpr, Ctx);
17367 default:
17368 return ICEDiag(IK_NotICE, E->getBeginLoc());
17369 }
17370 }
17371 case Expr::BinaryConditionalOperatorClass: {
17372 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
17373 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
17374 if (CommonResult.Kind == IK_NotICE) return CommonResult;
17375 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
17376 if (FalseResult.Kind == IK_NotICE) return FalseResult;
17377 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
17378 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
17379 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
17380 return FalseResult;
17381 }
17382 case Expr::ConditionalOperatorClass: {
17383 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
17384 // If the condition (ignoring parens) is a __builtin_constant_p call,
17385 // then only the true side is actually considered in an integer constant
17386 // expression, and it is fully evaluated. This is an important GNU
17387 // extension. See GCC PR38377 for discussion.
17388 if (const CallExpr *CallCE
17389 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
17390 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
17391 return CheckEvalInICE(E, Ctx);
17392 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
17393 if (CondResult.Kind == IK_NotICE)
17394 return CondResult;
17395
17396 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
17397 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
17398
17399 if (TrueResult.Kind == IK_NotICE)
17400 return TrueResult;
17401 if (FalseResult.Kind == IK_NotICE)
17402 return FalseResult;
17403 if (CondResult.Kind == IK_ICEIfUnevaluated)
17404 return CondResult;
17405 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
17406 return NoDiag();
17407 // Rare case where the diagnostics depend on which side is evaluated
17408 // Note that if we get here, CondResult is 0, and at least one of
17409 // TrueResult and FalseResult is non-zero.
17410 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
17411 return FalseResult;
17412 return TrueResult;
17413 }
17414 case Expr::CXXDefaultArgExprClass:
17415 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
17416 case Expr::CXXDefaultInitExprClass:
17417 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
17418 case Expr::ChooseExprClass: {
17419 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
17420 }
17421 case Expr::BuiltinBitCastExprClass: {
17422 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
17423 return ICEDiag(IK_NotICE, E->getBeginLoc());
17424 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
17425 }
17426 }
17427
17428 llvm_unreachable("Invalid StmtClass!");
17429}
17430
17431/// Evaluate an expression as a C++11 integral constant expression.
17433 const Expr *E,
17434 llvm::APSInt *Value,
17437 if (Loc) *Loc = E->getExprLoc();
17438 return false;
17439 }
17440
17441 APValue Result;
17442 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
17443 return false;
17444
17445 if (!Result.isInt()) {
17446 if (Loc) *Loc = E->getExprLoc();
17447 return false;
17448 }
17449
17450 if (Value) *Value = Result.getInt();
17451 return true;
17452}
17453
17455 SourceLocation *Loc) const {
17456 assert(!isValueDependent() &&
17457 "Expression evaluator can't be called on a dependent expression.");
17458
17459 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
17460
17461 if (Ctx.getLangOpts().CPlusPlus11)
17462 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
17463
17464 ICEDiag D = CheckICE(this, Ctx);
17465 if (D.Kind != IK_ICE) {
17466 if (Loc) *Loc = D.Loc;
17467 return false;
17468 }
17469 return true;
17470}
17471
17472std::optional<llvm::APSInt>
17474 if (isValueDependent()) {
17475 // Expression evaluator can't succeed on a dependent expression.
17476 return std::nullopt;
17477 }
17478
17479 APSInt Value;
17480
17481 if (Ctx.getLangOpts().CPlusPlus11) {
17483 return Value;
17484 return std::nullopt;
17485 }
17486
17487 if (!isIntegerConstantExpr(Ctx, Loc))
17488 return std::nullopt;
17489
17490 // The only possible side-effects here are due to UB discovered in the
17491 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
17492 // required to treat the expression as an ICE, so we produce the folded
17493 // value.
17495 Expr::EvalStatus Status;
17496 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
17497 Info.InConstantContext = true;
17498
17499 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
17500 llvm_unreachable("ICE cannot be evaluated!");
17501
17502 return ExprResult.Val.getInt();
17503}
17504
17506 assert(!isValueDependent() &&
17507 "Expression evaluator can't be called on a dependent expression.");
17508
17509 return CheckICE(this, Ctx).Kind == IK_ICE;
17510}
17511
17513 SourceLocation *Loc) const {
17514 assert(!isValueDependent() &&
17515 "Expression evaluator can't be called on a dependent expression.");
17516
17517 // We support this checking in C++98 mode in order to diagnose compatibility
17518 // issues.
17519 assert(Ctx.getLangOpts().CPlusPlus);
17520
17521 // Build evaluation settings.
17522 Expr::EvalStatus Status;
17524 Status.Diag = &Diags;
17525 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17526
17527 APValue Scratch;
17528 bool IsConstExpr =
17529 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
17530 // FIXME: We don't produce a diagnostic for this, but the callers that
17531 // call us on arbitrary full-expressions should generally not care.
17532 Info.discardCleanups() && !Status.HasSideEffects;
17533
17534 if (!Diags.empty()) {
17535 IsConstExpr = false;
17536 if (Loc) *Loc = Diags[0].first;
17537 } else if (!IsConstExpr) {
17538 // FIXME: This shouldn't happen.
17539 if (Loc) *Loc = getExprLoc();
17540 }
17541
17542 return IsConstExpr;
17543}
17544
17546 const FunctionDecl *Callee,
17548 const Expr *This) const {
17549 assert(!isValueDependent() &&
17550 "Expression evaluator can't be called on a dependent expression.");
17551
17552 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
17553 std::string Name;
17554 llvm::raw_string_ostream OS(Name);
17555 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
17556 /*Qualified=*/true);
17557 return Name;
17558 });
17559
17560 Expr::EvalStatus Status;
17561 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
17562 Info.InConstantContext = true;
17563
17564 LValue ThisVal;
17565 const LValue *ThisPtr = nullptr;
17566 if (This) {
17567#ifndef NDEBUG
17568 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
17569 assert(MD && "Don't provide `this` for non-methods.");
17570 assert(MD->isImplicitObjectMemberFunction() &&
17571 "Don't provide `this` for methods without an implicit object.");
17572#endif
17573 if (!This->isValueDependent() &&
17574 EvaluateObjectArgument(Info, This, ThisVal) &&
17575 !Info.EvalStatus.HasSideEffects)
17576 ThisPtr = &ThisVal;
17577
17578 // Ignore any side-effects from a failed evaluation. This is safe because
17579 // they can't interfere with any other argument evaluation.
17580 Info.EvalStatus.HasSideEffects = false;
17581 }
17582
17583 CallRef Call = Info.CurrentCall->createCall(Callee);
17584 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
17585 I != E; ++I) {
17586 unsigned Idx = I - Args.begin();
17587 if (Idx >= Callee->getNumParams())
17588 break;
17589 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
17590 if ((*I)->isValueDependent() ||
17591 !EvaluateCallArg(PVD, *I, Call, Info) ||
17592 Info.EvalStatus.HasSideEffects) {
17593 // If evaluation fails, throw away the argument entirely.
17594 if (APValue *Slot = Info.getParamSlot(Call, PVD))
17595 *Slot = APValue();
17596 }
17597
17598 // Ignore any side-effects from a failed evaluation. This is safe because
17599 // they can't interfere with any other argument evaluation.
17600 Info.EvalStatus.HasSideEffects = false;
17601 }
17602
17603 // Parameter cleanups happen in the caller and are not part of this
17604 // evaluation.
17605 Info.discardCleanups();
17606 Info.EvalStatus.HasSideEffects = false;
17607
17608 // Build fake call to Callee.
17609 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
17610 Call);
17611 // FIXME: Missing ExprWithCleanups in enable_if conditions?
17612 FullExpressionRAII Scope(Info);
17613 return Evaluate(Value, Info, this) && Scope.destroy() &&
17614 !Info.EvalStatus.HasSideEffects;
17615}
17616
17619 PartialDiagnosticAt> &Diags) {
17620 // FIXME: It would be useful to check constexpr function templates, but at the
17621 // moment the constant expression evaluator cannot cope with the non-rigorous
17622 // ASTs which we build for dependent expressions.
17623 if (FD->isDependentContext())
17624 return true;
17625
17626 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
17627 std::string Name;
17628 llvm::raw_string_ostream OS(Name);
17630 /*Qualified=*/true);
17631 return Name;
17632 });
17633
17634 Expr::EvalStatus Status;
17635 Status.Diag = &Diags;
17636
17637 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
17638 Info.InConstantContext = true;
17639 Info.CheckingPotentialConstantExpression = true;
17640
17641 // The constexpr VM attempts to compile all methods to bytecode here.
17642 if (Info.EnableNewConstInterp) {
17643 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
17644 return Diags.empty();
17645 }
17646
17647 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
17648 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
17649
17650 // Fabricate an arbitrary expression on the stack and pretend that it
17651 // is a temporary being used as the 'this' pointer.
17652 LValue This;
17653 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
17654 This.set({&VIE, Info.CurrentCall->Index});
17655
17657
17658 APValue Scratch;
17659 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
17660 // Evaluate the call as a constant initializer, to allow the construction
17661 // of objects of non-literal types.
17662 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
17663 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
17664 } else {
17667 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
17668 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
17669 /*ResultSlot=*/nullptr);
17670 }
17671
17672 return Diags.empty();
17673}
17674
17676 const FunctionDecl *FD,
17678 PartialDiagnosticAt> &Diags) {
17679 assert(!E->isValueDependent() &&
17680 "Expression evaluator can't be called on a dependent expression.");
17681
17682 Expr::EvalStatus Status;
17683 Status.Diag = &Diags;
17684
17685 EvalInfo Info(FD->getASTContext(), Status,
17686 EvalInfo::EM_ConstantExpressionUnevaluated);
17687 Info.InConstantContext = true;
17688 Info.CheckingPotentialConstantExpression = true;
17689
17690 // Fabricate a call stack frame to give the arguments a plausible cover story.
17691 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
17692 /*CallExpr=*/nullptr, CallRef());
17693
17694 APValue ResultScratch;
17695 Evaluate(ResultScratch, Info, E);
17696 return Diags.empty();
17697}
17698
17699bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
17700 unsigned Type) const {
17701 if (!getType()->isPointerType())
17702 return false;
17703
17704 Expr::EvalStatus Status;
17705 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17706 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
17707}
17708
17709static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
17710 EvalInfo &Info, std::string *StringResult) {
17711 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
17712 return false;
17713
17714 LValue String;
17715
17716 if (!EvaluatePointer(E, String, Info))
17717 return false;
17718
17719 QualType CharTy = E->getType()->getPointeeType();
17720
17721 // Fast path: if it's a string literal, search the string value.
17722 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
17723 String.getLValueBase().dyn_cast<const Expr *>())) {
17724 StringRef Str = S->getBytes();
17725 int64_t Off = String.Offset.getQuantity();
17726 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
17727 S->getCharByteWidth() == 1 &&
17728 // FIXME: Add fast-path for wchar_t too.
17729 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
17730 Str = Str.substr(Off);
17731
17732 StringRef::size_type Pos = Str.find(0);
17733 if (Pos != StringRef::npos)
17734 Str = Str.substr(0, Pos);
17735
17736 Result = Str.size();
17737 if (StringResult)
17738 *StringResult = Str;
17739 return true;
17740 }
17741
17742 // Fall through to slow path.
17743 }
17744
17745 // Slow path: scan the bytes of the string looking for the terminating 0.
17746 for (uint64_t Strlen = 0; /**/; ++Strlen) {
17747 APValue Char;
17748 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
17749 !Char.isInt())
17750 return false;
17751 if (!Char.getInt()) {
17752 Result = Strlen;
17753 return true;
17754 } else if (StringResult)
17755 StringResult->push_back(Char.getInt().getExtValue());
17756 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
17757 return false;
17758 }
17759}
17760
17761std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
17762 Expr::EvalStatus Status;
17763 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17764 uint64_t Result;
17765 std::string StringResult;
17766
17767 if (EvaluateBuiltinStrLen(this, Result, Info, &StringResult))
17768 return StringResult;
17769 return {};
17770}
17771
17772bool Expr::EvaluateCharRangeAsString(std::string &Result,
17773 const Expr *SizeExpression,
17774 const Expr *PtrExpression, ASTContext &Ctx,
17775 EvalResult &Status) const {
17776 LValue String;
17777 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17778 Info.InConstantContext = true;
17779
17780 FullExpressionRAII Scope(Info);
17781 APSInt SizeValue;
17782 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
17783 return false;
17784
17785 uint64_t Size = SizeValue.getZExtValue();
17786
17787 if (!::EvaluatePointer(PtrExpression, String, Info))
17788 return false;
17789
17790 QualType CharTy = PtrExpression->getType()->getPointeeType();
17791 for (uint64_t I = 0; I < Size; ++I) {
17792 APValue Char;
17793 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
17794 Char))
17795 return false;
17796
17797 APSInt C = Char.getInt();
17798 Result.push_back(static_cast<char>(C.getExtValue()));
17799 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
17800 return false;
17801 }
17802 if (!Scope.destroy())
17803 return false;
17804
17805 if (!CheckMemoryLeaks(Info))
17806 return false;
17807
17808 return true;
17809}
17810
17811bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
17812 Expr::EvalStatus Status;
17813 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17814 return EvaluateBuiltinStrLen(this, Result, Info);
17815}
17816
17817namespace {
17818struct IsWithinLifetimeHandler {
17819 EvalInfo &Info;
17820 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
17821 using result_type = std::optional<bool>;
17822 std::optional<bool> failed() { return std::nullopt; }
17823 template <typename T>
17824 std::optional<bool> found(T &Subobj, QualType SubobjType) {
17825 return true;
17826 }
17827};
17828
17829std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
17830 const CallExpr *E) {
17831 EvalInfo &Info = IEE.Info;
17832 // Sometimes this is called during some sorts of constant folding / early
17833 // evaluation. These are meant for non-constant expressions and are not
17834 // necessary since this consteval builtin will never be evaluated at runtime.
17835 // Just fail to evaluate when not in a constant context.
17836 if (!Info.InConstantContext)
17837 return std::nullopt;
17838 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
17839 const Expr *Arg = E->getArg(0);
17840 if (Arg->isValueDependent())
17841 return std::nullopt;
17842 LValue Val;
17843 if (!EvaluatePointer(Arg, Val, Info))
17844 return std::nullopt;
17845
17846 auto Error = [&](int Diag) {
17847 bool CalledFromStd = false;
17848 const auto *Callee = Info.CurrentCall->getCallee();
17849 if (Callee && Callee->isInStdNamespace()) {
17850 const IdentifierInfo *Identifier = Callee->getIdentifier();
17851 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
17852 }
17853 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
17854 : E->getExprLoc(),
17855 diag::err_invalid_is_within_lifetime)
17856 << (CalledFromStd ? "std::is_within_lifetime"
17857 : "__builtin_is_within_lifetime")
17858 << Diag;
17859 return std::nullopt;
17860 };
17861 // C++2c [meta.const.eval]p4:
17862 // During the evaluation of an expression E as a core constant expression, a
17863 // call to this function is ill-formed unless p points to an object that is
17864 // usable in constant expressions or whose complete object's lifetime began
17865 // within E.
17866
17867 // Make sure it points to an object
17868 // nullptr does not point to an object
17869 if (Val.isNullPointer() || Val.getLValueBase().isNull())
17870 return Error(0);
17871 QualType T = Val.getLValueBase().getType();
17872 assert(!T->isFunctionType() &&
17873 "Pointers to functions should have been typed as function pointers "
17874 "which would have been rejected earlier");
17875 assert(T->isObjectType());
17876 // Hypothetical array element is not an object
17877 if (Val.getLValueDesignator().isOnePastTheEnd())
17878 return Error(1);
17879 assert(Val.getLValueDesignator().isValidSubobject() &&
17880 "Unchecked case for valid subobject");
17881 // All other ill-formed values should have failed EvaluatePointer, so the
17882 // object should be a pointer to an object that is usable in a constant
17883 // expression or whose complete lifetime began within the expression
17884 CompleteObject CO =
17885 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
17886 // The lifetime hasn't begun yet if we are still evaluating the
17887 // initializer ([basic.life]p(1.2))
17888 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
17889 return Error(2);
17890
17891 if (!CO)
17892 return false;
17893 IsWithinLifetimeHandler handler{Info};
17894 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
17895}
17896} // namespace
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3443
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
enum clang::sema::@1724::IndirectLocalPathEntry::EntryKind Kind
IndirectLocalPath & Path
Expr * E
llvm::APSInt APSInt
Definition: Compiler.cpp:23
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1172
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 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 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.
static ICEDiag Worst(ICEDiag A, ICEDiag B)
static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, const VarDecl *VD, CallStackFrame *Frame, unsigned Version, APValue *&Result)
Try to evaluate the initializer for a variable declaration.
static bool handleDefaultInitValue(QualType T, APValue &Result)
Get the value to use for a default-initialized object of type T.
static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, uint64_t Size, uint64_t Idx)
static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base)
static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const LValue &LVal, ConstantExprKind Kind, CheckedTemporaries &CheckedTemps)
Check that this reference or pointer core constant expression is a valid value for an address or refe...
static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, const APSInt &LHS, const APSInt &RHS, unsigned BitWidth, Operation Op, APSInt &Result)
Perform the given integer operation, which is known to need at most BitWidth bits,...
static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info)
Evaluate an expression of record type as a temporary.
static bool EvaluateArray(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, APValue &Value, const FieldDecl *FD)
static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E, QualType ElemType, APValue const &VecVal1, APValue const &VecVal2, unsigned EltNum, APValue &Result)
static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO, const Expr *E, QualType SourceTy, QualType DestTy, APValue const &Original, APValue &Result)
static const ValueDecl * HandleMemberPointerAccess(EvalInfo &Info, QualType LVType, LValue &LV, const Expr *RHS, bool IncludeMember=true)
HandleMemberPointerAccess - Evaluate a member access operation and build an lvalue referring to the r...
static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, LValue &Result)
HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on the provided lvalue,...
static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info)
static bool IsOpaqueConstantCall(const CallExpr *E)
Should this call expression be treated as forming an opaque constant?
static bool CheckMemberPointerConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Member pointers are constant expressions unless they point to a non-virtual dllimport member function...
static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, const LValue &LVal, APValue &RVal, bool WantObjectRepresentation=false)
Perform an lvalue-to-rvalue conversion on the given glvalue.
static bool refersToCompleteObject(const LValue &LVal)
Tests to see if the LValue has a user-specified designator (that isn't necessarily valid).
static bool AreElementsOfSameArray(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B)
Determine whether the given subobject designators refer to elements of the same array object.
static bool 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)
CharUnits GetAlignOfExpr(const ASTContext &Ctx, const Expr *E, UnaryExprOrTypeTrait ExprKind)
static bool isModification(AccessKinds AK)
static bool handleCompareOpForVector(const APValue &LHSValue, BinaryOperatorKind Opcode, const APValue &RHSValue, APInt &Result)
static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr)
static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, LValue &This)
Build an lvalue for the object argument of a member function call.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
static bool 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 CharUnits GetAlignOfType(const ASTContext &Ctx, QualType T, UnaryExprOrTypeTrait ExprKind)
static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, APValue &Val, APSInt &Alignment)
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, APSInt Adjustment)
Update a pointer value to model pointer arithmetic.
static bool extractSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &Result, AccessKinds AK=AK_Read)
Extract the designated sub-object of an rvalue.
static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, const FieldDecl *FD, const ASTRecordLayout *RL=nullptr)
Update LVal to refer to the given field, which must be a member of the type currently described by LV...
static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, bool IsSub)
static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD)
void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, const Expr *E, APValue &Result, bool CopyObjectRepresentation)
Perform a trivial copy from Param, which is the parameter of a copy or move constructor or assignment...
static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, APFloat::opStatus St)
Check if the given evaluation result is allowed for constant evaluation.
static bool EvaluateBuiltinConstantPForLValue(const APValue &LV)
EvaluateBuiltinConstantPForLValue - Determine the result of __builtin_constant_p when applied to the ...
static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg)
EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to GCC as we can manage.
static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, const LValue &This, const CXXMethodDecl *NamedMember)
Check that the pointee of the 'this' pointer in a member function call is either within its lifetime ...
static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Check that this core constant expression value is a valid value for a constant expression.
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
static std::optional< DynamicType > ComputeDynamicType(EvalInfo &Info, const Expr *E, LValue &This, AccessKinds AK)
Determine the dynamic type of an object.
static 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 SubobjectHandler::result_type findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, SubobjectHandler &handler)
Find the designated sub-object of an rvalue.
static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, unsigned Type, const LValue &LVal, CharUnits &EndOffset)
Helper for tryEvaluateBuiltinObjectSize – Given an LValue, this will determine how many bytes exist f...
static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, CharUnits &Result)
Converts the given APInt to CharUnits, assuming the APInt is unsigned.
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 GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal, LValueBaseString &AsString)
static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E)
static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, EvalInfo &Info)
EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and produce either the intege...
static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, LValue &Ptr)
Apply the given dynamic cast operation on the provided lvalue.
static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, LValue &Result)
Perform a call to 'operator new' or to ‘__builtin_operator_new’.
static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, QualType SrcType, QualType DestType, APFloat &Result)
static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, const LValue &LHS)
Handle a builtin simple-assignment or a call to a trivial assignment operator whose left-hand side mi...
static bool isFormalAccess(AccessKinds AK)
Is this an access per the C++ definition?
static bool handleCompoundAssignment(EvalInfo &Info, const CompoundAssignOperator *E, const LValue &LVal, QualType LValType, QualType PromotedLValType, BinaryOperatorKind Opcode, const APValue &RVal)
Perform a compound assignment of LVal <op>= RVal.
static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, bool IsIncrement, APValue *Old)
Perform an increment or decrement on LVal.
static ICEDiag NoDiag()
static bool EvaluateVoid(const Expr *E, EvalInfo &Info)
static bool HandleDestruction(EvalInfo &Info, const Expr *E, const LValue &This, QualType ThisType)
Perform a destructor or pseudo-destructor call on the given object, which might in general not be a c...
static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange, const LValue &This, APValue &Value, QualType T)
static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info, const LValue &LHS, const LValue &RHS)
StringRef Identifier
Definition: Format.cpp:3059
const CFGBlock * Block
Definition: HTMLLogger.cpp:152
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition: MachO.h:31
Implements a partial diagnostic which may not be emitted.
llvm::DenseMap< Stmt *, Stmt * > MapTy
Definition: ParentMap.cpp:21
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
SourceLocation Loc
Definition: SemaObjC.cpp:759
bool Indirect
Definition: SemaObjC.cpp:760
static QualType getPointeeType(const MemRegion *R)
Enumerates target-specific builtins in their own namespaces within namespace clang.
Defines the clang::TypeLoc interface and its subclasses.
__DEVICE__ long long abs(long long __n)
__device__ int
#define bool
Definition: amdgpuintrin.h:20
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:206
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition: APValue.h:214
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool hasArrayFiller() const
Definition: APValue.h:560
const LValueBase getLValueBase() const
Definition: APValue.cpp:973
APValue & getArrayInitializedElt(unsigned I)
Definition: APValue.h:552
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition: APValue.cpp:468
APSInt & getInt()
Definition: APValue.h:465
APValue & getStructField(unsigned i)
Definition: APValue.h:593
const FieldDecl * getUnionField() const
Definition: APValue.h:605
bool isVector() const
Definition: APValue.h:449
APSInt & getComplexIntImag()
Definition: APValue.h:503
bool isAbsent() const
Definition: APValue.h:439
bool isComplexInt() const
Definition: APValue.h:446
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:203
ValueKind getKind() const
Definition: APValue.h:437
unsigned getArrayInitializedElts() const
Definition: APValue.h:571
static APValue IndeterminateValue()
Definition: APValue.h:408
bool isFloat() const
Definition: APValue.h:444
APFixedPoint & getFixedPoint()
Definition: APValue.h:487
bool hasValue() const
Definition: APValue.h:441
bool hasLValuePath() const
Definition: APValue.cpp:988
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1056
APValue & getUnionValue()
Definition: APValue.h:609
CharUnits & getLValueOffset()
Definition: APValue.cpp:983
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:693
bool isComplexFloat() const
Definition: APValue.h:447
APValue & getVectorElt(unsigned I)
Definition: APValue.h:539
APValue & getArrayFiller()
Definition: APValue.h:563
unsigned getVectorLength() const
Definition: APValue.h:547
bool isLValue() const
Definition: APValue.h:448
void setUnion(const FieldDecl *Field, const APValue &Value)
Definition: APValue.cpp:1049
bool isIndeterminate() const
Definition: APValue.h:440
bool isInt() const
Definition: APValue.h:443
unsigned getArraySize() const
Definition: APValue.h:575
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
bool isFixedPoint() const
Definition: APValue.h:445
@ 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:451
APSInt & getComplexIntReal()
Definition: APValue.h:495
APFloat & getComplexFloatImag()
Definition: APValue.h:519
APFloat & getComplexFloatReal()
Definition: APValue.h:511
APFloat & getFloat()
Definition: APValue.h:479
APValue & getStructBase(unsigned i)
Definition: APValue.h:588
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
SourceManager & getSourceManager()
Definition: ASTContext.h:741
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
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,...
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
Definition: ASTContext.h:2573
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:834
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:2413
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:733
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:2482
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
Definition: ASTContext.h:3175
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2486
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:4421
LabelDecl * getLabel() const
Definition: Expr.h:4444
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition: Expr.h:5805
Represents a loop initializing the elements of an array.
Definition: Expr.h:5752
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2718
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:3577
QualType getElementType() const
Definition: Type.h:3589
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7761
Attr - This represents one attribute.
Definition: Attr.h:43
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4324
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition: Expr.h:4378
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition: Expr.h:4359
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3909
Expr * getLHS() const
Definition: Expr.h:3959
bool isComparisonOp() const
Definition: Expr.h:4010
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition: Expr.h:4056
bool isLogicalOp() const
Definition: Expr.h:4043
Expr * getRHS() const
Definition: Expr.h:3961
Opcode getOpcode() const
Definition: Expr.h:3954
A binding in a decomposition declaration.
Definition: DeclCXX.h:4125
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6414
Represents a C++2a __builtin_bit_cast(T, v) expression.
Definition: ExprCXX.h:5298
This class is used for builtin types like 'int'.
Definition: Type.h:3034
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:2553
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2845
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Definition: DeclCXX.h:2638
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:2817
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:2078
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:2549
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:2556
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2657
bool isInstance() const
Definition: DeclCXX.h:2105
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2582
bool isStatic() const
Definition: DeclCXX.cpp:2280
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2560
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition: DeclCXX.cpp:2693
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:4960
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:1245
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition: DeclCXX.cpp:1629
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:1378
base_class_range bases()
Definition: DeclCXX.h:620
capture_const_iterator captures_end() const
Definition: DeclCXX.h:1119
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:1735
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:1198
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:2069
capture_const_iterator captures_begin() const
Definition: DeclCXX.h:1113
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1688
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:2874
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition: Expr.cpp:1577
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3047
Decl * getCalleeDecl()
Definition: Expr.h:3041
CaseStmt - Represent a case statement.
Definition: Stmt.h:1828
Expr * getLHS()
Definition: Stmt.h:1915
Expr * getRHS()
Definition: Stmt.h:1927
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3547
const CXXBaseSpecifier *const * path_const_iterator
Definition: Expr.h:3614
Expr * getSubExpr()
Definition: Expr.h:3597
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:4641
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:3145
QualType getElementType() const
Definition: Type.h:3155
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:4171
QualType getComputationLHSType() const
Definition: Expr.h:4205
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3477
bool isFileScope() const
Definition: Expr.h:3504
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1628
bool body_empty() const
Definition: Stmt.h:1672
Stmt *const * const_body_iterator
Definition: Stmt.h:1700
body_iterator body_end()
Definition: Stmt.h:1693
body_range body()
Definition: Stmt.h:1691
body_iterator body_begin()
Definition: Stmt.h:1692
Represents the specialization of a concept - evaluates to a prvalue of type bool.
Definition: ExprConcepts.h:42
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4262
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition: Expr.h:4294
Expr * getCond() const
getCond - Return the expression representing the condition for the ?: operator.
Definition: Expr.h:4285
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition: Expr.h:4289
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:3615
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition: Type.h:3678
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:205
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:245
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:3704
bool isZeroSize() const
Return true if the size is zero.
Definition: Type.h:3685
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition: Type.h:3711
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3671
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3691
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:4582
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:2369
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1334
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:1519
decl_range decls()
Definition: Stmt.h:1567
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isInStdNamespace() const
Definition: DeclBase.cpp:422
static void add(Kind k)
Definition: DeclBase.cpp:221
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:520
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
bool isInvalidDecl() const
Definition: DeclBase.h:591
SourceLocation getLocation() const
Definition: DeclBase.h:442
DeclContext * getDeclContext()
Definition: DeclBase.h:451
AccessSpecifier getAccess() const
Definition: DeclBase.h:510
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:4184
Designator - A designator in a C99 designated initializer.
Definition: Designator.h:38
DoStmt - This represents a 'do/while' stmt.
Definition: Stmt.h:2752
Stmt * getBody()
Definition: Stmt.h:2777
Expr * getCond()
Definition: Stmt.h:2770
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:4916
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3277
Represents an enum.
Definition: Decl.h:3847
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition: Decl.h:4044
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4061
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4007
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:4996
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6098
EnumDecl * getDecl() const
Definition: Type.h:6105
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3799
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:3095
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:3886
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3090
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:3086
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:3587
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:3224
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:6354
bool isFPConstrained() const
Definition: LangOptions.h:906
LangOptions::FPExceptionModeKind getExceptionMode() const
Definition: LangOptions.h:924
RoundingMode getRoundingMode() const
Definition: LangOptions.h:912
Represents a member of a struct/union/class.
Definition: Decl.h:3033
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3124
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4654
unsigned getBitWidthValue(const ASTContext &Ctx) const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4602
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3250
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:3261
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:101
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition: Stmt.h:2808
Represents a function declaration or definition.
Definition: Decl.h:1935
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2672
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3243
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4064
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4052
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2305
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4188
ArrayRef< ParmVarDecl * >::const_iterator param_const_iterator
Definition: Decl.h:2658
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2398
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:3372
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2313
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:3088
Declaration of a template function.
Definition: DeclTemplate.h:959
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:4716
Represents a C11 generic selection.
Definition: Expr.h:5966
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:2165
Stmt * getThen()
Definition: Stmt.h:2254
Stmt * getInit()
Definition: Stmt.h:2315
bool isNonNegatedConsteval() const
Definition: Stmt.h:2350
Expr * getCond()
Definition: Stmt.h:2242
Stmt * getElse()
Definition: Stmt.h:2263
bool isConsteval() const
Definition: Stmt.h:2345
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition: Stmt.cpp:989
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:5841
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3321
ArrayRef< NamedDecl * > chain() const
Definition: Decl.h:3343
Describes an C or C++ initializer list.
Definition: Expr.h:5088
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:499
A global _GUID constant.
Definition: DeclCXX.h:4307
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition: ExprCXX.h:4734
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3236
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
This represents a decl that may have a name.
Definition: Decl.h:253
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
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:2519
Expr * getIndexExpr(unsigned Idx)
Definition: Expr.h:2580
const OffsetOfNode & getComponent(unsigned Idx) const
Definition: Expr.h:2566
TypeSourceInfo * getTypeSourceInfo() const
Definition: Expr.h:2559
unsigned getNumComponents() const
Definition: Expr.h:2576
Helper class for OffsetOfExpr.
Definition: Expr.h:2413
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition: Expr.h:2471
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition: Expr.h:2477
@ Array
An index into an array.
Definition: Expr.h:2418
@ Identifier
A field in a dependent type, known only by its name.
Definition: Expr.h:2422
@ Field
A field.
Definition: Expr.h:2420
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition: Expr.h:2425
Kind getKind() const
Determine what kind of offsetof node this is.
Definition: Expr.h:2467
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition: Expr.h:2487
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
This expression type represents an asterisk in an OpenACC Size-Expr, used in the 'tile' and 'gang' cl...
Definition: Expr.h:2078
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:2170
Represents a parameter to a function.
Definition: Decl.h:1725
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1785
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
[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:6546
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8015
QualType withConst() const
Definition: Type.h:1154
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7931
bool isConstant(const ASTContext &Ctx) const
Definition: Type.h:1089
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:8134
QualType getCanonicalType() const
Definition: Type.h:7983
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8025
void removeLocalVolatile()
Definition: Type.h:8047
QualType withCVRQualifiers(unsigned CVR) const
Definition: Type.h:1174
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition: Type.h:1159
void removeLocalConst()
Definition: Type.h:8039
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8004
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1531
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7977
Represents a struct/union/class.
Definition: Decl.h:4148
bool hasFlexibleArrayMember() const
Definition: Decl.h:4181
field_iterator field_end() const
Definition: Decl.h:4357
field_range fields() const
Definition: Decl.h:4354
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4200
bool field_empty() const
Definition: Decl.h:4362
field_iterator field_begin() const
Definition: Decl.cpp:5092
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
RecordDecl * getDecl() const
Definition: Type.h:6082
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
Definition: ExprConcepts.h:502
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:4514
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:4810
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:4466
Stmt - This represents one statement.
Definition: Stmt.h:84
StmtClass getStmtClass() const
Definition: Stmt.h:1380
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:333
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:345
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:1187
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4490
const SwitchCase * getNextSwitchCase() const
Definition: Stmt.h:1801
SwitchStmt - This represents a 'switch' stmt.
Definition: Stmt.h:2415
Expr * getCond()
Definition: Stmt.h:2478
Stmt * getBody()
Definition: Stmt.h:2490
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition: Stmt.cpp:1107
Stmt * getInit()
Definition: Stmt.h:2499
SwitchCase * getSwitchCaseList()
Definition: Stmt.h:2552
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4749
bool isUnion() const
Definition: Decl.h:3770
virtual bool isNan2008() const
Returns true if NaN encoding is IEEE 754-2008.
Definition: TargetInfo.h:1257
A template argument list.
Definition: DeclTemplate.h:250
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:286
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:280
@ 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:7913
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:1828
bool isStructureType() const
Definition: Type.cpp:662
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isVoidType() const
Definition: Type.h:8510
bool isBooleanType() const
Definition: Type.h:8638
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2201
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2937
bool isIncompleteArrayType() const
Definition: Type.h:8266
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2180
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:710
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: Type.h:8809
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2251
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2105
bool isConstantArrayType() const
Definition: Type.h:8262
bool isNothrowT() const
Definition: Type.cpp:3106
bool isVoidPointerType() const
Definition: Type.cpp:698
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2386
bool isArrayType() const
Definition: Type.h:8258
bool isCharType() const
Definition: Type.cpp:2123
bool isFunctionPointerType() const
Definition: Type.h:8226
bool isPointerType() const
Definition: Type.h:8186
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8550
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8800
bool isReferenceType() const
Definition: Type.h:8204
bool isEnumeralType() const
Definition: Type.h:8290
bool isVariableArrayType() const
Definition: Type.h:8270
bool isChar8Type() const
Definition: Type.cpp:2139
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2554
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8625
bool isExtVectorBoolType() const
Definition: Type.h:8306
bool isMemberDataPointerType() const
Definition: Type.h:8251
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8479
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool isAnyComplexType() const
Definition: Type.h:8294
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8563
const RecordType * getAsStructureType() const
Definition: Type.cpp:754
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8681
bool isMemberPointerType() const
Definition: Type.h:8240
bool isAtomicType() const
Definition: Type.h:8341
bool isComplexIntegerType() const
Definition: Type.cpp:716
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8786
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2446
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
bool isFunctionType() const
Definition: Type.h:8182
bool isVectorType() const
Definition: Type.h:8298
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2300
bool isFloatingType() const
Definition: Type.cpp:2283
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:2230
bool isAnyPointerType() const
Definition: Type.h:8194
TypeClass getTypeClass() const
Definition: Type.h:2341
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
bool isNullPtrType() const
Definition: Type.h:8543
bool isRecordType() const
Definition: Type.h:8286
bool isUnionType() const
Definition: Type.cpp:704
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2513
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition: Type.h:8672
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1920
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2622
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition: Expr.h:2691
UnaryExprOrTypeTrait getKind() const
Definition: Expr.h:2654
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2232
Expr * getSubExpr() const
Definition: Expr.h:2277
Opcode getOpcode() const
Definition: Expr.h:2272
static bool isIncrementOp(Opcode Op)
Definition: Expr.h:2318
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4364
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
QualType getType() const
Definition: Decl.h:682
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5388
QualType getType() const
Definition: Value.cpp:234
bool hasValue() const
Definition: Value.h:135
Represents a variable declaration or definition.
Definition: Decl.h:882
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1513
bool hasInit() const
Definition: Decl.cpp:2387
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition: Decl.cpp:2608
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1522
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2547
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition: Decl.cpp:2853
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition: Decl.cpp:2620
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2355
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:2458
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:1159
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1128
const Expr * getInit() const
Definition: Decl.h:1319
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:2600
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1135
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2364
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1204
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:2500
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition: Decl.h:1309
Represents a GCC generic vector type.
Definition: Type.h:4034
unsigned getNumElements() const
Definition: Type.h:4049
QualType getElementType() const
Definition: Type.h:4048
WhileStmt - This represents a 'while' stmt.
Definition: Stmt.h:2611
Expr * getCond()
Definition: Stmt.h:2663
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition: Stmt.cpp:1168
Stmt * getBody()
Definition: Stmt.h:2675
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:57
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:180
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:3888
llvm::APFloat APFloat
Definition: Floating.h:23
llvm::APInt APInt
Definition: FixedPoint.h:19
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1157
llvm::FixedPointSemantics FixedPointSemantics
Definition: Interp.h:43
bool This(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2392
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2355
bool Alloc(InterpState &S, CodePtr OpPC, const Descriptor *Desc)
Definition: Interp.h:2885
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:204
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:41
@ CSK_ArrayToPointer
Definition: State.h:45
@ CSK_Derived
Definition: State.h:43
@ CSK_Base
Definition: State.h:42
@ CSK_Real
Definition: State.h:47
@ CSK_ArrayIndex
Definition: State.h:46
@ CSK_Imag
Definition: State.h:48
@ CSK_VectorElement
Definition: State.h:49
@ CSK_Field
Definition: State.h:44
@ 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_IsWithinLifetime
Definition: State.h:37
@ 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:1274
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
unsigned PathLength
The corresponding path length in the lvalue.
const CXXRecordDecl * Type
The dynamic class type of the object.
std::string ObjCEncodeStorage
Represents an element in a path from a derived class to a base class.
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h: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