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 "Interp/Context.h"
36 #include "Interp/Frame.h"
37 #include "Interp/State.h"
38 #include "clang/AST/APValue.h"
39 #include "clang/AST/ASTContext.h"
40 #include "clang/AST/ASTDiagnostic.h"
41 #include "clang/AST/ASTLambda.h"
42 #include "clang/AST/Attr.h"
43 #include "clang/AST/CXXInheritance.h"
44 #include "clang/AST/CharUnits.h"
45 #include "clang/AST/CurrentSourceLocExprScope.h"
46 #include "clang/AST/Expr.h"
47 #include "clang/AST/OSLog.h"
48 #include "clang/AST/OptionalDiagnostic.h"
49 #include "clang/AST/RecordLayout.h"
50 #include "clang/AST/StmtVisitor.h"
51 #include "clang/AST/TypeLoc.h"
52 #include "clang/Basic/Builtins.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "llvm/ADT/APFixedPoint.h"
55 #include "llvm/ADT/Optional.h"
56 #include "llvm/ADT/SmallBitVector.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/SaveAndRestore.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include <cstring>
61 #include <functional>
62
63 #define DEBUG_TYPE "exprconstant"
64
65 using namespace clang;
66 using llvm::APFixedPoint;
67 using llvm::APInt;
68 using llvm::APSInt;
69 using llvm::APFloat;
70 using llvm::FixedPointSemantics;
71 using llvm::Optional;
72
73 namespace {
74 struct LValue;
75 class CallStackFrame;
76 class EvalInfo;
77
78 using SourceLocExprScopeGuard =
79 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
80
getType(APValue::LValueBase B)81 static QualType getType(APValue::LValueBase B) {
82 return B.getType();
83 }
84
85 /// Get an LValue path entry, which is known to not be an array index, as a
86 /// field declaration.
getAsField(APValue::LValuePathEntry E)87 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
88 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
89 }
90 /// Get an LValue path entry, which is known to not be an array index, as a
91 /// base class declaration.
getAsBaseClass(APValue::LValuePathEntry E)92 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
93 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
94 }
95 /// Determine whether this LValue path entry for a base class names a virtual
96 /// base class.
isVirtualBaseClass(APValue::LValuePathEntry E)97 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
98 return E.getAsBaseOrMember().getInt();
99 }
100
101 /// Given an expression, determine the type used to store the result of
102 /// evaluating that expression.
getStorageType(const ASTContext & Ctx,const Expr * E)103 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
104 if (E->isRValue())
105 return E->getType();
106 return Ctx.getLValueReferenceType(E->getType());
107 }
108
109 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
getAllocSizeAttr(const CallExpr * CE)110 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
111 const FunctionDecl *Callee = CE->getDirectCallee();
112 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
113 }
114
115 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
116 /// This will look through a single cast.
117 ///
118 /// Returns null if we couldn't unwrap a function with alloc_size.
tryUnwrapAllocSizeCall(const Expr * E)119 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
120 if (!E->getType()->isPointerType())
121 return nullptr;
122
123 E = E->IgnoreParens();
124 // If we're doing a variable assignment from e.g. malloc(N), there will
125 // probably be a cast of some kind. In exotic cases, we might also see a
126 // top-level ExprWithCleanups. Ignore them either way.
127 if (const auto *FE = dyn_cast<FullExpr>(E))
128 E = FE->getSubExpr()->IgnoreParens();
129
130 if (const auto *Cast = dyn_cast<CastExpr>(E))
131 E = Cast->getSubExpr()->IgnoreParens();
132
133 if (const auto *CE = dyn_cast<CallExpr>(E))
134 return getAllocSizeAttr(CE) ? CE : nullptr;
135 return nullptr;
136 }
137
138 /// Determines whether or not the given Base contains a call to a function
139 /// with the alloc_size attribute.
isBaseAnAllocSizeCall(APValue::LValueBase Base)140 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
141 const auto *E = Base.dyn_cast<const Expr *>();
142 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
143 }
144
145 /// Determines whether the given kind of constant expression is only ever
146 /// used for name mangling. If so, it's permitted to reference things that we
147 /// can't generate code for (in particular, dllimported functions).
isForManglingOnly(ConstantExprKind Kind)148 static bool isForManglingOnly(ConstantExprKind Kind) {
149 switch (Kind) {
150 case ConstantExprKind::Normal:
151 case ConstantExprKind::ClassTemplateArgument:
152 case ConstantExprKind::ImmediateInvocation:
153 // Note that non-type template arguments of class type are emitted as
154 // template parameter objects.
155 return false;
156
157 case ConstantExprKind::NonClassTemplateArgument:
158 return true;
159 }
160 llvm_unreachable("unknown ConstantExprKind");
161 }
162
isTemplateArgument(ConstantExprKind Kind)163 static bool isTemplateArgument(ConstantExprKind Kind) {
164 switch (Kind) {
165 case ConstantExprKind::Normal:
166 case ConstantExprKind::ImmediateInvocation:
167 return false;
168
169 case ConstantExprKind::ClassTemplateArgument:
170 case ConstantExprKind::NonClassTemplateArgument:
171 return true;
172 }
173 llvm_unreachable("unknown ConstantExprKind");
174 }
175
176 /// The bound to claim that an array of unknown bound has.
177 /// The value in MostDerivedArraySize is undefined in this case. So, set it
178 /// to an arbitrary value that's likely to loudly break things if it's used.
179 static const uint64_t AssumedSizeForUnsizedArray =
180 std::numeric_limits<uint64_t>::max() / 2;
181
182 /// Determines if an LValue with the given LValueBase will have an unsized
183 /// array in its designator.
184 /// Find the path length and type of the most-derived subobject in the given
185 /// path, and find the size of the containing array, if any.
186 static unsigned
findMostDerivedSubobject(ASTContext & Ctx,APValue::LValueBase Base,ArrayRef<APValue::LValuePathEntry> Path,uint64_t & ArraySize,QualType & Type,bool & IsArray,bool & FirstEntryIsUnsizedArray)187 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
188 ArrayRef<APValue::LValuePathEntry> Path,
189 uint64_t &ArraySize, QualType &Type, bool &IsArray,
190 bool &FirstEntryIsUnsizedArray) {
191 // This only accepts LValueBases from APValues, and APValues don't support
192 // arrays that lack size info.
193 assert(!isBaseAnAllocSizeCall(Base) &&
194 "Unsized arrays shouldn't appear here");
195 unsigned MostDerivedLength = 0;
196 Type = getType(Base);
197
198 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
199 if (Type->isArrayType()) {
200 const ArrayType *AT = Ctx.getAsArrayType(Type);
201 Type = AT->getElementType();
202 MostDerivedLength = I + 1;
203 IsArray = true;
204
205 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
206 ArraySize = CAT->getSize().getZExtValue();
207 } else {
208 assert(I == 0 && "unexpected unsized array designator");
209 FirstEntryIsUnsizedArray = true;
210 ArraySize = AssumedSizeForUnsizedArray;
211 }
212 } else if (Type->isAnyComplexType()) {
213 const ComplexType *CT = Type->castAs<ComplexType>();
214 Type = CT->getElementType();
215 ArraySize = 2;
216 MostDerivedLength = I + 1;
217 IsArray = true;
218 } else if (const FieldDecl *FD = getAsField(Path[I])) {
219 Type = FD->getType();
220 ArraySize = 0;
221 MostDerivedLength = I + 1;
222 IsArray = false;
223 } else {
224 // Path[I] describes a base class.
225 ArraySize = 0;
226 IsArray = false;
227 }
228 }
229 return MostDerivedLength;
230 }
231
232 /// A path from a glvalue to a subobject of that glvalue.
233 struct SubobjectDesignator {
234 /// True if the subobject was named in a manner not supported by C++11. Such
235 /// lvalues can still be folded, but they are not core constant expressions
236 /// and we cannot perform lvalue-to-rvalue conversions on them.
237 unsigned Invalid : 1;
238
239 /// Is this a pointer one past the end of an object?
240 unsigned IsOnePastTheEnd : 1;
241
242 /// Indicator of whether the first entry is an unsized array.
243 unsigned FirstEntryIsAnUnsizedArray : 1;
244
245 /// Indicator of whether the most-derived object is an array element.
246 unsigned MostDerivedIsArrayElement : 1;
247
248 /// The length of the path to the most-derived object of which this is a
249 /// subobject.
250 unsigned MostDerivedPathLength : 28;
251
252 /// The size of the array of which the most-derived object is an element.
253 /// This will always be 0 if the most-derived object is not an array
254 /// element. 0 is not an indicator of whether or not the most-derived object
255 /// is an array, however, because 0-length arrays are allowed.
256 ///
257 /// If the current array is an unsized array, the value of this is
258 /// undefined.
259 uint64_t MostDerivedArraySize;
260
261 /// The type of the most derived object referred to by this address.
262 QualType MostDerivedType;
263
264 typedef APValue::LValuePathEntry PathEntry;
265
266 /// The entries on the path from the glvalue to the designated subobject.
267 SmallVector<PathEntry, 8> Entries;
268
SubobjectDesignator__anon4717f8730111::SubobjectDesignator269 SubobjectDesignator() : Invalid(true) {}
270
SubobjectDesignator__anon4717f8730111::SubobjectDesignator271 explicit SubobjectDesignator(QualType T)
272 : Invalid(false), IsOnePastTheEnd(false),
273 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
274 MostDerivedPathLength(0), MostDerivedArraySize(0),
275 MostDerivedType(T) {}
276
SubobjectDesignator__anon4717f8730111::SubobjectDesignator277 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
278 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
279 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
280 MostDerivedPathLength(0), MostDerivedArraySize(0) {
281 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
282 if (!Invalid) {
283 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
284 ArrayRef<PathEntry> VEntries = V.getLValuePath();
285 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
286 if (V.getLValueBase()) {
287 bool IsArray = false;
288 bool FirstIsUnsizedArray = false;
289 MostDerivedPathLength = findMostDerivedSubobject(
290 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
291 MostDerivedType, IsArray, FirstIsUnsizedArray);
292 MostDerivedIsArrayElement = IsArray;
293 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
294 }
295 }
296 }
297
truncate__anon4717f8730111::SubobjectDesignator298 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
299 unsigned NewLength) {
300 if (Invalid)
301 return;
302
303 assert(Base && "cannot truncate path for null pointer");
304 assert(NewLength <= Entries.size() && "not a truncation");
305
306 if (NewLength == Entries.size())
307 return;
308 Entries.resize(NewLength);
309
310 bool IsArray = false;
311 bool FirstIsUnsizedArray = false;
312 MostDerivedPathLength = findMostDerivedSubobject(
313 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
314 FirstIsUnsizedArray);
315 MostDerivedIsArrayElement = IsArray;
316 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
317 }
318
setInvalid__anon4717f8730111::SubobjectDesignator319 void setInvalid() {
320 Invalid = true;
321 Entries.clear();
322 }
323
324 /// Determine whether the most derived subobject is an array without a
325 /// known bound.
isMostDerivedAnUnsizedArray__anon4717f8730111::SubobjectDesignator326 bool isMostDerivedAnUnsizedArray() const {
327 assert(!Invalid && "Calling this makes no sense on invalid designators");
328 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
329 }
330
331 /// Determine what the most derived array's size is. Results in an assertion
332 /// failure if the most derived array lacks a size.
getMostDerivedArraySize__anon4717f8730111::SubobjectDesignator333 uint64_t getMostDerivedArraySize() const {
334 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
335 return MostDerivedArraySize;
336 }
337
338 /// Determine whether this is a one-past-the-end pointer.
isOnePastTheEnd__anon4717f8730111::SubobjectDesignator339 bool isOnePastTheEnd() const {
340 assert(!Invalid);
341 if (IsOnePastTheEnd)
342 return true;
343 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
344 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
345 MostDerivedArraySize)
346 return true;
347 return false;
348 }
349
350 /// Get the range of valid index adjustments in the form
351 /// {maximum value that can be subtracted from this pointer,
352 /// maximum value that can be added to this pointer}
validIndexAdjustments__anon4717f8730111::SubobjectDesignator353 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
354 if (Invalid || isMostDerivedAnUnsizedArray())
355 return {0, 0};
356
357 // [expr.add]p4: For the purposes of these operators, a pointer to a
358 // nonarray object behaves the same as a pointer to the first element of
359 // an array of length one with the type of the object as its element type.
360 bool IsArray = MostDerivedPathLength == Entries.size() &&
361 MostDerivedIsArrayElement;
362 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
363 : (uint64_t)IsOnePastTheEnd;
364 uint64_t ArraySize =
365 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
366 return {ArrayIndex, ArraySize - ArrayIndex};
367 }
368
369 /// Check that this refers to a valid subobject.
isValidSubobject__anon4717f8730111::SubobjectDesignator370 bool isValidSubobject() const {
371 if (Invalid)
372 return false;
373 return !isOnePastTheEnd();
374 }
375 /// Check that this refers to a valid subobject, and if not, produce a
376 /// relevant diagnostic and set the designator as invalid.
377 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
378
379 /// Get the type of the designated object.
getType__anon4717f8730111::SubobjectDesignator380 QualType getType(ASTContext &Ctx) const {
381 assert(!Invalid && "invalid designator has no subobject type");
382 return MostDerivedPathLength == Entries.size()
383 ? MostDerivedType
384 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
385 }
386
387 /// Update this designator to refer to the first element within this array.
addArrayUnchecked__anon4717f8730111::SubobjectDesignator388 void addArrayUnchecked(const ConstantArrayType *CAT) {
389 Entries.push_back(PathEntry::ArrayIndex(0));
390
391 // This is a most-derived object.
392 MostDerivedType = CAT->getElementType();
393 MostDerivedIsArrayElement = true;
394 MostDerivedArraySize = CAT->getSize().getZExtValue();
395 MostDerivedPathLength = Entries.size();
396 }
397 /// Update this designator to refer to the first element within the array of
398 /// elements of type T. This is an array of unknown size.
addUnsizedArrayUnchecked__anon4717f8730111::SubobjectDesignator399 void addUnsizedArrayUnchecked(QualType ElemTy) {
400 Entries.push_back(PathEntry::ArrayIndex(0));
401
402 MostDerivedType = ElemTy;
403 MostDerivedIsArrayElement = true;
404 // The value in MostDerivedArraySize is undefined in this case. So, set it
405 // to an arbitrary value that's likely to loudly break things if it's
406 // used.
407 MostDerivedArraySize = AssumedSizeForUnsizedArray;
408 MostDerivedPathLength = Entries.size();
409 }
410 /// Update this designator to refer to the given base or member of this
411 /// object.
addDeclUnchecked__anon4717f8730111::SubobjectDesignator412 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
413 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
414
415 // If this isn't a base class, it's a new most-derived object.
416 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
417 MostDerivedType = FD->getType();
418 MostDerivedIsArrayElement = false;
419 MostDerivedArraySize = 0;
420 MostDerivedPathLength = Entries.size();
421 }
422 }
423 /// Update this designator to refer to the given complex component.
addComplexUnchecked__anon4717f8730111::SubobjectDesignator424 void addComplexUnchecked(QualType EltTy, bool Imag) {
425 Entries.push_back(PathEntry::ArrayIndex(Imag));
426
427 // This is technically a most-derived object, though in practice this
428 // is unlikely to matter.
429 MostDerivedType = EltTy;
430 MostDerivedIsArrayElement = true;
431 MostDerivedArraySize = 2;
432 MostDerivedPathLength = Entries.size();
433 }
434 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
435 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
436 const APSInt &N);
437 /// Add N to the address of this subobject.
adjustIndex__anon4717f8730111::SubobjectDesignator438 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
439 if (Invalid || !N) return;
440 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
441 if (isMostDerivedAnUnsizedArray()) {
442 diagnoseUnsizedArrayPointerArithmetic(Info, E);
443 // Can't verify -- trust that the user is doing the right thing (or if
444 // not, trust that the caller will catch the bad behavior).
445 // FIXME: Should we reject if this overflows, at least?
446 Entries.back() = PathEntry::ArrayIndex(
447 Entries.back().getAsArrayIndex() + TruncatedN);
448 return;
449 }
450
451 // [expr.add]p4: For the purposes of these operators, a pointer to a
452 // nonarray object behaves the same as a pointer to the first element of
453 // an array of length one with the type of the object as its element type.
454 bool IsArray = MostDerivedPathLength == Entries.size() &&
455 MostDerivedIsArrayElement;
456 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
457 : (uint64_t)IsOnePastTheEnd;
458 uint64_t ArraySize =
459 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
460
461 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
462 // Calculate the actual index in a wide enough type, so we can include
463 // it in the note.
464 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
465 (llvm::APInt&)N += ArrayIndex;
466 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
467 diagnosePointerArithmetic(Info, E, N);
468 setInvalid();
469 return;
470 }
471
472 ArrayIndex += TruncatedN;
473 assert(ArrayIndex <= ArraySize &&
474 "bounds check succeeded for out-of-bounds index");
475
476 if (IsArray)
477 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
478 else
479 IsOnePastTheEnd = (ArrayIndex != 0);
480 }
481 };
482
483 /// A scope at the end of which an object can need to be destroyed.
484 enum class ScopeKind {
485 Block,
486 FullExpression,
487 Call
488 };
489
490 /// A reference to a particular call and its arguments.
491 struct CallRef {
CallRef__anon4717f8730111::CallRef492 CallRef() : OrigCallee(), CallIndex(0), Version() {}
CallRef__anon4717f8730111::CallRef493 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
494 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
495
operator bool__anon4717f8730111::CallRef496 explicit operator bool() const { return OrigCallee; }
497
498 /// Get the parameter that the caller initialized, corresponding to the
499 /// given parameter in the callee.
getOrigParam__anon4717f8730111::CallRef500 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
501 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
502 : PVD;
503 }
504
505 /// The callee at the point where the arguments were evaluated. This might
506 /// be different from the actual callee (a different redeclaration, or a
507 /// virtual override), but this function's parameters are the ones that
508 /// appear in the parameter map.
509 const FunctionDecl *OrigCallee;
510 /// The call index of the frame that holds the argument values.
511 unsigned CallIndex;
512 /// The version of the parameters corresponding to this call.
513 unsigned Version;
514 };
515
516 /// A stack frame in the constexpr call stack.
517 class CallStackFrame : public interp::Frame {
518 public:
519 EvalInfo &Info;
520
521 /// Parent - The caller of this stack frame.
522 CallStackFrame *Caller;
523
524 /// Callee - The function which was called.
525 const FunctionDecl *Callee;
526
527 /// This - The binding for the this pointer in this call, if any.
528 const LValue *This;
529
530 /// Information on how to find the arguments to this call. Our arguments
531 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
532 /// key and this value as the version.
533 CallRef Arguments;
534
535 /// Source location information about the default argument or default
536 /// initializer expression we're evaluating, if any.
537 CurrentSourceLocExprScope CurSourceLocExprScope;
538
539 // Note that we intentionally use std::map here so that references to
540 // values are stable.
541 typedef std::pair<const void *, unsigned> MapKeyTy;
542 typedef std::map<MapKeyTy, APValue> MapTy;
543 /// Temporaries - Temporary lvalues materialized within this stack frame.
544 MapTy Temporaries;
545
546 /// CallLoc - The location of the call expression for this call.
547 SourceLocation CallLoc;
548
549 /// Index - The call index of this call.
550 unsigned Index;
551
552 /// The stack of integers for tracking version numbers for temporaries.
553 SmallVector<unsigned, 2> TempVersionStack = {1};
554 unsigned CurTempVersion = TempVersionStack.back();
555
getTempVersion() const556 unsigned getTempVersion() const { return TempVersionStack.back(); }
557
pushTempVersion()558 void pushTempVersion() {
559 TempVersionStack.push_back(++CurTempVersion);
560 }
561
popTempVersion()562 void popTempVersion() {
563 TempVersionStack.pop_back();
564 }
565
createCall(const FunctionDecl * Callee)566 CallRef createCall(const FunctionDecl *Callee) {
567 return {Callee, Index, ++CurTempVersion};
568 }
569
570 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
571 // on the overall stack usage of deeply-recursing constexpr evaluations.
572 // (We should cache this map rather than recomputing it repeatedly.)
573 // But let's try this and see how it goes; we can look into caching the map
574 // as a later change.
575
576 /// LambdaCaptureFields - Mapping from captured variables/this to
577 /// corresponding data members in the closure class.
578 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
579 FieldDecl *LambdaThisCaptureField;
580
581 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
582 const FunctionDecl *Callee, const LValue *This,
583 CallRef Arguments);
584 ~CallStackFrame();
585
586 // Return the temporary for Key whose version number is Version.
getTemporary(const void * Key,unsigned Version)587 APValue *getTemporary(const void *Key, unsigned Version) {
588 MapKeyTy KV(Key, Version);
589 auto LB = Temporaries.lower_bound(KV);
590 if (LB != Temporaries.end() && LB->first == KV)
591 return &LB->second;
592 // Pair (Key,Version) wasn't found in the map. Check that no elements
593 // in the map have 'Key' as their key.
594 assert((LB == Temporaries.end() || LB->first.first != Key) &&
595 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
596 "Element with key 'Key' found in map");
597 return nullptr;
598 }
599
600 // Return the current temporary for Key in the map.
getCurrentTemporary(const void * Key)601 APValue *getCurrentTemporary(const void *Key) {
602 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
603 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
604 return &std::prev(UB)->second;
605 return nullptr;
606 }
607
608 // Return the version number of the current temporary for Key.
getCurrentTemporaryVersion(const void * Key) const609 unsigned getCurrentTemporaryVersion(const void *Key) const {
610 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
611 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
612 return std::prev(UB)->first.second;
613 return 0;
614 }
615
616 /// Allocate storage for an object of type T in this stack frame.
617 /// Populates LV with a handle to the created object. Key identifies
618 /// the temporary within the stack frame, and must not be reused without
619 /// bumping the temporary version number.
620 template<typename KeyT>
621 APValue &createTemporary(const KeyT *Key, QualType T,
622 ScopeKind Scope, LValue &LV);
623
624 /// Allocate storage for a parameter of a function call made in this frame.
625 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
626
627 void describe(llvm::raw_ostream &OS) override;
628
getCaller() const629 Frame *getCaller() const override { return Caller; }
getCallLocation() const630 SourceLocation getCallLocation() const override { return CallLoc; }
getCallee() const631 const FunctionDecl *getCallee() const override { return Callee; }
632
isStdFunction() const633 bool isStdFunction() const {
634 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
635 if (DC->isStdNamespace())
636 return true;
637 return false;
638 }
639
640 private:
641 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
642 ScopeKind Scope);
643 };
644
645 /// Temporarily override 'this'.
646 class ThisOverrideRAII {
647 public:
ThisOverrideRAII(CallStackFrame & Frame,const LValue * NewThis,bool Enable)648 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
649 : Frame(Frame), OldThis(Frame.This) {
650 if (Enable)
651 Frame.This = NewThis;
652 }
~ThisOverrideRAII()653 ~ThisOverrideRAII() {
654 Frame.This = OldThis;
655 }
656 private:
657 CallStackFrame &Frame;
658 const LValue *OldThis;
659 };
660 }
661
662 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
663 const LValue &This, QualType ThisType);
664 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
665 APValue::LValueBase LVBase, APValue &Value,
666 QualType T);
667
668 namespace {
669 /// A cleanup, and a flag indicating whether it is lifetime-extended.
670 class Cleanup {
671 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
672 APValue::LValueBase Base;
673 QualType T;
674
675 public:
Cleanup(APValue * Val,APValue::LValueBase Base,QualType T,ScopeKind Scope)676 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
677 ScopeKind Scope)
678 : Value(Val, Scope), Base(Base), T(T) {}
679
680 /// Determine whether this cleanup should be performed at the end of the
681 /// given kind of scope.
isDestroyedAtEndOf(ScopeKind K) const682 bool isDestroyedAtEndOf(ScopeKind K) const {
683 return (int)Value.getInt() >= (int)K;
684 }
endLifetime(EvalInfo & Info,bool RunDestructors)685 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
686 if (RunDestructors) {
687 SourceLocation Loc;
688 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
689 Loc = VD->getLocation();
690 else if (const Expr *E = Base.dyn_cast<const Expr*>())
691 Loc = E->getExprLoc();
692 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
693 }
694 *Value.getPointer() = APValue();
695 return true;
696 }
697
hasSideEffect()698 bool hasSideEffect() {
699 return T.isDestructedType();
700 }
701 };
702
703 /// A reference to an object whose construction we are currently evaluating.
704 struct ObjectUnderConstruction {
705 APValue::LValueBase Base;
706 ArrayRef<APValue::LValuePathEntry> Path;
operator ==(const ObjectUnderConstruction & LHS,const ObjectUnderConstruction & RHS)707 friend bool operator==(const ObjectUnderConstruction &LHS,
708 const ObjectUnderConstruction &RHS) {
709 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
710 }
hash_value(const ObjectUnderConstruction & Obj)711 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
712 return llvm::hash_combine(Obj.Base, Obj.Path);
713 }
714 };
715 enum class ConstructionPhase {
716 None,
717 Bases,
718 AfterBases,
719 AfterFields,
720 Destroying,
721 DestroyingBases
722 };
723 }
724
725 namespace llvm {
726 template<> struct DenseMapInfo<ObjectUnderConstruction> {
727 using Base = DenseMapInfo<APValue::LValueBase>;
getEmptyKeyllvm::DenseMapInfo728 static ObjectUnderConstruction getEmptyKey() {
729 return {Base::getEmptyKey(), {}}; }
getTombstoneKeyllvm::DenseMapInfo730 static ObjectUnderConstruction getTombstoneKey() {
731 return {Base::getTombstoneKey(), {}};
732 }
getHashValuellvm::DenseMapInfo733 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
734 return hash_value(Object);
735 }
isEqualllvm::DenseMapInfo736 static bool isEqual(const ObjectUnderConstruction &LHS,
737 const ObjectUnderConstruction &RHS) {
738 return LHS == RHS;
739 }
740 };
741 }
742
743 namespace {
744 /// A dynamically-allocated heap object.
745 struct DynAlloc {
746 /// The value of this heap-allocated object.
747 APValue Value;
748 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
749 /// or a CallExpr (the latter is for direct calls to operator new inside
750 /// std::allocator<T>::allocate).
751 const Expr *AllocExpr = nullptr;
752
753 enum Kind {
754 New,
755 ArrayNew,
756 StdAllocator
757 };
758
759 /// Get the kind of the allocation. This must match between allocation
760 /// and deallocation.
getKind__anon4717f8730311::DynAlloc761 Kind getKind() const {
762 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
763 return NE->isArray() ? ArrayNew : New;
764 assert(isa<CallExpr>(AllocExpr));
765 return StdAllocator;
766 }
767 };
768
769 struct DynAllocOrder {
operator ()__anon4717f8730311::DynAllocOrder770 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
771 return L.getIndex() < R.getIndex();
772 }
773 };
774
775 /// EvalInfo - This is a private struct used by the evaluator to capture
776 /// information about a subexpression as it is folded. It retains information
777 /// about the AST context, but also maintains information about the folded
778 /// expression.
779 ///
780 /// If an expression could be evaluated, it is still possible it is not a C
781 /// "integer constant expression" or constant expression. If not, this struct
782 /// captures information about how and why not.
783 ///
784 /// One bit of information passed *into* the request for constant folding
785 /// indicates whether the subexpression is "evaluated" or not according to C
786 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
787 /// evaluate the expression regardless of what the RHS is, but C only allows
788 /// certain things in certain situations.
789 class EvalInfo : public interp::State {
790 public:
791 ASTContext &Ctx;
792
793 /// EvalStatus - Contains information about the evaluation.
794 Expr::EvalStatus &EvalStatus;
795
796 /// CurrentCall - The top of the constexpr call stack.
797 CallStackFrame *CurrentCall;
798
799 /// CallStackDepth - The number of calls in the call stack right now.
800 unsigned CallStackDepth;
801
802 /// NextCallIndex - The next call index to assign.
803 unsigned NextCallIndex;
804
805 /// StepsLeft - The remaining number of evaluation steps we're permitted
806 /// to perform. This is essentially a limit for the number of statements
807 /// we will evaluate.
808 unsigned StepsLeft;
809
810 /// Enable the experimental new constant interpreter. If an expression is
811 /// not supported by the interpreter, an error is triggered.
812 bool EnableNewConstInterp;
813
814 /// BottomFrame - The frame in which evaluation started. This must be
815 /// initialized after CurrentCall and CallStackDepth.
816 CallStackFrame BottomFrame;
817
818 /// A stack of values whose lifetimes end at the end of some surrounding
819 /// evaluation frame.
820 llvm::SmallVector<Cleanup, 16> CleanupStack;
821
822 /// EvaluatingDecl - This is the declaration whose initializer is being
823 /// evaluated, if any.
824 APValue::LValueBase EvaluatingDecl;
825
826 enum class EvaluatingDeclKind {
827 None,
828 /// We're evaluating the construction of EvaluatingDecl.
829 Ctor,
830 /// We're evaluating the destruction of EvaluatingDecl.
831 Dtor,
832 };
833 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
834
835 /// EvaluatingDeclValue - This is the value being constructed for the
836 /// declaration whose initializer is being evaluated, if any.
837 APValue *EvaluatingDeclValue;
838
839 /// Set of objects that are currently being constructed.
840 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
841 ObjectsUnderConstruction;
842
843 /// Current heap allocations, along with the location where each was
844 /// allocated. We use std::map here because we need stable addresses
845 /// for the stored APValues.
846 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
847
848 /// The number of heap allocations performed so far in this evaluation.
849 unsigned NumHeapAllocs = 0;
850
851 struct EvaluatingConstructorRAII {
852 EvalInfo &EI;
853 ObjectUnderConstruction Object;
854 bool DidInsert;
EvaluatingConstructorRAII__anon4717f8730311::EvalInfo::EvaluatingConstructorRAII855 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
856 bool HasBases)
857 : EI(EI), Object(Object) {
858 DidInsert =
859 EI.ObjectsUnderConstruction
860 .insert({Object, HasBases ? ConstructionPhase::Bases
861 : ConstructionPhase::AfterBases})
862 .second;
863 }
finishedConstructingBases__anon4717f8730311::EvalInfo::EvaluatingConstructorRAII864 void finishedConstructingBases() {
865 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
866 }
finishedConstructingFields__anon4717f8730311::EvalInfo::EvaluatingConstructorRAII867 void finishedConstructingFields() {
868 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
869 }
~EvaluatingConstructorRAII__anon4717f8730311::EvalInfo::EvaluatingConstructorRAII870 ~EvaluatingConstructorRAII() {
871 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
872 }
873 };
874
875 struct EvaluatingDestructorRAII {
876 EvalInfo &EI;
877 ObjectUnderConstruction Object;
878 bool DidInsert;
EvaluatingDestructorRAII__anon4717f8730311::EvalInfo::EvaluatingDestructorRAII879 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
880 : EI(EI), Object(Object) {
881 DidInsert = EI.ObjectsUnderConstruction
882 .insert({Object, ConstructionPhase::Destroying})
883 .second;
884 }
startedDestroyingBases__anon4717f8730311::EvalInfo::EvaluatingDestructorRAII885 void startedDestroyingBases() {
886 EI.ObjectsUnderConstruction[Object] =
887 ConstructionPhase::DestroyingBases;
888 }
~EvaluatingDestructorRAII__anon4717f8730311::EvalInfo::EvaluatingDestructorRAII889 ~EvaluatingDestructorRAII() {
890 if (DidInsert)
891 EI.ObjectsUnderConstruction.erase(Object);
892 }
893 };
894
895 ConstructionPhase
isEvaluatingCtorDtor(APValue::LValueBase Base,ArrayRef<APValue::LValuePathEntry> Path)896 isEvaluatingCtorDtor(APValue::LValueBase Base,
897 ArrayRef<APValue::LValuePathEntry> Path) {
898 return ObjectsUnderConstruction.lookup({Base, Path});
899 }
900
901 /// If we're currently speculatively evaluating, the outermost call stack
902 /// depth at which we can mutate state, otherwise 0.
903 unsigned SpeculativeEvaluationDepth = 0;
904
905 /// The current array initialization index, if we're performing array
906 /// initialization.
907 uint64_t ArrayInitIndex = -1;
908
909 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
910 /// notes attached to it will also be stored, otherwise they will not be.
911 bool HasActiveDiagnostic;
912
913 /// Have we emitted a diagnostic explaining why we couldn't constant
914 /// fold (not just why it's not strictly a constant expression)?
915 bool HasFoldFailureDiagnostic;
916
917 /// Whether or not we're in a context where the front end requires a
918 /// constant value.
919 bool InConstantContext;
920
921 /// Whether we're checking that an expression is a potential constant
922 /// expression. If so, do not fail on constructs that could become constant
923 /// later on (such as a use of an undefined global).
924 bool CheckingPotentialConstantExpression = false;
925
926 /// Whether we're checking for an expression that has undefined behavior.
927 /// If so, we will produce warnings if we encounter an operation that is
928 /// always undefined.
929 bool CheckingForUndefinedBehavior = false;
930
931 enum EvaluationMode {
932 /// Evaluate as a constant expression. Stop if we find that the expression
933 /// is not a constant expression.
934 EM_ConstantExpression,
935
936 /// Evaluate as a constant expression. Stop if we find that the expression
937 /// is not a constant expression. Some expressions can be retried in the
938 /// optimizer if we don't constant fold them here, but in an unevaluated
939 /// context we try to fold them immediately since the optimizer never
940 /// gets a chance to look at it.
941 EM_ConstantExpressionUnevaluated,
942
943 /// Fold the expression to a constant. Stop if we hit a side-effect that
944 /// we can't model.
945 EM_ConstantFold,
946
947 /// Evaluate in any way we know how. Don't worry about side-effects that
948 /// can't be modeled.
949 EM_IgnoreSideEffects,
950 } EvalMode;
951
952 /// Are we checking whether the expression is a potential constant
953 /// expression?
checkingPotentialConstantExpression() const954 bool checkingPotentialConstantExpression() const override {
955 return CheckingPotentialConstantExpression;
956 }
957
958 /// Are we checking an expression for overflow?
959 // FIXME: We should check for any kind of undefined or suspicious behavior
960 // in such constructs, not just overflow.
checkingForUndefinedBehavior() const961 bool checkingForUndefinedBehavior() const override {
962 return CheckingForUndefinedBehavior;
963 }
964
EvalInfo(const ASTContext & C,Expr::EvalStatus & S,EvaluationMode Mode)965 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
966 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
967 CallStackDepth(0), NextCallIndex(1),
968 StepsLeft(C.getLangOpts().ConstexprStepLimit),
969 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
970 BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
971 EvaluatingDecl((const ValueDecl *)nullptr),
972 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
973 HasFoldFailureDiagnostic(false), InConstantContext(false),
974 EvalMode(Mode) {}
975
~EvalInfo()976 ~EvalInfo() {
977 discardCleanups();
978 }
979
setEvaluatingDecl(APValue::LValueBase Base,APValue & Value,EvaluatingDeclKind EDK=EvaluatingDeclKind::Ctor)980 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
981 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
982 EvaluatingDecl = Base;
983 IsEvaluatingDecl = EDK;
984 EvaluatingDeclValue = &Value;
985 }
986
CheckCallLimit(SourceLocation Loc)987 bool CheckCallLimit(SourceLocation Loc) {
988 // Don't perform any constexpr calls (other than the call we're checking)
989 // when checking a potential constant expression.
990 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
991 return false;
992 if (NextCallIndex == 0) {
993 // NextCallIndex has wrapped around.
994 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
995 return false;
996 }
997 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
998 return true;
999 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1000 << getLangOpts().ConstexprCallDepth;
1001 return false;
1002 }
1003
1004 std::pair<CallStackFrame *, unsigned>
getCallFrameAndDepth(unsigned CallIndex)1005 getCallFrameAndDepth(unsigned CallIndex) {
1006 assert(CallIndex && "no call index in getCallFrameAndDepth");
1007 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1008 // be null in this loop.
1009 unsigned Depth = CallStackDepth;
1010 CallStackFrame *Frame = CurrentCall;
1011 while (Frame->Index > CallIndex) {
1012 Frame = Frame->Caller;
1013 --Depth;
1014 }
1015 if (Frame->Index == CallIndex)
1016 return {Frame, Depth};
1017 return {nullptr, 0};
1018 }
1019
nextStep(const Stmt * S)1020 bool nextStep(const Stmt *S) {
1021 if (!StepsLeft) {
1022 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1023 return false;
1024 }
1025 --StepsLeft;
1026 return true;
1027 }
1028
1029 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1030
lookupDynamicAlloc(DynamicAllocLValue DA)1031 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1032 Optional<DynAlloc*> Result;
1033 auto It = HeapAllocs.find(DA);
1034 if (It != HeapAllocs.end())
1035 Result = &It->second;
1036 return Result;
1037 }
1038
1039 /// Get the allocated storage for the given parameter of the given call.
getParamSlot(CallRef Call,const ParmVarDecl * PVD)1040 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1041 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1042 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1043 : nullptr;
1044 }
1045
1046 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1047 struct StdAllocatorCaller {
1048 unsigned FrameIndex;
1049 QualType ElemType;
operator bool__anon4717f8730311::EvalInfo::StdAllocatorCaller1050 explicit operator bool() const { return FrameIndex != 0; };
1051 };
1052
getStdAllocatorCaller(StringRef FnName) const1053 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1054 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1055 Call = Call->Caller) {
1056 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1057 if (!MD)
1058 continue;
1059 const IdentifierInfo *FnII = MD->getIdentifier();
1060 if (!FnII || !FnII->isStr(FnName))
1061 continue;
1062
1063 const auto *CTSD =
1064 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1065 if (!CTSD)
1066 continue;
1067
1068 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1069 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1070 if (CTSD->isInStdNamespace() && ClassII &&
1071 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1072 TAL[0].getKind() == TemplateArgument::Type)
1073 return {Call->Index, TAL[0].getAsType()};
1074 }
1075
1076 return {};
1077 }
1078
performLifetimeExtension()1079 void performLifetimeExtension() {
1080 // Disable the cleanups for lifetime-extended temporaries.
1081 CleanupStack.erase(std::remove_if(CleanupStack.begin(),
1082 CleanupStack.end(),
1083 [](Cleanup &C) {
1084 return !C.isDestroyedAtEndOf(
1085 ScopeKind::FullExpression);
1086 }),
1087 CleanupStack.end());
1088 }
1089
1090 /// Throw away any remaining cleanups at the end of evaluation. If any
1091 /// cleanups would have had a side-effect, note that as an unmodeled
1092 /// side-effect and return false. Otherwise, return true.
discardCleanups()1093 bool discardCleanups() {
1094 for (Cleanup &C : CleanupStack) {
1095 if (C.hasSideEffect() && !noteSideEffect()) {
1096 CleanupStack.clear();
1097 return false;
1098 }
1099 }
1100 CleanupStack.clear();
1101 return true;
1102 }
1103
1104 private:
getCurrentFrame()1105 interp::Frame *getCurrentFrame() override { return CurrentCall; }
getBottomFrame() const1106 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1107
hasActiveDiagnostic()1108 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
setActiveDiagnostic(bool Flag)1109 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1110
setFoldFailureDiagnostic(bool Flag)1111 void setFoldFailureDiagnostic(bool Flag) override {
1112 HasFoldFailureDiagnostic = Flag;
1113 }
1114
getEvalStatus() const1115 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1116
getCtx() const1117 ASTContext &getCtx() const override { return Ctx; }
1118
1119 // If we have a prior diagnostic, it will be noting that the expression
1120 // isn't a constant expression. This diagnostic is more important,
1121 // unless we require this evaluation to produce a constant expression.
1122 //
1123 // FIXME: We might want to show both diagnostics to the user in
1124 // EM_ConstantFold mode.
hasPriorDiagnostic()1125 bool hasPriorDiagnostic() override {
1126 if (!EvalStatus.Diag->empty()) {
1127 switch (EvalMode) {
1128 case EM_ConstantFold:
1129 case EM_IgnoreSideEffects:
1130 if (!HasFoldFailureDiagnostic)
1131 break;
1132 // We've already failed to fold something. Keep that diagnostic.
1133 LLVM_FALLTHROUGH;
1134 case EM_ConstantExpression:
1135 case EM_ConstantExpressionUnevaluated:
1136 setActiveDiagnostic(false);
1137 return true;
1138 }
1139 }
1140 return false;
1141 }
1142
getCallStackDepth()1143 unsigned getCallStackDepth() override { return CallStackDepth; }
1144
1145 public:
1146 /// Should we continue evaluation after encountering a side-effect that we
1147 /// couldn't model?
keepEvaluatingAfterSideEffect()1148 bool keepEvaluatingAfterSideEffect() {
1149 switch (EvalMode) {
1150 case EM_IgnoreSideEffects:
1151 return true;
1152
1153 case EM_ConstantExpression:
1154 case EM_ConstantExpressionUnevaluated:
1155 case EM_ConstantFold:
1156 // By default, assume any side effect might be valid in some other
1157 // evaluation of this expression from a different context.
1158 return checkingPotentialConstantExpression() ||
1159 checkingForUndefinedBehavior();
1160 }
1161 llvm_unreachable("Missed EvalMode case");
1162 }
1163
1164 /// Note that we have had a side-effect, and determine whether we should
1165 /// keep evaluating.
noteSideEffect()1166 bool noteSideEffect() {
1167 EvalStatus.HasSideEffects = true;
1168 return keepEvaluatingAfterSideEffect();
1169 }
1170
1171 /// Should we continue evaluation after encountering undefined behavior?
keepEvaluatingAfterUndefinedBehavior()1172 bool keepEvaluatingAfterUndefinedBehavior() {
1173 switch (EvalMode) {
1174 case EM_IgnoreSideEffects:
1175 case EM_ConstantFold:
1176 return true;
1177
1178 case EM_ConstantExpression:
1179 case EM_ConstantExpressionUnevaluated:
1180 return checkingForUndefinedBehavior();
1181 }
1182 llvm_unreachable("Missed EvalMode case");
1183 }
1184
1185 /// Note that we hit something that was technically undefined behavior, but
1186 /// that we can evaluate past it (such as signed overflow or floating-point
1187 /// division by zero.)
noteUndefinedBehavior()1188 bool noteUndefinedBehavior() override {
1189 EvalStatus.HasUndefinedBehavior = true;
1190 return keepEvaluatingAfterUndefinedBehavior();
1191 }
1192
1193 /// Should we continue evaluation as much as possible after encountering a
1194 /// construct which can't be reduced to a value?
keepEvaluatingAfterFailure() const1195 bool keepEvaluatingAfterFailure() const override {
1196 if (!StepsLeft)
1197 return false;
1198
1199 switch (EvalMode) {
1200 case EM_ConstantExpression:
1201 case EM_ConstantExpressionUnevaluated:
1202 case EM_ConstantFold:
1203 case EM_IgnoreSideEffects:
1204 return checkingPotentialConstantExpression() ||
1205 checkingForUndefinedBehavior();
1206 }
1207 llvm_unreachable("Missed EvalMode case");
1208 }
1209
1210 /// Notes that we failed to evaluate an expression that other expressions
1211 /// directly depend on, and determine if we should keep evaluating. This
1212 /// should only be called if we actually intend to keep evaluating.
1213 ///
1214 /// Call noteSideEffect() instead if we may be able to ignore the value that
1215 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1216 ///
1217 /// (Foo(), 1) // use noteSideEffect
1218 /// (Foo() || true) // use noteSideEffect
1219 /// Foo() + 1 // use noteFailure
noteFailure()1220 LLVM_NODISCARD bool noteFailure() {
1221 // Failure when evaluating some expression often means there is some
1222 // subexpression whose evaluation was skipped. Therefore, (because we
1223 // don't track whether we skipped an expression when unwinding after an
1224 // evaluation failure) every evaluation failure that bubbles up from a
1225 // subexpression implies that a side-effect has potentially happened. We
1226 // skip setting the HasSideEffects flag to true until we decide to
1227 // continue evaluating after that point, which happens here.
1228 bool KeepGoing = keepEvaluatingAfterFailure();
1229 EvalStatus.HasSideEffects |= KeepGoing;
1230 return KeepGoing;
1231 }
1232
1233 class ArrayInitLoopIndex {
1234 EvalInfo &Info;
1235 uint64_t OuterIndex;
1236
1237 public:
ArrayInitLoopIndex(EvalInfo & Info)1238 ArrayInitLoopIndex(EvalInfo &Info)
1239 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1240 Info.ArrayInitIndex = 0;
1241 }
~ArrayInitLoopIndex()1242 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1243
operator uint64_t&()1244 operator uint64_t&() { return Info.ArrayInitIndex; }
1245 };
1246 };
1247
1248 /// Object used to treat all foldable expressions as constant expressions.
1249 struct FoldConstant {
1250 EvalInfo &Info;
1251 bool Enabled;
1252 bool HadNoPriorDiags;
1253 EvalInfo::EvaluationMode OldMode;
1254
FoldConstant__anon4717f8730311::FoldConstant1255 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1256 : Info(Info),
1257 Enabled(Enabled),
1258 HadNoPriorDiags(Info.EvalStatus.Diag &&
1259 Info.EvalStatus.Diag->empty() &&
1260 !Info.EvalStatus.HasSideEffects),
1261 OldMode(Info.EvalMode) {
1262 if (Enabled)
1263 Info.EvalMode = EvalInfo::EM_ConstantFold;
1264 }
keepDiagnostics__anon4717f8730311::FoldConstant1265 void keepDiagnostics() { Enabled = false; }
~FoldConstant__anon4717f8730311::FoldConstant1266 ~FoldConstant() {
1267 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1268 !Info.EvalStatus.HasSideEffects)
1269 Info.EvalStatus.Diag->clear();
1270 Info.EvalMode = OldMode;
1271 }
1272 };
1273
1274 /// RAII object used to set the current evaluation mode to ignore
1275 /// side-effects.
1276 struct IgnoreSideEffectsRAII {
1277 EvalInfo &Info;
1278 EvalInfo::EvaluationMode OldMode;
IgnoreSideEffectsRAII__anon4717f8730311::IgnoreSideEffectsRAII1279 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1280 : Info(Info), OldMode(Info.EvalMode) {
1281 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1282 }
1283
~IgnoreSideEffectsRAII__anon4717f8730311::IgnoreSideEffectsRAII1284 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1285 };
1286
1287 /// RAII object used to optionally suppress diagnostics and side-effects from
1288 /// a speculative evaluation.
1289 class SpeculativeEvaluationRAII {
1290 EvalInfo *Info = nullptr;
1291 Expr::EvalStatus OldStatus;
1292 unsigned OldSpeculativeEvaluationDepth;
1293
moveFromAndCancel(SpeculativeEvaluationRAII && Other)1294 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1295 Info = Other.Info;
1296 OldStatus = Other.OldStatus;
1297 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1298 Other.Info = nullptr;
1299 }
1300
maybeRestoreState()1301 void maybeRestoreState() {
1302 if (!Info)
1303 return;
1304
1305 Info->EvalStatus = OldStatus;
1306 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1307 }
1308
1309 public:
1310 SpeculativeEvaluationRAII() = default;
1311
SpeculativeEvaluationRAII(EvalInfo & Info,SmallVectorImpl<PartialDiagnosticAt> * NewDiag=nullptr)1312 SpeculativeEvaluationRAII(
1313 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1314 : Info(&Info), OldStatus(Info.EvalStatus),
1315 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1316 Info.EvalStatus.Diag = NewDiag;
1317 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1318 }
1319
1320 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
SpeculativeEvaluationRAII(SpeculativeEvaluationRAII && Other)1321 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1322 moveFromAndCancel(std::move(Other));
1323 }
1324
operator =(SpeculativeEvaluationRAII && Other)1325 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1326 maybeRestoreState();
1327 moveFromAndCancel(std::move(Other));
1328 return *this;
1329 }
1330
~SpeculativeEvaluationRAII()1331 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1332 };
1333
1334 /// RAII object wrapping a full-expression or block scope, and handling
1335 /// the ending of the lifetime of temporaries created within it.
1336 template<ScopeKind Kind>
1337 class ScopeRAII {
1338 EvalInfo &Info;
1339 unsigned OldStackSize;
1340 public:
ScopeRAII(EvalInfo & Info)1341 ScopeRAII(EvalInfo &Info)
1342 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1343 // Push a new temporary version. This is needed to distinguish between
1344 // temporaries created in different iterations of a loop.
1345 Info.CurrentCall->pushTempVersion();
1346 }
destroy(bool RunDestructors=true)1347 bool destroy(bool RunDestructors = true) {
1348 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1349 OldStackSize = -1U;
1350 return OK;
1351 }
~ScopeRAII()1352 ~ScopeRAII() {
1353 if (OldStackSize != -1U)
1354 destroy(false);
1355 // Body moved to a static method to encourage the compiler to inline away
1356 // instances of this class.
1357 Info.CurrentCall->popTempVersion();
1358 }
1359 private:
cleanup(EvalInfo & Info,bool RunDestructors,unsigned OldStackSize)1360 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1361 unsigned OldStackSize) {
1362 assert(OldStackSize <= Info.CleanupStack.size() &&
1363 "running cleanups out of order?");
1364
1365 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1366 // for a full-expression scope.
1367 bool Success = true;
1368 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1369 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1370 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1371 Success = false;
1372 break;
1373 }
1374 }
1375 }
1376
1377 // Compact any retained cleanups.
1378 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1379 if (Kind != ScopeKind::Block)
1380 NewEnd =
1381 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1382 return C.isDestroyedAtEndOf(Kind);
1383 });
1384 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1385 return Success;
1386 }
1387 };
1388 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1389 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1390 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1391 }
1392
checkSubobject(EvalInfo & Info,const Expr * E,CheckSubobjectKind CSK)1393 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1394 CheckSubobjectKind CSK) {
1395 if (Invalid)
1396 return false;
1397 if (isOnePastTheEnd()) {
1398 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1399 << CSK;
1400 setInvalid();
1401 return false;
1402 }
1403 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1404 // must actually be at least one array element; even a VLA cannot have a
1405 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1406 return true;
1407 }
1408
diagnoseUnsizedArrayPointerArithmetic(EvalInfo & Info,const Expr * E)1409 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1410 const Expr *E) {
1411 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1412 // Do not set the designator as invalid: we can represent this situation,
1413 // and correct handling of __builtin_object_size requires us to do so.
1414 }
1415
diagnosePointerArithmetic(EvalInfo & Info,const Expr * E,const APSInt & N)1416 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1417 const Expr *E,
1418 const APSInt &N) {
1419 // If we're complaining, we must be able to statically determine the size of
1420 // the most derived array.
1421 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1422 Info.CCEDiag(E, diag::note_constexpr_array_index)
1423 << N << /*array*/ 0
1424 << static_cast<unsigned>(getMostDerivedArraySize());
1425 else
1426 Info.CCEDiag(E, diag::note_constexpr_array_index)
1427 << N << /*non-array*/ 1;
1428 setInvalid();
1429 }
1430
CallStackFrame(EvalInfo & Info,SourceLocation CallLoc,const FunctionDecl * Callee,const LValue * This,CallRef Call)1431 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1432 const FunctionDecl *Callee, const LValue *This,
1433 CallRef Call)
1434 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1435 Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1436 Info.CurrentCall = this;
1437 ++Info.CallStackDepth;
1438 }
1439
~CallStackFrame()1440 CallStackFrame::~CallStackFrame() {
1441 assert(Info.CurrentCall == this && "calls retired out of order");
1442 --Info.CallStackDepth;
1443 Info.CurrentCall = Caller;
1444 }
1445
isRead(AccessKinds AK)1446 static bool isRead(AccessKinds AK) {
1447 return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1448 }
1449
isModification(AccessKinds AK)1450 static bool isModification(AccessKinds AK) {
1451 switch (AK) {
1452 case AK_Read:
1453 case AK_ReadObjectRepresentation:
1454 case AK_MemberCall:
1455 case AK_DynamicCast:
1456 case AK_TypeId:
1457 return false;
1458 case AK_Assign:
1459 case AK_Increment:
1460 case AK_Decrement:
1461 case AK_Construct:
1462 case AK_Destroy:
1463 return true;
1464 }
1465 llvm_unreachable("unknown access kind");
1466 }
1467
isAnyAccess(AccessKinds AK)1468 static bool isAnyAccess(AccessKinds AK) {
1469 return isRead(AK) || isModification(AK);
1470 }
1471
1472 /// Is this an access per the C++ definition?
isFormalAccess(AccessKinds AK)1473 static bool isFormalAccess(AccessKinds AK) {
1474 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1475 }
1476
1477 /// Is this kind of axcess valid on an indeterminate object value?
isValidIndeterminateAccess(AccessKinds AK)1478 static bool isValidIndeterminateAccess(AccessKinds AK) {
1479 switch (AK) {
1480 case AK_Read:
1481 case AK_Increment:
1482 case AK_Decrement:
1483 // These need the object's value.
1484 return false;
1485
1486 case AK_ReadObjectRepresentation:
1487 case AK_Assign:
1488 case AK_Construct:
1489 case AK_Destroy:
1490 // Construction and destruction don't need the value.
1491 return true;
1492
1493 case AK_MemberCall:
1494 case AK_DynamicCast:
1495 case AK_TypeId:
1496 // These aren't really meaningful on scalars.
1497 return true;
1498 }
1499 llvm_unreachable("unknown access kind");
1500 }
1501
1502 namespace {
1503 struct ComplexValue {
1504 private:
1505 bool IsInt;
1506
1507 public:
1508 APSInt IntReal, IntImag;
1509 APFloat FloatReal, FloatImag;
1510
ComplexValue__anon4717f8730611::ComplexValue1511 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1512
makeComplexFloat__anon4717f8730611::ComplexValue1513 void makeComplexFloat() { IsInt = false; }
isComplexFloat__anon4717f8730611::ComplexValue1514 bool isComplexFloat() const { return !IsInt; }
getComplexFloatReal__anon4717f8730611::ComplexValue1515 APFloat &getComplexFloatReal() { return FloatReal; }
getComplexFloatImag__anon4717f8730611::ComplexValue1516 APFloat &getComplexFloatImag() { return FloatImag; }
1517
makeComplexInt__anon4717f8730611::ComplexValue1518 void makeComplexInt() { IsInt = true; }
isComplexInt__anon4717f8730611::ComplexValue1519 bool isComplexInt() const { return IsInt; }
getComplexIntReal__anon4717f8730611::ComplexValue1520 APSInt &getComplexIntReal() { return IntReal; }
getComplexIntImag__anon4717f8730611::ComplexValue1521 APSInt &getComplexIntImag() { return IntImag; }
1522
moveInto__anon4717f8730611::ComplexValue1523 void moveInto(APValue &v) const {
1524 if (isComplexFloat())
1525 v = APValue(FloatReal, FloatImag);
1526 else
1527 v = APValue(IntReal, IntImag);
1528 }
setFrom__anon4717f8730611::ComplexValue1529 void setFrom(const APValue &v) {
1530 assert(v.isComplexFloat() || v.isComplexInt());
1531 if (v.isComplexFloat()) {
1532 makeComplexFloat();
1533 FloatReal = v.getComplexFloatReal();
1534 FloatImag = v.getComplexFloatImag();
1535 } else {
1536 makeComplexInt();
1537 IntReal = v.getComplexIntReal();
1538 IntImag = v.getComplexIntImag();
1539 }
1540 }
1541 };
1542
1543 struct LValue {
1544 APValue::LValueBase Base;
1545 CharUnits Offset;
1546 SubobjectDesignator Designator;
1547 bool IsNullPtr : 1;
1548 bool InvalidBase : 1;
1549
getLValueBase__anon4717f8730611::LValue1550 const APValue::LValueBase getLValueBase() const { return Base; }
getLValueOffset__anon4717f8730611::LValue1551 CharUnits &getLValueOffset() { return Offset; }
getLValueOffset__anon4717f8730611::LValue1552 const CharUnits &getLValueOffset() const { return Offset; }
getLValueDesignator__anon4717f8730611::LValue1553 SubobjectDesignator &getLValueDesignator() { return Designator; }
getLValueDesignator__anon4717f8730611::LValue1554 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
isNullPointer__anon4717f8730611::LValue1555 bool isNullPointer() const { return IsNullPtr;}
1556
getLValueCallIndex__anon4717f8730611::LValue1557 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
getLValueVersion__anon4717f8730611::LValue1558 unsigned getLValueVersion() const { return Base.getVersion(); }
1559
moveInto__anon4717f8730611::LValue1560 void moveInto(APValue &V) const {
1561 if (Designator.Invalid)
1562 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1563 else {
1564 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1565 V = APValue(Base, Offset, Designator.Entries,
1566 Designator.IsOnePastTheEnd, IsNullPtr);
1567 }
1568 }
setFrom__anon4717f8730611::LValue1569 void setFrom(ASTContext &Ctx, const APValue &V) {
1570 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1571 Base = V.getLValueBase();
1572 Offset = V.getLValueOffset();
1573 InvalidBase = false;
1574 Designator = SubobjectDesignator(Ctx, V);
1575 IsNullPtr = V.isNullPointer();
1576 }
1577
set__anon4717f8730611::LValue1578 void set(APValue::LValueBase B, bool BInvalid = false) {
1579 #ifndef NDEBUG
1580 // We only allow a few types of invalid bases. Enforce that here.
1581 if (BInvalid) {
1582 const auto *E = B.get<const Expr *>();
1583 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1584 "Unexpected type of invalid base");
1585 }
1586 #endif
1587
1588 Base = B;
1589 Offset = CharUnits::fromQuantity(0);
1590 InvalidBase = BInvalid;
1591 Designator = SubobjectDesignator(getType(B));
1592 IsNullPtr = false;
1593 }
1594
setNull__anon4717f8730611::LValue1595 void setNull(ASTContext &Ctx, QualType PointerTy) {
1596 Base = (const ValueDecl *)nullptr;
1597 Offset =
1598 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1599 InvalidBase = false;
1600 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1601 IsNullPtr = true;
1602 }
1603
setInvalid__anon4717f8730611::LValue1604 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1605 set(B, true);
1606 }
1607
toString__anon4717f8730611::LValue1608 std::string toString(ASTContext &Ctx, QualType T) const {
1609 APValue Printable;
1610 moveInto(Printable);
1611 return Printable.getAsString(Ctx, T);
1612 }
1613
1614 private:
1615 // Check that this LValue is not based on a null pointer. If it is, produce
1616 // a diagnostic and mark the designator as invalid.
1617 template <typename GenDiagType>
checkNullPointerDiagnosingWith__anon4717f8730611::LValue1618 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1619 if (Designator.Invalid)
1620 return false;
1621 if (IsNullPtr) {
1622 GenDiag();
1623 Designator.setInvalid();
1624 return false;
1625 }
1626 return true;
1627 }
1628
1629 public:
checkNullPointer__anon4717f8730611::LValue1630 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1631 CheckSubobjectKind CSK) {
1632 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1633 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1634 });
1635 }
1636
checkNullPointerForFoldAccess__anon4717f8730611::LValue1637 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1638 AccessKinds AK) {
1639 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1640 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1641 });
1642 }
1643
1644 // Check this LValue refers to an object. If not, set the designator to be
1645 // invalid and emit a diagnostic.
checkSubobject__anon4717f8730611::LValue1646 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1647 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1648 Designator.checkSubobject(Info, E, CSK);
1649 }
1650
addDecl__anon4717f8730611::LValue1651 void addDecl(EvalInfo &Info, const Expr *E,
1652 const Decl *D, bool Virtual = false) {
1653 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1654 Designator.addDeclUnchecked(D, Virtual);
1655 }
addUnsizedArray__anon4717f8730611::LValue1656 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1657 if (!Designator.Entries.empty()) {
1658 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1659 Designator.setInvalid();
1660 return;
1661 }
1662 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1663 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1664 Designator.FirstEntryIsAnUnsizedArray = true;
1665 Designator.addUnsizedArrayUnchecked(ElemTy);
1666 }
1667 }
addArray__anon4717f8730611::LValue1668 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1669 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1670 Designator.addArrayUnchecked(CAT);
1671 }
addComplex__anon4717f8730611::LValue1672 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1673 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1674 Designator.addComplexUnchecked(EltTy, Imag);
1675 }
clearIsNullPointer__anon4717f8730611::LValue1676 void clearIsNullPointer() {
1677 IsNullPtr = false;
1678 }
adjustOffsetAndIndex__anon4717f8730611::LValue1679 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1680 const APSInt &Index, CharUnits ElementSize) {
1681 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1682 // but we're not required to diagnose it and it's valid in C++.)
1683 if (!Index)
1684 return;
1685
1686 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1687 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1688 // offsets.
1689 uint64_t Offset64 = Offset.getQuantity();
1690 uint64_t ElemSize64 = ElementSize.getQuantity();
1691 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1692 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1693
1694 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1695 Designator.adjustIndex(Info, E, Index);
1696 clearIsNullPointer();
1697 }
adjustOffset__anon4717f8730611::LValue1698 void adjustOffset(CharUnits N) {
1699 Offset += N;
1700 if (N.getQuantity())
1701 clearIsNullPointer();
1702 }
1703 };
1704
1705 struct MemberPtr {
MemberPtr__anon4717f8730611::MemberPtr1706 MemberPtr() {}
MemberPtr__anon4717f8730611::MemberPtr1707 explicit MemberPtr(const ValueDecl *Decl) :
1708 DeclAndIsDerivedMember(Decl, false), Path() {}
1709
1710 /// The member or (direct or indirect) field referred to by this member
1711 /// pointer, or 0 if this is a null member pointer.
getDecl__anon4717f8730611::MemberPtr1712 const ValueDecl *getDecl() const {
1713 return DeclAndIsDerivedMember.getPointer();
1714 }
1715 /// Is this actually a member of some type derived from the relevant class?
isDerivedMember__anon4717f8730611::MemberPtr1716 bool isDerivedMember() const {
1717 return DeclAndIsDerivedMember.getInt();
1718 }
1719 /// Get the class which the declaration actually lives in.
getContainingRecord__anon4717f8730611::MemberPtr1720 const CXXRecordDecl *getContainingRecord() const {
1721 return cast<CXXRecordDecl>(
1722 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1723 }
1724
moveInto__anon4717f8730611::MemberPtr1725 void moveInto(APValue &V) const {
1726 V = APValue(getDecl(), isDerivedMember(), Path);
1727 }
setFrom__anon4717f8730611::MemberPtr1728 void setFrom(const APValue &V) {
1729 assert(V.isMemberPointer());
1730 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1731 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1732 Path.clear();
1733 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1734 Path.insert(Path.end(), P.begin(), P.end());
1735 }
1736
1737 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1738 /// whether the member is a member of some class derived from the class type
1739 /// of the member pointer.
1740 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1741 /// Path - The path of base/derived classes from the member declaration's
1742 /// class (exclusive) to the class type of the member pointer (inclusive).
1743 SmallVector<const CXXRecordDecl*, 4> Path;
1744
1745 /// Perform a cast towards the class of the Decl (either up or down the
1746 /// hierarchy).
castBack__anon4717f8730611::MemberPtr1747 bool castBack(const CXXRecordDecl *Class) {
1748 assert(!Path.empty());
1749 const CXXRecordDecl *Expected;
1750 if (Path.size() >= 2)
1751 Expected = Path[Path.size() - 2];
1752 else
1753 Expected = getContainingRecord();
1754 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1755 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1756 // if B does not contain the original member and is not a base or
1757 // derived class of the class containing the original member, the result
1758 // of the cast is undefined.
1759 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1760 // (D::*). We consider that to be a language defect.
1761 return false;
1762 }
1763 Path.pop_back();
1764 return true;
1765 }
1766 /// Perform a base-to-derived member pointer cast.
castToDerived__anon4717f8730611::MemberPtr1767 bool castToDerived(const CXXRecordDecl *Derived) {
1768 if (!getDecl())
1769 return true;
1770 if (!isDerivedMember()) {
1771 Path.push_back(Derived);
1772 return true;
1773 }
1774 if (!castBack(Derived))
1775 return false;
1776 if (Path.empty())
1777 DeclAndIsDerivedMember.setInt(false);
1778 return true;
1779 }
1780 /// Perform a derived-to-base member pointer cast.
castToBase__anon4717f8730611::MemberPtr1781 bool castToBase(const CXXRecordDecl *Base) {
1782 if (!getDecl())
1783 return true;
1784 if (Path.empty())
1785 DeclAndIsDerivedMember.setInt(true);
1786 if (isDerivedMember()) {
1787 Path.push_back(Base);
1788 return true;
1789 }
1790 return castBack(Base);
1791 }
1792 };
1793
1794 /// Compare two member pointers, which are assumed to be of the same type.
operator ==(const MemberPtr & LHS,const MemberPtr & RHS)1795 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1796 if (!LHS.getDecl() || !RHS.getDecl())
1797 return !LHS.getDecl() && !RHS.getDecl();
1798 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1799 return false;
1800 return LHS.Path == RHS.Path;
1801 }
1802 }
1803
1804 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1805 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1806 const LValue &This, const Expr *E,
1807 bool AllowNonLiteralTypes = false);
1808 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1809 bool InvalidBaseOK = false);
1810 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1811 bool InvalidBaseOK = false);
1812 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1813 EvalInfo &Info);
1814 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1815 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1816 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1817 EvalInfo &Info);
1818 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1819 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1820 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1821 EvalInfo &Info);
1822 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1823
1824 /// Evaluate an integer or fixed point expression into an APResult.
1825 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1826 EvalInfo &Info);
1827
1828 /// Evaluate only a fixed point expression into an APResult.
1829 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1830 EvalInfo &Info);
1831
1832 //===----------------------------------------------------------------------===//
1833 // Misc utilities
1834 //===----------------------------------------------------------------------===//
1835
1836 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1837 /// preserving its value (by extending by up to one bit as needed).
negateAsSigned(APSInt & Int)1838 static void negateAsSigned(APSInt &Int) {
1839 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1840 Int = Int.extend(Int.getBitWidth() + 1);
1841 Int.setIsSigned(true);
1842 }
1843 Int = -Int;
1844 }
1845
1846 template<typename KeyT>
createTemporary(const KeyT * Key,QualType T,ScopeKind Scope,LValue & LV)1847 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1848 ScopeKind Scope, LValue &LV) {
1849 unsigned Version = getTempVersion();
1850 APValue::LValueBase Base(Key, Index, Version);
1851 LV.set(Base);
1852 return createLocal(Base, Key, T, Scope);
1853 }
1854
1855 /// Allocate storage for a parameter of a function call made in this frame.
createParam(CallRef Args,const ParmVarDecl * PVD,LValue & LV)1856 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1857 LValue &LV) {
1858 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1859 APValue::LValueBase Base(PVD, Index, Args.Version);
1860 LV.set(Base);
1861 // We always destroy parameters at the end of the call, even if we'd allow
1862 // them to live to the end of the full-expression at runtime, in order to
1863 // give portable results and match other compilers.
1864 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1865 }
1866
createLocal(APValue::LValueBase Base,const void * Key,QualType T,ScopeKind Scope)1867 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1868 QualType T, ScopeKind Scope) {
1869 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1870 unsigned Version = Base.getVersion();
1871 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1872 assert(Result.isAbsent() && "local created multiple times");
1873
1874 // If we're creating a local immediately in the operand of a speculative
1875 // evaluation, don't register a cleanup to be run outside the speculative
1876 // evaluation context, since we won't actually be able to initialize this
1877 // object.
1878 if (Index <= Info.SpeculativeEvaluationDepth) {
1879 if (T.isDestructedType())
1880 Info.noteSideEffect();
1881 } else {
1882 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1883 }
1884 return Result;
1885 }
1886
createHeapAlloc(const Expr * E,QualType T,LValue & LV)1887 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1888 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1889 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1890 return nullptr;
1891 }
1892
1893 DynamicAllocLValue DA(NumHeapAllocs++);
1894 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1895 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1896 std::forward_as_tuple(DA), std::tuple<>());
1897 assert(Result.second && "reused a heap alloc index?");
1898 Result.first->second.AllocExpr = E;
1899 return &Result.first->second.Value;
1900 }
1901
1902 /// Produce a string describing the given constexpr call.
describe(raw_ostream & Out)1903 void CallStackFrame::describe(raw_ostream &Out) {
1904 unsigned ArgIndex = 0;
1905 bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1906 !isa<CXXConstructorDecl>(Callee) &&
1907 cast<CXXMethodDecl>(Callee)->isInstance();
1908
1909 if (!IsMemberCall)
1910 Out << *Callee << '(';
1911
1912 if (This && IsMemberCall) {
1913 APValue Val;
1914 This->moveInto(Val);
1915 Val.printPretty(Out, Info.Ctx,
1916 This->Designator.MostDerivedType);
1917 // FIXME: Add parens around Val if needed.
1918 Out << "->" << *Callee << '(';
1919 IsMemberCall = false;
1920 }
1921
1922 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1923 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1924 if (ArgIndex > (unsigned)IsMemberCall)
1925 Out << ", ";
1926
1927 const ParmVarDecl *Param = *I;
1928 APValue *V = Info.getParamSlot(Arguments, Param);
1929 if (V)
1930 V->printPretty(Out, Info.Ctx, Param->getType());
1931 else
1932 Out << "<...>";
1933
1934 if (ArgIndex == 0 && IsMemberCall)
1935 Out << "->" << *Callee << '(';
1936 }
1937
1938 Out << ')';
1939 }
1940
1941 /// Evaluate an expression to see if it had side-effects, and discard its
1942 /// result.
1943 /// \return \c true if the caller should keep evaluating.
EvaluateIgnoredValue(EvalInfo & Info,const Expr * E)1944 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1945 APValue Scratch;
1946 if (!Evaluate(Scratch, Info, E))
1947 // We don't need the value, but we might have skipped a side effect here.
1948 return Info.noteSideEffect();
1949 return true;
1950 }
1951
1952 /// Should this call expression be treated as a string literal?
IsStringLiteralCall(const CallExpr * E)1953 static bool IsStringLiteralCall(const CallExpr *E) {
1954 unsigned Builtin = E->getBuiltinCallee();
1955 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1956 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1957 }
1958
IsGlobalLValue(APValue::LValueBase B)1959 static bool IsGlobalLValue(APValue::LValueBase B) {
1960 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1961 // constant expression of pointer type that evaluates to...
1962
1963 // ... a null pointer value, or a prvalue core constant expression of type
1964 // std::nullptr_t.
1965 if (!B) return true;
1966
1967 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1968 // ... the address of an object with static storage duration,
1969 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1970 return VD->hasGlobalStorage();
1971 if (isa<TemplateParamObjectDecl>(D))
1972 return true;
1973 // ... the address of a function,
1974 // ... the address of a GUID [MS extension],
1975 return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D);
1976 }
1977
1978 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1979 return true;
1980
1981 const Expr *E = B.get<const Expr*>();
1982 switch (E->getStmtClass()) {
1983 default:
1984 return false;
1985 case Expr::CompoundLiteralExprClass: {
1986 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1987 return CLE->isFileScope() && CLE->isLValue();
1988 }
1989 case Expr::MaterializeTemporaryExprClass:
1990 // A materialized temporary might have been lifetime-extended to static
1991 // storage duration.
1992 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1993 // A string literal has static storage duration.
1994 case Expr::StringLiteralClass:
1995 case Expr::PredefinedExprClass:
1996 case Expr::ObjCStringLiteralClass:
1997 case Expr::ObjCEncodeExprClass:
1998 return true;
1999 case Expr::ObjCBoxedExprClass:
2000 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2001 case Expr::CallExprClass:
2002 return IsStringLiteralCall(cast<CallExpr>(E));
2003 // For GCC compatibility, &&label has static storage duration.
2004 case Expr::AddrLabelExprClass:
2005 return true;
2006 // A Block literal expression may be used as the initialization value for
2007 // Block variables at global or local static scope.
2008 case Expr::BlockExprClass:
2009 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2010 case Expr::ImplicitValueInitExprClass:
2011 // FIXME:
2012 // We can never form an lvalue with an implicit value initialization as its
2013 // base through expression evaluation, so these only appear in one case: the
2014 // implicit variable declaration we invent when checking whether a constexpr
2015 // constructor can produce a constant expression. We must assume that such
2016 // an expression might be a global lvalue.
2017 return true;
2018 }
2019 }
2020
GetLValueBaseDecl(const LValue & LVal)2021 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2022 return LVal.Base.dyn_cast<const ValueDecl*>();
2023 }
2024
IsLiteralLValue(const LValue & Value)2025 static bool IsLiteralLValue(const LValue &Value) {
2026 if (Value.getLValueCallIndex())
2027 return false;
2028 const Expr *E = Value.Base.dyn_cast<const Expr*>();
2029 return E && !isa<MaterializeTemporaryExpr>(E);
2030 }
2031
IsWeakLValue(const LValue & Value)2032 static bool IsWeakLValue(const LValue &Value) {
2033 const ValueDecl *Decl = GetLValueBaseDecl(Value);
2034 return Decl && Decl->isWeak();
2035 }
2036
isZeroSized(const LValue & Value)2037 static bool isZeroSized(const LValue &Value) {
2038 const ValueDecl *Decl = GetLValueBaseDecl(Value);
2039 if (Decl && isa<VarDecl>(Decl)) {
2040 QualType Ty = Decl->getType();
2041 if (Ty->isArrayType())
2042 return Ty->isIncompleteType() ||
2043 Decl->getASTContext().getTypeSize(Ty) == 0;
2044 }
2045 return false;
2046 }
2047
HasSameBase(const LValue & A,const LValue & B)2048 static bool HasSameBase(const LValue &A, const LValue &B) {
2049 if (!A.getLValueBase())
2050 return !B.getLValueBase();
2051 if (!B.getLValueBase())
2052 return false;
2053
2054 if (A.getLValueBase().getOpaqueValue() !=
2055 B.getLValueBase().getOpaqueValue())
2056 return false;
2057
2058 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2059 A.getLValueVersion() == B.getLValueVersion();
2060 }
2061
NoteLValueLocation(EvalInfo & Info,APValue::LValueBase Base)2062 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2063 assert(Base && "no location for a null lvalue");
2064 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2065
2066 // For a parameter, find the corresponding call stack frame (if it still
2067 // exists), and point at the parameter of the function definition we actually
2068 // invoked.
2069 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2070 unsigned Idx = PVD->getFunctionScopeIndex();
2071 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2072 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2073 F->Arguments.Version == Base.getVersion() && F->Callee &&
2074 Idx < F->Callee->getNumParams()) {
2075 VD = F->Callee->getParamDecl(Idx);
2076 break;
2077 }
2078 }
2079 }
2080
2081 if (VD)
2082 Info.Note(VD->getLocation(), diag::note_declared_at);
2083 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2084 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2085 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2086 // FIXME: Produce a note for dangling pointers too.
2087 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2088 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2089 diag::note_constexpr_dynamic_alloc_here);
2090 }
2091 // We have no information to show for a typeid(T) object.
2092 }
2093
2094 enum class CheckEvaluationResultKind {
2095 ConstantExpression,
2096 FullyInitialized,
2097 };
2098
2099 /// Materialized temporaries that we've already checked to determine if they're
2100 /// initializsed by a constant expression.
2101 using CheckedTemporaries =
2102 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2103
2104 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2105 EvalInfo &Info, SourceLocation DiagLoc,
2106 QualType Type, const APValue &Value,
2107 ConstantExprKind Kind,
2108 SourceLocation SubobjectLoc,
2109 CheckedTemporaries &CheckedTemps);
2110
2111 /// Check that this reference or pointer core constant expression is a valid
2112 /// value for an address or reference constant expression. Return true if we
2113 /// can fold this expression, whether or not it's a constant expression.
CheckLValueConstantExpression(EvalInfo & Info,SourceLocation Loc,QualType Type,const LValue & LVal,ConstantExprKind Kind,CheckedTemporaries & CheckedTemps)2114 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2115 QualType Type, const LValue &LVal,
2116 ConstantExprKind Kind,
2117 CheckedTemporaries &CheckedTemps) {
2118 bool IsReferenceType = Type->isReferenceType();
2119
2120 APValue::LValueBase Base = LVal.getLValueBase();
2121 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2122
2123 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2124 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2125
2126 // Additional restrictions apply in a template argument. We only enforce the
2127 // C++20 restrictions here; additional syntactic and semantic restrictions
2128 // are applied elsewhere.
2129 if (isTemplateArgument(Kind)) {
2130 int InvalidBaseKind = -1;
2131 StringRef Ident;
2132 if (Base.is<TypeInfoLValue>())
2133 InvalidBaseKind = 0;
2134 else if (isa_and_nonnull<StringLiteral>(BaseE))
2135 InvalidBaseKind = 1;
2136 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2137 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2138 InvalidBaseKind = 2;
2139 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2140 InvalidBaseKind = 3;
2141 Ident = PE->getIdentKindName();
2142 }
2143
2144 if (InvalidBaseKind != -1) {
2145 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2146 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2147 << Ident;
2148 return false;
2149 }
2150 }
2151
2152 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2153 if (FD->isConsteval()) {
2154 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2155 << !Type->isAnyPointerType();
2156 Info.Note(FD->getLocation(), diag::note_declared_at);
2157 return false;
2158 }
2159 }
2160
2161 // Check that the object is a global. Note that the fake 'this' object we
2162 // manufacture when checking potential constant expressions is conservatively
2163 // assumed to be global here.
2164 if (!IsGlobalLValue(Base)) {
2165 if (Info.getLangOpts().CPlusPlus11) {
2166 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2167 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2168 << IsReferenceType << !Designator.Entries.empty()
2169 << !!VD << VD;
2170
2171 auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2172 if (VarD && VarD->isConstexpr()) {
2173 // Non-static local constexpr variables have unintuitive semantics:
2174 // constexpr int a = 1;
2175 // constexpr const int *p = &a;
2176 // ... is invalid because the address of 'a' is not constant. Suggest
2177 // adding a 'static' in this case.
2178 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2179 << VarD
2180 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2181 } else {
2182 NoteLValueLocation(Info, Base);
2183 }
2184 } else {
2185 Info.FFDiag(Loc);
2186 }
2187 // Don't allow references to temporaries to escape.
2188 return false;
2189 }
2190 assert((Info.checkingPotentialConstantExpression() ||
2191 LVal.getLValueCallIndex() == 0) &&
2192 "have call index for global lvalue");
2193
2194 if (Base.is<DynamicAllocLValue>()) {
2195 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2196 << IsReferenceType << !Designator.Entries.empty();
2197 NoteLValueLocation(Info, Base);
2198 return false;
2199 }
2200
2201 if (BaseVD) {
2202 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2203 // Check if this is a thread-local variable.
2204 if (Var->getTLSKind())
2205 // FIXME: Diagnostic!
2206 return false;
2207
2208 // A dllimport variable never acts like a constant, unless we're
2209 // evaluating a value for use only in name mangling.
2210 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2211 // FIXME: Diagnostic!
2212 return false;
2213 }
2214 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2215 // __declspec(dllimport) must be handled very carefully:
2216 // We must never initialize an expression with the thunk in C++.
2217 // Doing otherwise would allow the same id-expression to yield
2218 // different addresses for the same function in different translation
2219 // units. However, this means that we must dynamically initialize the
2220 // expression with the contents of the import address table at runtime.
2221 //
2222 // The C language has no notion of ODR; furthermore, it has no notion of
2223 // dynamic initialization. This means that we are permitted to
2224 // perform initialization with the address of the thunk.
2225 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2226 FD->hasAttr<DLLImportAttr>())
2227 // FIXME: Diagnostic!
2228 return false;
2229 }
2230 } else if (const auto *MTE =
2231 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2232 if (CheckedTemps.insert(MTE).second) {
2233 QualType TempType = getType(Base);
2234 if (TempType.isDestructedType()) {
2235 Info.FFDiag(MTE->getExprLoc(),
2236 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2237 << TempType;
2238 return false;
2239 }
2240
2241 APValue *V = MTE->getOrCreateValue(false);
2242 assert(V && "evasluation result refers to uninitialised temporary");
2243 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2244 Info, MTE->getExprLoc(), TempType, *V,
2245 Kind, SourceLocation(), CheckedTemps))
2246 return false;
2247 }
2248 }
2249
2250 // Allow address constant expressions to be past-the-end pointers. This is
2251 // an extension: the standard requires them to point to an object.
2252 if (!IsReferenceType)
2253 return true;
2254
2255 // A reference constant expression must refer to an object.
2256 if (!Base) {
2257 // FIXME: diagnostic
2258 Info.CCEDiag(Loc);
2259 return true;
2260 }
2261
2262 // Does this refer one past the end of some object?
2263 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2264 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2265 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2266 NoteLValueLocation(Info, Base);
2267 }
2268
2269 return true;
2270 }
2271
2272 /// Member pointers are constant expressions unless they point to a
2273 /// non-virtual dllimport member function.
CheckMemberPointerConstantExpression(EvalInfo & Info,SourceLocation Loc,QualType Type,const APValue & Value,ConstantExprKind Kind)2274 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2275 SourceLocation Loc,
2276 QualType Type,
2277 const APValue &Value,
2278 ConstantExprKind Kind) {
2279 const ValueDecl *Member = Value.getMemberPointerDecl();
2280 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2281 if (!FD)
2282 return true;
2283 if (FD->isConsteval()) {
2284 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2285 Info.Note(FD->getLocation(), diag::note_declared_at);
2286 return false;
2287 }
2288 return isForManglingOnly(Kind) || FD->isVirtual() ||
2289 !FD->hasAttr<DLLImportAttr>();
2290 }
2291
2292 /// Check that this core constant expression is of literal type, and if not,
2293 /// produce an appropriate diagnostic.
CheckLiteralType(EvalInfo & Info,const Expr * E,const LValue * This=nullptr)2294 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2295 const LValue *This = nullptr) {
2296 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2297 return true;
2298
2299 // C++1y: A constant initializer for an object o [...] may also invoke
2300 // constexpr constructors for o and its subobjects even if those objects
2301 // are of non-literal class types.
2302 //
2303 // C++11 missed this detail for aggregates, so classes like this:
2304 // struct foo_t { union { int i; volatile int j; } u; };
2305 // are not (obviously) initializable like so:
2306 // __attribute__((__require_constant_initialization__))
2307 // static const foo_t x = {{0}};
2308 // because "i" is a subobject with non-literal initialization (due to the
2309 // volatile member of the union). See:
2310 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2311 // Therefore, we use the C++1y behavior.
2312 if (This && Info.EvaluatingDecl == This->getLValueBase())
2313 return true;
2314
2315 // Prvalue constant expressions must be of literal types.
2316 if (Info.getLangOpts().CPlusPlus11)
2317 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2318 << E->getType();
2319 else
2320 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2321 return false;
2322 }
2323
CheckEvaluationResult(CheckEvaluationResultKind CERK,EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value,ConstantExprKind Kind,SourceLocation SubobjectLoc,CheckedTemporaries & CheckedTemps)2324 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2325 EvalInfo &Info, SourceLocation DiagLoc,
2326 QualType Type, const APValue &Value,
2327 ConstantExprKind Kind,
2328 SourceLocation SubobjectLoc,
2329 CheckedTemporaries &CheckedTemps) {
2330 if (!Value.hasValue()) {
2331 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2332 << true << Type;
2333 if (SubobjectLoc.isValid())
2334 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2335 return false;
2336 }
2337
2338 // We allow _Atomic(T) to be initialized from anything that T can be
2339 // initialized from.
2340 if (const AtomicType *AT = Type->getAs<AtomicType>())
2341 Type = AT->getValueType();
2342
2343 // Core issue 1454: For a literal constant expression of array or class type,
2344 // each subobject of its value shall have been initialized by a constant
2345 // expression.
2346 if (Value.isArray()) {
2347 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2348 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2349 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2350 Value.getArrayInitializedElt(I), Kind,
2351 SubobjectLoc, CheckedTemps))
2352 return false;
2353 }
2354 if (!Value.hasArrayFiller())
2355 return true;
2356 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2357 Value.getArrayFiller(), Kind, SubobjectLoc,
2358 CheckedTemps);
2359 }
2360 if (Value.isUnion() && Value.getUnionField()) {
2361 return CheckEvaluationResult(
2362 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2363 Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2364 CheckedTemps);
2365 }
2366 if (Value.isStruct()) {
2367 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2368 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2369 unsigned BaseIndex = 0;
2370 for (const CXXBaseSpecifier &BS : CD->bases()) {
2371 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2372 Value.getStructBase(BaseIndex), Kind,
2373 BS.getBeginLoc(), CheckedTemps))
2374 return false;
2375 ++BaseIndex;
2376 }
2377 }
2378 for (const auto *I : RD->fields()) {
2379 if (I->isUnnamedBitfield())
2380 continue;
2381
2382 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2383 Value.getStructField(I->getFieldIndex()),
2384 Kind, I->getLocation(), CheckedTemps))
2385 return false;
2386 }
2387 }
2388
2389 if (Value.isLValue() &&
2390 CERK == CheckEvaluationResultKind::ConstantExpression) {
2391 LValue LVal;
2392 LVal.setFrom(Info.Ctx, Value);
2393 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2394 CheckedTemps);
2395 }
2396
2397 if (Value.isMemberPointer() &&
2398 CERK == CheckEvaluationResultKind::ConstantExpression)
2399 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2400
2401 // Everything else is fine.
2402 return true;
2403 }
2404
2405 /// Check that this core constant expression value is a valid value for a
2406 /// constant expression. If not, report an appropriate diagnostic. Does not
2407 /// check that the expression is of literal type.
CheckConstantExpression(EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value,ConstantExprKind Kind)2408 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2409 QualType Type, const APValue &Value,
2410 ConstantExprKind Kind) {
2411 // Nothing to check for a constant expression of type 'cv void'.
2412 if (Type->isVoidType())
2413 return true;
2414
2415 CheckedTemporaries CheckedTemps;
2416 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2417 Info, DiagLoc, Type, Value, Kind,
2418 SourceLocation(), CheckedTemps);
2419 }
2420
2421 /// Check that this evaluated value is fully-initialized and can be loaded by
2422 /// an lvalue-to-rvalue conversion.
CheckFullyInitialized(EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value)2423 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2424 QualType Type, const APValue &Value) {
2425 CheckedTemporaries CheckedTemps;
2426 return CheckEvaluationResult(
2427 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2428 ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2429 }
2430
2431 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2432 /// "the allocated storage is deallocated within the evaluation".
CheckMemoryLeaks(EvalInfo & Info)2433 static bool CheckMemoryLeaks(EvalInfo &Info) {
2434 if (!Info.HeapAllocs.empty()) {
2435 // We can still fold to a constant despite a compile-time memory leak,
2436 // so long as the heap allocation isn't referenced in the result (we check
2437 // that in CheckConstantExpression).
2438 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2439 diag::note_constexpr_memory_leak)
2440 << unsigned(Info.HeapAllocs.size() - 1);
2441 }
2442 return true;
2443 }
2444
EvalPointerValueAsBool(const APValue & Value,bool & Result)2445 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2446 // A null base expression indicates a null pointer. These are always
2447 // evaluatable, and they are false unless the offset is zero.
2448 if (!Value.getLValueBase()) {
2449 Result = !Value.getLValueOffset().isZero();
2450 return true;
2451 }
2452
2453 // We have a non-null base. These are generally known to be true, but if it's
2454 // a weak declaration it can be null at runtime.
2455 Result = true;
2456 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2457 return !Decl || !Decl->isWeak();
2458 }
2459
HandleConversionToBool(const APValue & Val,bool & Result)2460 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2461 switch (Val.getKind()) {
2462 case APValue::None:
2463 case APValue::Indeterminate:
2464 return false;
2465 case APValue::Int:
2466 Result = Val.getInt().getBoolValue();
2467 return true;
2468 case APValue::FixedPoint:
2469 Result = Val.getFixedPoint().getBoolValue();
2470 return true;
2471 case APValue::Float:
2472 Result = !Val.getFloat().isZero();
2473 return true;
2474 case APValue::ComplexInt:
2475 Result = Val.getComplexIntReal().getBoolValue() ||
2476 Val.getComplexIntImag().getBoolValue();
2477 return true;
2478 case APValue::ComplexFloat:
2479 Result = !Val.getComplexFloatReal().isZero() ||
2480 !Val.getComplexFloatImag().isZero();
2481 return true;
2482 case APValue::LValue:
2483 return EvalPointerValueAsBool(Val, Result);
2484 case APValue::MemberPointer:
2485 Result = Val.getMemberPointerDecl();
2486 return true;
2487 case APValue::Vector:
2488 case APValue::Array:
2489 case APValue::Struct:
2490 case APValue::Union:
2491 case APValue::AddrLabelDiff:
2492 return false;
2493 }
2494
2495 llvm_unreachable("unknown APValue kind");
2496 }
2497
EvaluateAsBooleanCondition(const Expr * E,bool & Result,EvalInfo & Info)2498 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2499 EvalInfo &Info) {
2500 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2501 APValue Val;
2502 if (!Evaluate(Val, Info, E))
2503 return false;
2504 return HandleConversionToBool(Val, Result);
2505 }
2506
2507 template<typename T>
HandleOverflow(EvalInfo & Info,const Expr * E,const T & SrcValue,QualType DestType)2508 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2509 const T &SrcValue, QualType DestType) {
2510 Info.CCEDiag(E, diag::note_constexpr_overflow)
2511 << SrcValue << DestType;
2512 return Info.noteUndefinedBehavior();
2513 }
2514
HandleFloatToIntCast(EvalInfo & Info,const Expr * E,QualType SrcType,const APFloat & Value,QualType DestType,APSInt & Result)2515 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2516 QualType SrcType, const APFloat &Value,
2517 QualType DestType, APSInt &Result) {
2518 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2519 // Determine whether we are converting to unsigned or signed.
2520 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2521
2522 Result = APSInt(DestWidth, !DestSigned);
2523 bool ignored;
2524 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2525 & APFloat::opInvalidOp)
2526 return HandleOverflow(Info, E, Value, DestType);
2527 return true;
2528 }
2529
2530 /// Get rounding mode used for evaluation of the specified expression.
2531 /// \param[out] DynamicRM Is set to true is the requested rounding mode is
2532 /// dynamic.
2533 /// If rounding mode is unknown at compile time, still try to evaluate the
2534 /// expression. If the result is exact, it does not depend on rounding mode.
2535 /// So return "tonearest" mode instead of "dynamic".
getActiveRoundingMode(EvalInfo & Info,const Expr * E,bool & DynamicRM)2536 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
2537 bool &DynamicRM) {
2538 llvm::RoundingMode RM =
2539 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2540 DynamicRM = (RM == llvm::RoundingMode::Dynamic);
2541 if (DynamicRM)
2542 RM = llvm::RoundingMode::NearestTiesToEven;
2543 return RM;
2544 }
2545
2546 /// Check if the given evaluation result is allowed for constant evaluation.
checkFloatingPointResult(EvalInfo & Info,const Expr * E,APFloat::opStatus St)2547 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2548 APFloat::opStatus St) {
2549 // In a constant context, assume that any dynamic rounding mode or FP
2550 // exception state matches the default floating-point environment.
2551 if (Info.InConstantContext)
2552 return true;
2553
2554 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2555 if ((St & APFloat::opInexact) &&
2556 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2557 // Inexact result means that it depends on rounding mode. If the requested
2558 // mode is dynamic, the evaluation cannot be made in compile time.
2559 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2560 return false;
2561 }
2562
2563 if ((St != APFloat::opOK) &&
2564 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2565 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore ||
2566 FPO.getAllowFEnvAccess())) {
2567 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2568 return false;
2569 }
2570
2571 if ((St & APFloat::opStatus::opInvalidOp) &&
2572 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) {
2573 // There is no usefully definable result.
2574 Info.FFDiag(E);
2575 return false;
2576 }
2577
2578 // FIXME: if:
2579 // - evaluation triggered other FP exception, and
2580 // - exception mode is not "ignore", and
2581 // - the expression being evaluated is not a part of global variable
2582 // initializer,
2583 // the evaluation probably need to be rejected.
2584 return true;
2585 }
2586
HandleFloatToFloatCast(EvalInfo & Info,const Expr * E,QualType SrcType,QualType DestType,APFloat & Result)2587 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2588 QualType SrcType, QualType DestType,
2589 APFloat &Result) {
2590 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2591 bool DynamicRM;
2592 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2593 APFloat::opStatus St;
2594 APFloat Value = Result;
2595 bool ignored;
2596 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2597 return checkFloatingPointResult(Info, E, St);
2598 }
2599
HandleIntToIntCast(EvalInfo & Info,const Expr * E,QualType DestType,QualType SrcType,const APSInt & Value)2600 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2601 QualType DestType, QualType SrcType,
2602 const APSInt &Value) {
2603 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2604 // Figure out if this is a truncate, extend or noop cast.
2605 // If the input is signed, do a sign extend, noop, or truncate.
2606 APSInt Result = Value.extOrTrunc(DestWidth);
2607 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2608 if (DestType->isBooleanType())
2609 Result = Value.getBoolValue();
2610 return Result;
2611 }
2612
HandleIntToFloatCast(EvalInfo & Info,const Expr * E,const FPOptions FPO,QualType SrcType,const APSInt & Value,QualType DestType,APFloat & Result)2613 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2614 const FPOptions FPO,
2615 QualType SrcType, const APSInt &Value,
2616 QualType DestType, APFloat &Result) {
2617 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2618 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2619 APFloat::rmNearestTiesToEven);
2620 if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
2621 FPO.isFPConstrained()) {
2622 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2623 return false;
2624 }
2625 return true;
2626 }
2627
truncateBitfieldValue(EvalInfo & Info,const Expr * E,APValue & Value,const FieldDecl * FD)2628 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2629 APValue &Value, const FieldDecl *FD) {
2630 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2631
2632 if (!Value.isInt()) {
2633 // Trying to store a pointer-cast-to-integer into a bitfield.
2634 // FIXME: In this case, we should provide the diagnostic for casting
2635 // a pointer to an integer.
2636 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2637 Info.FFDiag(E);
2638 return false;
2639 }
2640
2641 APSInt &Int = Value.getInt();
2642 unsigned OldBitWidth = Int.getBitWidth();
2643 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2644 if (NewBitWidth < OldBitWidth)
2645 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2646 return true;
2647 }
2648
EvalAndBitcastToAPInt(EvalInfo & Info,const Expr * E,llvm::APInt & Res)2649 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2650 llvm::APInt &Res) {
2651 APValue SVal;
2652 if (!Evaluate(SVal, Info, E))
2653 return false;
2654 if (SVal.isInt()) {
2655 Res = SVal.getInt();
2656 return true;
2657 }
2658 if (SVal.isFloat()) {
2659 Res = SVal.getFloat().bitcastToAPInt();
2660 return true;
2661 }
2662 if (SVal.isVector()) {
2663 QualType VecTy = E->getType();
2664 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2665 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2666 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2667 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2668 Res = llvm::APInt::getNullValue(VecSize);
2669 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2670 APValue &Elt = SVal.getVectorElt(i);
2671 llvm::APInt EltAsInt;
2672 if (Elt.isInt()) {
2673 EltAsInt = Elt.getInt();
2674 } else if (Elt.isFloat()) {
2675 EltAsInt = Elt.getFloat().bitcastToAPInt();
2676 } else {
2677 // Don't try to handle vectors of anything other than int or float
2678 // (not sure if it's possible to hit this case).
2679 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2680 return false;
2681 }
2682 unsigned BaseEltSize = EltAsInt.getBitWidth();
2683 if (BigEndian)
2684 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2685 else
2686 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2687 }
2688 return true;
2689 }
2690 // Give up if the input isn't an int, float, or vector. For example, we
2691 // reject "(v4i16)(intptr_t)&a".
2692 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2693 return false;
2694 }
2695
2696 /// Perform the given integer operation, which is known to need at most BitWidth
2697 /// bits, and check for overflow in the original type (if that type was not an
2698 /// unsigned type).
2699 template<typename Operation>
CheckedIntArithmetic(EvalInfo & Info,const Expr * E,const APSInt & LHS,const APSInt & RHS,unsigned BitWidth,Operation Op,APSInt & Result)2700 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2701 const APSInt &LHS, const APSInt &RHS,
2702 unsigned BitWidth, Operation Op,
2703 APSInt &Result) {
2704 if (LHS.isUnsigned()) {
2705 Result = Op(LHS, RHS);
2706 return true;
2707 }
2708
2709 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2710 Result = Value.trunc(LHS.getBitWidth());
2711 if (Result.extend(BitWidth) != Value) {
2712 if (Info.checkingForUndefinedBehavior())
2713 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2714 diag::warn_integer_constant_overflow)
2715 << Result.toString(10) << E->getType();
2716 else
2717 return HandleOverflow(Info, E, Value, E->getType());
2718 }
2719 return true;
2720 }
2721
2722 /// Perform the given binary integer operation.
handleIntIntBinOp(EvalInfo & Info,const Expr * E,const APSInt & LHS,BinaryOperatorKind Opcode,APSInt RHS,APSInt & Result)2723 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2724 BinaryOperatorKind Opcode, APSInt RHS,
2725 APSInt &Result) {
2726 switch (Opcode) {
2727 default:
2728 Info.FFDiag(E);
2729 return false;
2730 case BO_Mul:
2731 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2732 std::multiplies<APSInt>(), Result);
2733 case BO_Add:
2734 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2735 std::plus<APSInt>(), Result);
2736 case BO_Sub:
2737 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2738 std::minus<APSInt>(), Result);
2739 case BO_And: Result = LHS & RHS; return true;
2740 case BO_Xor: Result = LHS ^ RHS; return true;
2741 case BO_Or: Result = LHS | RHS; return true;
2742 case BO_Div:
2743 case BO_Rem:
2744 if (RHS == 0) {
2745 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2746 return false;
2747 }
2748 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2749 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2750 // this operation and gives the two's complement result.
2751 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2752 LHS.isSigned() && LHS.isMinSignedValue())
2753 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2754 E->getType());
2755 return true;
2756 case BO_Shl: {
2757 if (Info.getLangOpts().OpenCL)
2758 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2759 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2760 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2761 RHS.isUnsigned());
2762 else if (RHS.isSigned() && RHS.isNegative()) {
2763 // During constant-folding, a negative shift is an opposite shift. Such
2764 // a shift is not a constant expression.
2765 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2766 RHS = -RHS;
2767 goto shift_right;
2768 }
2769 shift_left:
2770 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2771 // the shifted type.
2772 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2773 if (SA != RHS) {
2774 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2775 << RHS << E->getType() << LHS.getBitWidth();
2776 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2777 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2778 // operand, and must not overflow the corresponding unsigned type.
2779 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2780 // E1 x 2^E2 module 2^N.
2781 if (LHS.isNegative())
2782 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2783 else if (LHS.countLeadingZeros() < SA)
2784 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2785 }
2786 Result = LHS << SA;
2787 return true;
2788 }
2789 case BO_Shr: {
2790 if (Info.getLangOpts().OpenCL)
2791 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2792 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2793 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2794 RHS.isUnsigned());
2795 else if (RHS.isSigned() && RHS.isNegative()) {
2796 // During constant-folding, a negative shift is an opposite shift. Such a
2797 // shift is not a constant expression.
2798 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2799 RHS = -RHS;
2800 goto shift_left;
2801 }
2802 shift_right:
2803 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2804 // shifted type.
2805 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2806 if (SA != RHS)
2807 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2808 << RHS << E->getType() << LHS.getBitWidth();
2809 Result = LHS >> SA;
2810 return true;
2811 }
2812
2813 case BO_LT: Result = LHS < RHS; return true;
2814 case BO_GT: Result = LHS > RHS; return true;
2815 case BO_LE: Result = LHS <= RHS; return true;
2816 case BO_GE: Result = LHS >= RHS; return true;
2817 case BO_EQ: Result = LHS == RHS; return true;
2818 case BO_NE: Result = LHS != RHS; return true;
2819 case BO_Cmp:
2820 llvm_unreachable("BO_Cmp should be handled elsewhere");
2821 }
2822 }
2823
2824 /// Perform the given binary floating-point operation, in-place, on LHS.
handleFloatFloatBinOp(EvalInfo & Info,const BinaryOperator * E,APFloat & LHS,BinaryOperatorKind Opcode,const APFloat & RHS)2825 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2826 APFloat &LHS, BinaryOperatorKind Opcode,
2827 const APFloat &RHS) {
2828 bool DynamicRM;
2829 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2830 APFloat::opStatus St;
2831 switch (Opcode) {
2832 default:
2833 Info.FFDiag(E);
2834 return false;
2835 case BO_Mul:
2836 St = LHS.multiply(RHS, RM);
2837 break;
2838 case BO_Add:
2839 St = LHS.add(RHS, RM);
2840 break;
2841 case BO_Sub:
2842 St = LHS.subtract(RHS, RM);
2843 break;
2844 case BO_Div:
2845 // [expr.mul]p4:
2846 // If the second operand of / or % is zero the behavior is undefined.
2847 if (RHS.isZero())
2848 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2849 St = LHS.divide(RHS, RM);
2850 break;
2851 }
2852
2853 // [expr.pre]p4:
2854 // If during the evaluation of an expression, the result is not
2855 // mathematically defined [...], the behavior is undefined.
2856 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2857 if (LHS.isNaN()) {
2858 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2859 return Info.noteUndefinedBehavior();
2860 }
2861
2862 return checkFloatingPointResult(Info, E, St);
2863 }
2864
handleLogicalOpForVector(const APInt & LHSValue,BinaryOperatorKind Opcode,const APInt & RHSValue,APInt & Result)2865 static bool handleLogicalOpForVector(const APInt &LHSValue,
2866 BinaryOperatorKind Opcode,
2867 const APInt &RHSValue, APInt &Result) {
2868 bool LHS = (LHSValue != 0);
2869 bool RHS = (RHSValue != 0);
2870
2871 if (Opcode == BO_LAnd)
2872 Result = LHS && RHS;
2873 else
2874 Result = LHS || RHS;
2875 return true;
2876 }
handleLogicalOpForVector(const APFloat & LHSValue,BinaryOperatorKind Opcode,const APFloat & RHSValue,APInt & Result)2877 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2878 BinaryOperatorKind Opcode,
2879 const APFloat &RHSValue, APInt &Result) {
2880 bool LHS = !LHSValue.isZero();
2881 bool RHS = !RHSValue.isZero();
2882
2883 if (Opcode == BO_LAnd)
2884 Result = LHS && RHS;
2885 else
2886 Result = LHS || RHS;
2887 return true;
2888 }
2889
handleLogicalOpForVector(const APValue & LHSValue,BinaryOperatorKind Opcode,const APValue & RHSValue,APInt & Result)2890 static bool handleLogicalOpForVector(const APValue &LHSValue,
2891 BinaryOperatorKind Opcode,
2892 const APValue &RHSValue, APInt &Result) {
2893 // The result is always an int type, however operands match the first.
2894 if (LHSValue.getKind() == APValue::Int)
2895 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2896 RHSValue.getInt(), Result);
2897 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2898 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2899 RHSValue.getFloat(), Result);
2900 }
2901
2902 template <typename APTy>
2903 static bool
handleCompareOpForVectorHelper(const APTy & LHSValue,BinaryOperatorKind Opcode,const APTy & RHSValue,APInt & Result)2904 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2905 const APTy &RHSValue, APInt &Result) {
2906 switch (Opcode) {
2907 default:
2908 llvm_unreachable("unsupported binary operator");
2909 case BO_EQ:
2910 Result = (LHSValue == RHSValue);
2911 break;
2912 case BO_NE:
2913 Result = (LHSValue != RHSValue);
2914 break;
2915 case BO_LT:
2916 Result = (LHSValue < RHSValue);
2917 break;
2918 case BO_GT:
2919 Result = (LHSValue > RHSValue);
2920 break;
2921 case BO_LE:
2922 Result = (LHSValue <= RHSValue);
2923 break;
2924 case BO_GE:
2925 Result = (LHSValue >= RHSValue);
2926 break;
2927 }
2928
2929 return true;
2930 }
2931
handleCompareOpForVector(const APValue & LHSValue,BinaryOperatorKind Opcode,const APValue & RHSValue,APInt & Result)2932 static bool handleCompareOpForVector(const APValue &LHSValue,
2933 BinaryOperatorKind Opcode,
2934 const APValue &RHSValue, APInt &Result) {
2935 // The result is always an int type, however operands match the first.
2936 if (LHSValue.getKind() == APValue::Int)
2937 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2938 RHSValue.getInt(), Result);
2939 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2940 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2941 RHSValue.getFloat(), Result);
2942 }
2943
2944 // Perform binary operations for vector types, in place on the LHS.
handleVectorVectorBinOp(EvalInfo & Info,const BinaryOperator * E,BinaryOperatorKind Opcode,APValue & LHSValue,const APValue & RHSValue)2945 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2946 BinaryOperatorKind Opcode,
2947 APValue &LHSValue,
2948 const APValue &RHSValue) {
2949 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2950 "Operation not supported on vector types");
2951
2952 const auto *VT = E->getType()->castAs<VectorType>();
2953 unsigned NumElements = VT->getNumElements();
2954 QualType EltTy = VT->getElementType();
2955
2956 // In the cases (typically C as I've observed) where we aren't evaluating
2957 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2958 // just give up.
2959 if (!LHSValue.isVector()) {
2960 assert(LHSValue.isLValue() &&
2961 "A vector result that isn't a vector OR uncalculated LValue");
2962 Info.FFDiag(E);
2963 return false;
2964 }
2965
2966 assert(LHSValue.getVectorLength() == NumElements &&
2967 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2968
2969 SmallVector<APValue, 4> ResultElements;
2970
2971 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2972 APValue LHSElt = LHSValue.getVectorElt(EltNum);
2973 APValue RHSElt = RHSValue.getVectorElt(EltNum);
2974
2975 if (EltTy->isIntegerType()) {
2976 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2977 EltTy->isUnsignedIntegerType()};
2978 bool Success = true;
2979
2980 if (BinaryOperator::isLogicalOp(Opcode))
2981 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2982 else if (BinaryOperator::isComparisonOp(Opcode))
2983 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2984 else
2985 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2986 RHSElt.getInt(), EltResult);
2987
2988 if (!Success) {
2989 Info.FFDiag(E);
2990 return false;
2991 }
2992 ResultElements.emplace_back(EltResult);
2993
2994 } else if (EltTy->isFloatingType()) {
2995 assert(LHSElt.getKind() == APValue::Float &&
2996 RHSElt.getKind() == APValue::Float &&
2997 "Mismatched LHS/RHS/Result Type");
2998 APFloat LHSFloat = LHSElt.getFloat();
2999
3000 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3001 RHSElt.getFloat())) {
3002 Info.FFDiag(E);
3003 return false;
3004 }
3005
3006 ResultElements.emplace_back(LHSFloat);
3007 }
3008 }
3009
3010 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3011 return true;
3012 }
3013
3014 /// Cast an lvalue referring to a base subobject to a derived class, by
3015 /// truncating the lvalue's path to the given length.
CastToDerivedClass(EvalInfo & Info,const Expr * E,LValue & Result,const RecordDecl * TruncatedType,unsigned TruncatedElements)3016 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3017 const RecordDecl *TruncatedType,
3018 unsigned TruncatedElements) {
3019 SubobjectDesignator &D = Result.Designator;
3020
3021 // Check we actually point to a derived class object.
3022 if (TruncatedElements == D.Entries.size())
3023 return true;
3024 assert(TruncatedElements >= D.MostDerivedPathLength &&
3025 "not casting to a derived class");
3026 if (!Result.checkSubobject(Info, E, CSK_Derived))
3027 return false;
3028
3029 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3030 const RecordDecl *RD = TruncatedType;
3031 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3032 if (RD->isInvalidDecl()) return false;
3033 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3034 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3035 if (isVirtualBaseClass(D.Entries[I]))
3036 Result.Offset -= Layout.getVBaseClassOffset(Base);
3037 else
3038 Result.Offset -= Layout.getBaseClassOffset(Base);
3039 RD = Base;
3040 }
3041 D.Entries.resize(TruncatedElements);
3042 return true;
3043 }
3044
HandleLValueDirectBase(EvalInfo & Info,const Expr * E,LValue & Obj,const CXXRecordDecl * Derived,const CXXRecordDecl * Base,const ASTRecordLayout * RL=nullptr)3045 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3046 const CXXRecordDecl *Derived,
3047 const CXXRecordDecl *Base,
3048 const ASTRecordLayout *RL = nullptr) {
3049 if (!RL) {
3050 if (Derived->isInvalidDecl()) return false;
3051 RL = &Info.Ctx.getASTRecordLayout(Derived);
3052 }
3053
3054 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3055 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3056 return true;
3057 }
3058
HandleLValueBase(EvalInfo & Info,const Expr * E,LValue & Obj,const CXXRecordDecl * DerivedDecl,const CXXBaseSpecifier * Base)3059 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3060 const CXXRecordDecl *DerivedDecl,
3061 const CXXBaseSpecifier *Base) {
3062 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3063
3064 if (!Base->isVirtual())
3065 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3066
3067 SubobjectDesignator &D = Obj.Designator;
3068 if (D.Invalid)
3069 return false;
3070
3071 // Extract most-derived object and corresponding type.
3072 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3073 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3074 return false;
3075
3076 // Find the virtual base class.
3077 if (DerivedDecl->isInvalidDecl()) return false;
3078 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3079 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3080 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3081 return true;
3082 }
3083
HandleLValueBasePath(EvalInfo & Info,const CastExpr * E,QualType Type,LValue & Result)3084 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3085 QualType Type, LValue &Result) {
3086 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3087 PathE = E->path_end();
3088 PathI != PathE; ++PathI) {
3089 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3090 *PathI))
3091 return false;
3092 Type = (*PathI)->getType();
3093 }
3094 return true;
3095 }
3096
3097 /// Cast an lvalue referring to a derived class to a known base subobject.
CastToBaseClass(EvalInfo & Info,const Expr * E,LValue & Result,const CXXRecordDecl * DerivedRD,const CXXRecordDecl * BaseRD)3098 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3099 const CXXRecordDecl *DerivedRD,
3100 const CXXRecordDecl *BaseRD) {
3101 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3102 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3103 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3104 llvm_unreachable("Class must be derived from the passed in base class!");
3105
3106 for (CXXBasePathElement &Elem : Paths.front())
3107 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3108 return false;
3109 return true;
3110 }
3111
3112 /// Update LVal to refer to the given field, which must be a member of the type
3113 /// currently described by LVal.
HandleLValueMember(EvalInfo & Info,const Expr * E,LValue & LVal,const FieldDecl * FD,const ASTRecordLayout * RL=nullptr)3114 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3115 const FieldDecl *FD,
3116 const ASTRecordLayout *RL = nullptr) {
3117 if (!RL) {
3118 if (FD->getParent()->isInvalidDecl()) return false;
3119 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3120 }
3121
3122 unsigned I = FD->getFieldIndex();
3123 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3124 LVal.addDecl(Info, E, FD);
3125 return true;
3126 }
3127
3128 /// Update LVal to refer to the given indirect field.
HandleLValueIndirectMember(EvalInfo & Info,const Expr * E,LValue & LVal,const IndirectFieldDecl * IFD)3129 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3130 LValue &LVal,
3131 const IndirectFieldDecl *IFD) {
3132 for (const auto *C : IFD->chain())
3133 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3134 return false;
3135 return true;
3136 }
3137
3138 /// Get the size of the given type in char units.
HandleSizeof(EvalInfo & Info,SourceLocation Loc,QualType Type,CharUnits & Size)3139 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3140 QualType Type, CharUnits &Size) {
3141 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3142 // extension.
3143 if (Type->isVoidType() || Type->isFunctionType()) {
3144 Size = CharUnits::One();
3145 return true;
3146 }
3147
3148 if (Type->isDependentType()) {
3149 Info.FFDiag(Loc);
3150 return false;
3151 }
3152
3153 if (!Type->isConstantSizeType()) {
3154 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3155 // FIXME: Better diagnostic.
3156 Info.FFDiag(Loc);
3157 return false;
3158 }
3159
3160 Size = Info.Ctx.getTypeSizeInChars(Type);
3161 return true;
3162 }
3163
3164 /// Update a pointer value to model pointer arithmetic.
3165 /// \param Info - Information about the ongoing evaluation.
3166 /// \param E - The expression being evaluated, for diagnostic purposes.
3167 /// \param LVal - The pointer value to be updated.
3168 /// \param EltTy - The pointee type represented by LVal.
3169 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
HandleLValueArrayAdjustment(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,APSInt Adjustment)3170 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3171 LValue &LVal, QualType EltTy,
3172 APSInt Adjustment) {
3173 CharUnits SizeOfPointee;
3174 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3175 return false;
3176
3177 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3178 return true;
3179 }
3180
HandleLValueArrayAdjustment(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,int64_t Adjustment)3181 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3182 LValue &LVal, QualType EltTy,
3183 int64_t Adjustment) {
3184 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3185 APSInt::get(Adjustment));
3186 }
3187
3188 /// Update an lvalue to refer to a component of a complex number.
3189 /// \param Info - Information about the ongoing evaluation.
3190 /// \param LVal - The lvalue to be updated.
3191 /// \param EltTy - The complex number's component type.
3192 /// \param Imag - False for the real component, true for the imaginary.
HandleLValueComplexElement(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,bool Imag)3193 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3194 LValue &LVal, QualType EltTy,
3195 bool Imag) {
3196 if (Imag) {
3197 CharUnits SizeOfComponent;
3198 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3199 return false;
3200 LVal.Offset += SizeOfComponent;
3201 }
3202 LVal.addComplex(Info, E, EltTy, Imag);
3203 return true;
3204 }
3205
3206 /// Try to evaluate the initializer for a variable declaration.
3207 ///
3208 /// \param Info Information about the ongoing evaluation.
3209 /// \param E An expression to be used when printing diagnostics.
3210 /// \param VD The variable whose initializer should be obtained.
3211 /// \param Version The version of the variable within the frame.
3212 /// \param Frame The frame in which the variable was created. Must be null
3213 /// if this variable is not local to the evaluation.
3214 /// \param Result Filled in with a pointer to the value of the variable.
evaluateVarDeclInit(EvalInfo & Info,const Expr * E,const VarDecl * VD,CallStackFrame * Frame,unsigned Version,APValue * & Result)3215 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3216 const VarDecl *VD, CallStackFrame *Frame,
3217 unsigned Version, APValue *&Result) {
3218 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3219
3220 // If this is a local variable, dig out its value.
3221 if (Frame) {
3222 Result = Frame->getTemporary(VD, Version);
3223 if (Result)
3224 return true;
3225
3226 if (!isa<ParmVarDecl>(VD)) {
3227 // Assume variables referenced within a lambda's call operator that were
3228 // not declared within the call operator are captures and during checking
3229 // of a potential constant expression, assume they are unknown constant
3230 // expressions.
3231 assert(isLambdaCallOperator(Frame->Callee) &&
3232 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3233 "missing value for local variable");
3234 if (Info.checkingPotentialConstantExpression())
3235 return false;
3236 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3237 // still reachable at all?
3238 Info.FFDiag(E->getBeginLoc(),
3239 diag::note_unimplemented_constexpr_lambda_feature_ast)
3240 << "captures not currently allowed";
3241 return false;
3242 }
3243 }
3244
3245 // If we're currently evaluating the initializer of this declaration, use that
3246 // in-flight value.
3247 if (Info.EvaluatingDecl == Base) {
3248 Result = Info.EvaluatingDeclValue;
3249 return true;
3250 }
3251
3252 if (isa<ParmVarDecl>(VD)) {
3253 // Assume parameters of a potential constant expression are usable in
3254 // constant expressions.
3255 if (!Info.checkingPotentialConstantExpression() ||
3256 !Info.CurrentCall->Callee ||
3257 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3258 if (Info.getLangOpts().CPlusPlus11) {
3259 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3260 << VD;
3261 NoteLValueLocation(Info, Base);
3262 } else {
3263 Info.FFDiag(E);
3264 }
3265 }
3266 return false;
3267 }
3268
3269 // Dig out the initializer, and use the declaration which it's attached to.
3270 // FIXME: We should eventually check whether the variable has a reachable
3271 // initializing declaration.
3272 const Expr *Init = VD->getAnyInitializer(VD);
3273 if (!Init) {
3274 // Don't diagnose during potential constant expression checking; an
3275 // initializer might be added later.
3276 if (!Info.checkingPotentialConstantExpression()) {
3277 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3278 << VD;
3279 NoteLValueLocation(Info, Base);
3280 }
3281 return false;
3282 }
3283
3284 if (Init->isValueDependent()) {
3285 // The DeclRefExpr is not value-dependent, but the variable it refers to
3286 // has a value-dependent initializer. This should only happen in
3287 // constant-folding cases, where the variable is not actually of a suitable
3288 // type for use in a constant expression (otherwise the DeclRefExpr would
3289 // have been value-dependent too), so diagnose that.
3290 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3291 if (!Info.checkingPotentialConstantExpression()) {
3292 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3293 ? diag::note_constexpr_ltor_non_constexpr
3294 : diag::note_constexpr_ltor_non_integral, 1)
3295 << VD << VD->getType();
3296 NoteLValueLocation(Info, Base);
3297 }
3298 return false;
3299 }
3300
3301 // Check that we can fold the initializer. In C++, we will have already done
3302 // this in the cases where it matters for conformance.
3303 if (!VD->evaluateValue()) {
3304 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3305 NoteLValueLocation(Info, Base);
3306 return false;
3307 }
3308
3309 // Check that the variable is actually usable in constant expressions. For a
3310 // const integral variable or a reference, we might have a non-constant
3311 // initializer that we can nonetheless evaluate the initializer for. Such
3312 // variables are not usable in constant expressions. In C++98, the
3313 // initializer also syntactically needs to be an ICE.
3314 //
3315 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3316 // expressions here; doing so would regress diagnostics for things like
3317 // reading from a volatile constexpr variable.
3318 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3319 VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3320 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3321 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3322 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3323 NoteLValueLocation(Info, Base);
3324 }
3325
3326 // Never use the initializer of a weak variable, not even for constant
3327 // folding. We can't be sure that this is the definition that will be used.
3328 if (VD->isWeak()) {
3329 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3330 NoteLValueLocation(Info, Base);
3331 return false;
3332 }
3333
3334 Result = VD->getEvaluatedValue();
3335 return true;
3336 }
3337
3338 /// Get the base index of the given base class within an APValue representing
3339 /// the given derived class.
getBaseIndex(const CXXRecordDecl * Derived,const CXXRecordDecl * Base)3340 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3341 const CXXRecordDecl *Base) {
3342 Base = Base->getCanonicalDecl();
3343 unsigned Index = 0;
3344 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3345 E = Derived->bases_end(); I != E; ++I, ++Index) {
3346 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3347 return Index;
3348 }
3349
3350 llvm_unreachable("base class missing from derived class's bases list");
3351 }
3352
3353 /// Extract the value of a character from a string literal.
extractStringLiteralCharacter(EvalInfo & Info,const Expr * Lit,uint64_t Index)3354 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3355 uint64_t Index) {
3356 assert(!isa<SourceLocExpr>(Lit) &&
3357 "SourceLocExpr should have already been converted to a StringLiteral");
3358
3359 // FIXME: Support MakeStringConstant
3360 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3361 std::string Str;
3362 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3363 assert(Index <= Str.size() && "Index too large");
3364 return APSInt::getUnsigned(Str.c_str()[Index]);
3365 }
3366
3367 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3368 Lit = PE->getFunctionName();
3369 const StringLiteral *S = cast<StringLiteral>(Lit);
3370 const ConstantArrayType *CAT =
3371 Info.Ctx.getAsConstantArrayType(S->getType());
3372 assert(CAT && "string literal isn't an array");
3373 QualType CharType = CAT->getElementType();
3374 assert(CharType->isIntegerType() && "unexpected character type");
3375
3376 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3377 CharType->isUnsignedIntegerType());
3378 if (Index < S->getLength())
3379 Value = S->getCodeUnit(Index);
3380 return Value;
3381 }
3382
3383 // Expand a string literal into an array of characters.
3384 //
3385 // FIXME: This is inefficient; we should probably introduce something similar
3386 // to the LLVM ConstantDataArray to make this cheaper.
expandStringLiteral(EvalInfo & Info,const StringLiteral * S,APValue & Result,QualType AllocType=QualType ())3387 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3388 APValue &Result,
3389 QualType AllocType = QualType()) {
3390 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3391 AllocType.isNull() ? S->getType() : AllocType);
3392 assert(CAT && "string literal isn't an array");
3393 QualType CharType = CAT->getElementType();
3394 assert(CharType->isIntegerType() && "unexpected character type");
3395
3396 unsigned Elts = CAT->getSize().getZExtValue();
3397 Result = APValue(APValue::UninitArray(),
3398 std::min(S->getLength(), Elts), Elts);
3399 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3400 CharType->isUnsignedIntegerType());
3401 if (Result.hasArrayFiller())
3402 Result.getArrayFiller() = APValue(Value);
3403 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3404 Value = S->getCodeUnit(I);
3405 Result.getArrayInitializedElt(I) = APValue(Value);
3406 }
3407 }
3408
3409 // Expand an array so that it has more than Index filled elements.
expandArray(APValue & Array,unsigned Index)3410 static void expandArray(APValue &Array, unsigned Index) {
3411 unsigned Size = Array.getArraySize();
3412 assert(Index < Size);
3413
3414 // Always at least double the number of elements for which we store a value.
3415 unsigned OldElts = Array.getArrayInitializedElts();
3416 unsigned NewElts = std::max(Index+1, OldElts * 2);
3417 NewElts = std::min(Size, std::max(NewElts, 8u));
3418
3419 // Copy the data across.
3420 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3421 for (unsigned I = 0; I != OldElts; ++I)
3422 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3423 for (unsigned I = OldElts; I != NewElts; ++I)
3424 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3425 if (NewValue.hasArrayFiller())
3426 NewValue.getArrayFiller() = Array.getArrayFiller();
3427 Array.swap(NewValue);
3428 }
3429
3430 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3431 /// conversion. If it's of class type, we may assume that the copy operation
3432 /// is trivial. Note that this is never true for a union type with fields
3433 /// (because the copy always "reads" the active member) and always true for
3434 /// a non-class type.
3435 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
isReadByLvalueToRvalueConversion(QualType T)3436 static bool isReadByLvalueToRvalueConversion(QualType T) {
3437 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3438 return !RD || isReadByLvalueToRvalueConversion(RD);
3439 }
isReadByLvalueToRvalueConversion(const CXXRecordDecl * RD)3440 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3441 // FIXME: A trivial copy of a union copies the object representation, even if
3442 // the union is empty.
3443 if (RD->isUnion())
3444 return !RD->field_empty();
3445 if (RD->isEmpty())
3446 return false;
3447
3448 for (auto *Field : RD->fields())
3449 if (!Field->isUnnamedBitfield() &&
3450 isReadByLvalueToRvalueConversion(Field->getType()))
3451 return true;
3452
3453 for (auto &BaseSpec : RD->bases())
3454 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3455 return true;
3456
3457 return false;
3458 }
3459
3460 /// Diagnose an attempt to read from any unreadable field within the specified
3461 /// type, which might be a class type.
diagnoseMutableFields(EvalInfo & Info,const Expr * E,AccessKinds AK,QualType T)3462 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3463 QualType T) {
3464 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3465 if (!RD)
3466 return false;
3467
3468 if (!RD->hasMutableFields())
3469 return false;
3470
3471 for (auto *Field : RD->fields()) {
3472 // If we're actually going to read this field in some way, then it can't
3473 // be mutable. If we're in a union, then assigning to a mutable field
3474 // (even an empty one) can change the active member, so that's not OK.
3475 // FIXME: Add core issue number for the union case.
3476 if (Field->isMutable() &&
3477 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3478 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3479 Info.Note(Field->getLocation(), diag::note_declared_at);
3480 return true;
3481 }
3482
3483 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3484 return true;
3485 }
3486
3487 for (auto &BaseSpec : RD->bases())
3488 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3489 return true;
3490
3491 // All mutable fields were empty, and thus not actually read.
3492 return false;
3493 }
3494
lifetimeStartedInEvaluation(EvalInfo & Info,APValue::LValueBase Base,bool MutableSubobject=false)3495 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3496 APValue::LValueBase Base,
3497 bool MutableSubobject = false) {
3498 // A temporary we created.
3499 if (Base.getCallIndex())
3500 return true;
3501
3502 switch (Info.IsEvaluatingDecl) {
3503 case EvalInfo::EvaluatingDeclKind::None:
3504 return false;
3505
3506 case EvalInfo::EvaluatingDeclKind::Ctor:
3507 // The variable whose initializer we're evaluating.
3508 if (Info.EvaluatingDecl == Base)
3509 return true;
3510
3511 // A temporary lifetime-extended by the variable whose initializer we're
3512 // evaluating.
3513 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3514 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3515 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3516 return false;
3517
3518 case EvalInfo::EvaluatingDeclKind::Dtor:
3519 // C++2a [expr.const]p6:
3520 // [during constant destruction] the lifetime of a and its non-mutable
3521 // subobjects (but not its mutable subobjects) [are] considered to start
3522 // within e.
3523 if (MutableSubobject || Base != Info.EvaluatingDecl)
3524 return false;
3525 // FIXME: We can meaningfully extend this to cover non-const objects, but
3526 // we will need special handling: we should be able to access only
3527 // subobjects of such objects that are themselves declared const.
3528 QualType T = getType(Base);
3529 return T.isConstQualified() || T->isReferenceType();
3530 }
3531
3532 llvm_unreachable("unknown evaluating decl kind");
3533 }
3534
3535 namespace {
3536 /// A handle to a complete object (an object that is not a subobject of
3537 /// another object).
3538 struct CompleteObject {
3539 /// The identity of the object.
3540 APValue::LValueBase Base;
3541 /// The value of the complete object.
3542 APValue *Value;
3543 /// The type of the complete object.
3544 QualType Type;
3545
CompleteObject__anon4717f8730911::CompleteObject3546 CompleteObject() : Value(nullptr) {}
CompleteObject__anon4717f8730911::CompleteObject3547 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3548 : Base(Base), Value(Value), Type(Type) {}
3549
mayAccessMutableMembers__anon4717f8730911::CompleteObject3550 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3551 // If this isn't a "real" access (eg, if it's just accessing the type
3552 // info), allow it. We assume the type doesn't change dynamically for
3553 // subobjects of constexpr objects (even though we'd hit UB here if it
3554 // did). FIXME: Is this right?
3555 if (!isAnyAccess(AK))
3556 return true;
3557
3558 // In C++14 onwards, it is permitted to read a mutable member whose
3559 // lifetime began within the evaluation.
3560 // FIXME: Should we also allow this in C++11?
3561 if (!Info.getLangOpts().CPlusPlus14)
3562 return false;
3563 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3564 }
3565
operator bool__anon4717f8730911::CompleteObject3566 explicit operator bool() const { return !Type.isNull(); }
3567 };
3568 } // end anonymous namespace
3569
getSubobjectType(QualType ObjType,QualType SubobjType,bool IsMutable=false)3570 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3571 bool IsMutable = false) {
3572 // C++ [basic.type.qualifier]p1:
3573 // - A const object is an object of type const T or a non-mutable subobject
3574 // of a const object.
3575 if (ObjType.isConstQualified() && !IsMutable)
3576 SubobjType.addConst();
3577 // - A volatile object is an object of type const T or a subobject of a
3578 // volatile object.
3579 if (ObjType.isVolatileQualified())
3580 SubobjType.addVolatile();
3581 return SubobjType;
3582 }
3583
3584 /// Find the designated sub-object of an rvalue.
3585 template<typename SubobjectHandler>
3586 typename SubobjectHandler::result_type
findSubobject(EvalInfo & Info,const Expr * E,const CompleteObject & Obj,const SubobjectDesignator & Sub,SubobjectHandler & handler)3587 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3588 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3589 if (Sub.Invalid)
3590 // A diagnostic will have already been produced.
3591 return handler.failed();
3592 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3593 if (Info.getLangOpts().CPlusPlus11)
3594 Info.FFDiag(E, Sub.isOnePastTheEnd()
3595 ? diag::note_constexpr_access_past_end
3596 : diag::note_constexpr_access_unsized_array)
3597 << handler.AccessKind;
3598 else
3599 Info.FFDiag(E);
3600 return handler.failed();
3601 }
3602
3603 APValue *O = Obj.Value;
3604 QualType ObjType = Obj.Type;
3605 const FieldDecl *LastField = nullptr;
3606 const FieldDecl *VolatileField = nullptr;
3607
3608 // Walk the designator's path to find the subobject.
3609 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3610 // Reading an indeterminate value is undefined, but assigning over one is OK.
3611 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3612 (O->isIndeterminate() &&
3613 !isValidIndeterminateAccess(handler.AccessKind))) {
3614 if (!Info.checkingPotentialConstantExpression())
3615 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3616 << handler.AccessKind << O->isIndeterminate();
3617 return handler.failed();
3618 }
3619
3620 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3621 // const and volatile semantics are not applied on an object under
3622 // {con,de}struction.
3623 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3624 ObjType->isRecordType() &&
3625 Info.isEvaluatingCtorDtor(
3626 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3627 Sub.Entries.begin() + I)) !=
3628 ConstructionPhase::None) {
3629 ObjType = Info.Ctx.getCanonicalType(ObjType);
3630 ObjType.removeLocalConst();
3631 ObjType.removeLocalVolatile();
3632 }
3633
3634 // If this is our last pass, check that the final object type is OK.
3635 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3636 // Accesses to volatile objects are prohibited.
3637 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3638 if (Info.getLangOpts().CPlusPlus) {
3639 int DiagKind;
3640 SourceLocation Loc;
3641 const NamedDecl *Decl = nullptr;
3642 if (VolatileField) {
3643 DiagKind = 2;
3644 Loc = VolatileField->getLocation();
3645 Decl = VolatileField;
3646 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3647 DiagKind = 1;
3648 Loc = VD->getLocation();
3649 Decl = VD;
3650 } else {
3651 DiagKind = 0;
3652 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3653 Loc = E->getExprLoc();
3654 }
3655 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3656 << handler.AccessKind << DiagKind << Decl;
3657 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3658 } else {
3659 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3660 }
3661 return handler.failed();
3662 }
3663
3664 // If we are reading an object of class type, there may still be more
3665 // things we need to check: if there are any mutable subobjects, we
3666 // cannot perform this read. (This only happens when performing a trivial
3667 // copy or assignment.)
3668 if (ObjType->isRecordType() &&
3669 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3670 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3671 return handler.failed();
3672 }
3673
3674 if (I == N) {
3675 if (!handler.found(*O, ObjType))
3676 return false;
3677
3678 // If we modified a bit-field, truncate it to the right width.
3679 if (isModification(handler.AccessKind) &&
3680 LastField && LastField->isBitField() &&
3681 !truncateBitfieldValue(Info, E, *O, LastField))
3682 return false;
3683
3684 return true;
3685 }
3686
3687 LastField = nullptr;
3688 if (ObjType->isArrayType()) {
3689 // Next subobject is an array element.
3690 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3691 assert(CAT && "vla in literal type?");
3692 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3693 if (CAT->getSize().ule(Index)) {
3694 // Note, it should not be possible to form a pointer with a valid
3695 // designator which points more than one past the end of the array.
3696 if (Info.getLangOpts().CPlusPlus11)
3697 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3698 << handler.AccessKind;
3699 else
3700 Info.FFDiag(E);
3701 return handler.failed();
3702 }
3703
3704 ObjType = CAT->getElementType();
3705
3706 if (O->getArrayInitializedElts() > Index)
3707 O = &O->getArrayInitializedElt(Index);
3708 else if (!isRead(handler.AccessKind)) {
3709 expandArray(*O, Index);
3710 O = &O->getArrayInitializedElt(Index);
3711 } else
3712 O = &O->getArrayFiller();
3713 } else if (ObjType->isAnyComplexType()) {
3714 // Next subobject is a complex number.
3715 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3716 if (Index > 1) {
3717 if (Info.getLangOpts().CPlusPlus11)
3718 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3719 << handler.AccessKind;
3720 else
3721 Info.FFDiag(E);
3722 return handler.failed();
3723 }
3724
3725 ObjType = getSubobjectType(
3726 ObjType, ObjType->castAs<ComplexType>()->getElementType());
3727
3728 assert(I == N - 1 && "extracting subobject of scalar?");
3729 if (O->isComplexInt()) {
3730 return handler.found(Index ? O->getComplexIntImag()
3731 : O->getComplexIntReal(), ObjType);
3732 } else {
3733 assert(O->isComplexFloat());
3734 return handler.found(Index ? O->getComplexFloatImag()
3735 : O->getComplexFloatReal(), ObjType);
3736 }
3737 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3738 if (Field->isMutable() &&
3739 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3740 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3741 << handler.AccessKind << Field;
3742 Info.Note(Field->getLocation(), diag::note_declared_at);
3743 return handler.failed();
3744 }
3745
3746 // Next subobject is a class, struct or union field.
3747 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3748 if (RD->isUnion()) {
3749 const FieldDecl *UnionField = O->getUnionField();
3750 if (!UnionField ||
3751 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3752 if (I == N - 1 && handler.AccessKind == AK_Construct) {
3753 // Placement new onto an inactive union member makes it active.
3754 O->setUnion(Field, APValue());
3755 } else {
3756 // FIXME: If O->getUnionValue() is absent, report that there's no
3757 // active union member rather than reporting the prior active union
3758 // member. We'll need to fix nullptr_t to not use APValue() as its
3759 // representation first.
3760 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3761 << handler.AccessKind << Field << !UnionField << UnionField;
3762 return handler.failed();
3763 }
3764 }
3765 O = &O->getUnionValue();
3766 } else
3767 O = &O->getStructField(Field->getFieldIndex());
3768
3769 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3770 LastField = Field;
3771 if (Field->getType().isVolatileQualified())
3772 VolatileField = Field;
3773 } else {
3774 // Next subobject is a base class.
3775 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3776 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3777 O = &O->getStructBase(getBaseIndex(Derived, Base));
3778
3779 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3780 }
3781 }
3782 }
3783
3784 namespace {
3785 struct ExtractSubobjectHandler {
3786 EvalInfo &Info;
3787 const Expr *E;
3788 APValue &Result;
3789 const AccessKinds AccessKind;
3790
3791 typedef bool result_type;
failed__anon4717f8730a11::ExtractSubobjectHandler3792 bool failed() { return false; }
found__anon4717f8730a11::ExtractSubobjectHandler3793 bool found(APValue &Subobj, QualType SubobjType) {
3794 Result = Subobj;
3795 if (AccessKind == AK_ReadObjectRepresentation)
3796 return true;
3797 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3798 }
found__anon4717f8730a11::ExtractSubobjectHandler3799 bool found(APSInt &Value, QualType SubobjType) {
3800 Result = APValue(Value);
3801 return true;
3802 }
found__anon4717f8730a11::ExtractSubobjectHandler3803 bool found(APFloat &Value, QualType SubobjType) {
3804 Result = APValue(Value);
3805 return true;
3806 }
3807 };
3808 } // end anonymous namespace
3809
3810 /// Extract the designated sub-object of an rvalue.
extractSubobject(EvalInfo & Info,const Expr * E,const CompleteObject & Obj,const SubobjectDesignator & Sub,APValue & Result,AccessKinds AK=AK_Read)3811 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3812 const CompleteObject &Obj,
3813 const SubobjectDesignator &Sub, APValue &Result,
3814 AccessKinds AK = AK_Read) {
3815 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3816 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3817 return findSubobject(Info, E, Obj, Sub, Handler);
3818 }
3819
3820 namespace {
3821 struct ModifySubobjectHandler {
3822 EvalInfo &Info;
3823 APValue &NewVal;
3824 const Expr *E;
3825
3826 typedef bool result_type;
3827 static const AccessKinds AccessKind = AK_Assign;
3828
checkConst__anon4717f8730b11::ModifySubobjectHandler3829 bool checkConst(QualType QT) {
3830 // Assigning to a const object has undefined behavior.
3831 if (QT.isConstQualified()) {
3832 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3833 return false;
3834 }
3835 return true;
3836 }
3837
failed__anon4717f8730b11::ModifySubobjectHandler3838 bool failed() { return false; }
found__anon4717f8730b11::ModifySubobjectHandler3839 bool found(APValue &Subobj, QualType SubobjType) {
3840 if (!checkConst(SubobjType))
3841 return false;
3842 // We've been given ownership of NewVal, so just swap it in.
3843 Subobj.swap(NewVal);
3844 return true;
3845 }
found__anon4717f8730b11::ModifySubobjectHandler3846 bool found(APSInt &Value, QualType SubobjType) {
3847 if (!checkConst(SubobjType))
3848 return false;
3849 if (!NewVal.isInt()) {
3850 // Maybe trying to write a cast pointer value into a complex?
3851 Info.FFDiag(E);
3852 return false;
3853 }
3854 Value = NewVal.getInt();
3855 return true;
3856 }
found__anon4717f8730b11::ModifySubobjectHandler3857 bool found(APFloat &Value, QualType SubobjType) {
3858 if (!checkConst(SubobjType))
3859 return false;
3860 Value = NewVal.getFloat();
3861 return true;
3862 }
3863 };
3864 } // end anonymous namespace
3865
3866 const AccessKinds ModifySubobjectHandler::AccessKind;
3867
3868 /// Update the designated sub-object of an rvalue to the given value.
modifySubobject(EvalInfo & Info,const Expr * E,const CompleteObject & Obj,const SubobjectDesignator & Sub,APValue & NewVal)3869 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3870 const CompleteObject &Obj,
3871 const SubobjectDesignator &Sub,
3872 APValue &NewVal) {
3873 ModifySubobjectHandler Handler = { Info, NewVal, E };
3874 return findSubobject(Info, E, Obj, Sub, Handler);
3875 }
3876
3877 /// Find the position where two subobject designators diverge, or equivalently
3878 /// the length of the common initial subsequence.
FindDesignatorMismatch(QualType ObjType,const SubobjectDesignator & A,const SubobjectDesignator & B,bool & WasArrayIndex)3879 static unsigned FindDesignatorMismatch(QualType ObjType,
3880 const SubobjectDesignator &A,
3881 const SubobjectDesignator &B,
3882 bool &WasArrayIndex) {
3883 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3884 for (/**/; I != N; ++I) {
3885 if (!ObjType.isNull() &&
3886 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3887 // Next subobject is an array element.
3888 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3889 WasArrayIndex = true;
3890 return I;
3891 }
3892 if (ObjType->isAnyComplexType())
3893 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3894 else
3895 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3896 } else {
3897 if (A.Entries[I].getAsBaseOrMember() !=
3898 B.Entries[I].getAsBaseOrMember()) {
3899 WasArrayIndex = false;
3900 return I;
3901 }
3902 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3903 // Next subobject is a field.
3904 ObjType = FD->getType();
3905 else
3906 // Next subobject is a base class.
3907 ObjType = QualType();
3908 }
3909 }
3910 WasArrayIndex = false;
3911 return I;
3912 }
3913
3914 /// Determine whether the given subobject designators refer to elements of the
3915 /// same array object.
AreElementsOfSameArray(QualType ObjType,const SubobjectDesignator & A,const SubobjectDesignator & B)3916 static bool AreElementsOfSameArray(QualType ObjType,
3917 const SubobjectDesignator &A,
3918 const SubobjectDesignator &B) {
3919 if (A.Entries.size() != B.Entries.size())
3920 return false;
3921
3922 bool IsArray = A.MostDerivedIsArrayElement;
3923 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3924 // A is a subobject of the array element.
3925 return false;
3926
3927 // If A (and B) designates an array element, the last entry will be the array
3928 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3929 // of length 1' case, and the entire path must match.
3930 bool WasArrayIndex;
3931 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3932 return CommonLength >= A.Entries.size() - IsArray;
3933 }
3934
3935 /// Find the complete object to which an LValue refers.
findCompleteObject(EvalInfo & Info,const Expr * E,AccessKinds AK,const LValue & LVal,QualType LValType)3936 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3937 AccessKinds AK, const LValue &LVal,
3938 QualType LValType) {
3939 if (LVal.InvalidBase) {
3940 Info.FFDiag(E);
3941 return CompleteObject();
3942 }
3943
3944 if (!LVal.Base) {
3945 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3946 return CompleteObject();
3947 }
3948
3949 CallStackFrame *Frame = nullptr;
3950 unsigned Depth = 0;
3951 if (LVal.getLValueCallIndex()) {
3952 std::tie(Frame, Depth) =
3953 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3954 if (!Frame) {
3955 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3956 << AK << LVal.Base.is<const ValueDecl*>();
3957 NoteLValueLocation(Info, LVal.Base);
3958 return CompleteObject();
3959 }
3960 }
3961
3962 bool IsAccess = isAnyAccess(AK);
3963
3964 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3965 // is not a constant expression (even if the object is non-volatile). We also
3966 // apply this rule to C++98, in order to conform to the expected 'volatile'
3967 // semantics.
3968 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3969 if (Info.getLangOpts().CPlusPlus)
3970 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3971 << AK << LValType;
3972 else
3973 Info.FFDiag(E);
3974 return CompleteObject();
3975 }
3976
3977 // Compute value storage location and type of base object.
3978 APValue *BaseVal = nullptr;
3979 QualType BaseType = getType(LVal.Base);
3980
3981 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
3982 lifetimeStartedInEvaluation(Info, LVal.Base)) {
3983 // This is the object whose initializer we're evaluating, so its lifetime
3984 // started in the current evaluation.
3985 BaseVal = Info.EvaluatingDeclValue;
3986 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3987 // Allow reading from a GUID declaration.
3988 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
3989 if (isModification(AK)) {
3990 // All the remaining cases do not permit modification of the object.
3991 Info.FFDiag(E, diag::note_constexpr_modify_global);
3992 return CompleteObject();
3993 }
3994 APValue &V = GD->getAsAPValue();
3995 if (V.isAbsent()) {
3996 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
3997 << GD->getType();
3998 return CompleteObject();
3999 }
4000 return CompleteObject(LVal.Base, &V, GD->getType());
4001 }
4002
4003 // Allow reading from template parameter objects.
4004 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4005 if (isModification(AK)) {
4006 Info.FFDiag(E, diag::note_constexpr_modify_global);
4007 return CompleteObject();
4008 }
4009 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4010 TPO->getType());
4011 }
4012
4013 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4014 // In C++11, constexpr, non-volatile variables initialized with constant
4015 // expressions are constant expressions too. Inside constexpr functions,
4016 // parameters are constant expressions even if they're non-const.
4017 // In C++1y, objects local to a constant expression (those with a Frame) are
4018 // both readable and writable inside constant expressions.
4019 // In C, such things can also be folded, although they are not ICEs.
4020 const VarDecl *VD = dyn_cast<VarDecl>(D);
4021 if (VD) {
4022 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4023 VD = VDef;
4024 }
4025 if (!VD || VD->isInvalidDecl()) {
4026 Info.FFDiag(E);
4027 return CompleteObject();
4028 }
4029
4030 bool IsConstant = BaseType.isConstant(Info.Ctx);
4031
4032 // Unless we're looking at a local variable or argument in a constexpr call,
4033 // the variable we're reading must be const.
4034 if (!Frame) {
4035 if (IsAccess && isa<ParmVarDecl>(VD)) {
4036 // Access of a parameter that's not associated with a frame isn't going
4037 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4038 // suitable diagnostic.
4039 } else if (Info.getLangOpts().CPlusPlus14 &&
4040 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4041 // OK, we can read and modify an object if we're in the process of
4042 // evaluating its initializer, because its lifetime began in this
4043 // evaluation.
4044 } else if (isModification(AK)) {
4045 // All the remaining cases do not permit modification of the object.
4046 Info.FFDiag(E, diag::note_constexpr_modify_global);
4047 return CompleteObject();
4048 } else if (VD->isConstexpr()) {
4049 // OK, we can read this variable.
4050 } else if (BaseType->isIntegralOrEnumerationType()) {
4051 if (!IsConstant) {
4052 if (!IsAccess)
4053 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4054 if (Info.getLangOpts().CPlusPlus) {
4055 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4056 Info.Note(VD->getLocation(), diag::note_declared_at);
4057 } else {
4058 Info.FFDiag(E);
4059 }
4060 return CompleteObject();
4061 }
4062 } else if (!IsAccess) {
4063 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4064 } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4065 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4066 // This variable might end up being constexpr. Don't diagnose it yet.
4067 } else if (IsConstant) {
4068 // Keep evaluating to see what we can do. In particular, we support
4069 // folding of const floating-point types, in order to make static const
4070 // data members of such types (supported as an extension) more useful.
4071 if (Info.getLangOpts().CPlusPlus) {
4072 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4073 ? diag::note_constexpr_ltor_non_constexpr
4074 : diag::note_constexpr_ltor_non_integral, 1)
4075 << VD << BaseType;
4076 Info.Note(VD->getLocation(), diag::note_declared_at);
4077 } else {
4078 Info.CCEDiag(E);
4079 }
4080 } else {
4081 // Never allow reading a non-const value.
4082 if (Info.getLangOpts().CPlusPlus) {
4083 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4084 ? diag::note_constexpr_ltor_non_constexpr
4085 : diag::note_constexpr_ltor_non_integral, 1)
4086 << VD << BaseType;
4087 Info.Note(VD->getLocation(), diag::note_declared_at);
4088 } else {
4089 Info.FFDiag(E);
4090 }
4091 return CompleteObject();
4092 }
4093 }
4094
4095 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4096 return CompleteObject();
4097 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4098 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4099 if (!Alloc) {
4100 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4101 return CompleteObject();
4102 }
4103 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4104 LVal.Base.getDynamicAllocType());
4105 } else {
4106 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4107
4108 if (!Frame) {
4109 if (const MaterializeTemporaryExpr *MTE =
4110 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4111 assert(MTE->getStorageDuration() == SD_Static &&
4112 "should have a frame for a non-global materialized temporary");
4113
4114 // C++20 [expr.const]p4: [DR2126]
4115 // An object or reference is usable in constant expressions if it is
4116 // - a temporary object of non-volatile const-qualified literal type
4117 // whose lifetime is extended to that of a variable that is usable
4118 // in constant expressions
4119 //
4120 // C++20 [expr.const]p5:
4121 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4122 // - a non-volatile glvalue that refers to an object that is usable
4123 // in constant expressions, or
4124 // - a non-volatile glvalue of literal type that refers to a
4125 // non-volatile object whose lifetime began within the evaluation
4126 // of E;
4127 //
4128 // C++11 misses the 'began within the evaluation of e' check and
4129 // instead allows all temporaries, including things like:
4130 // int &&r = 1;
4131 // int x = ++r;
4132 // constexpr int k = r;
4133 // Therefore we use the C++14-onwards rules in C++11 too.
4134 //
4135 // Note that temporaries whose lifetimes began while evaluating a
4136 // variable's constructor are not usable while evaluating the
4137 // corresponding destructor, not even if they're of const-qualified
4138 // types.
4139 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4140 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4141 if (!IsAccess)
4142 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4143 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4144 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4145 return CompleteObject();
4146 }
4147
4148 BaseVal = MTE->getOrCreateValue(false);
4149 assert(BaseVal && "got reference to unevaluated temporary");
4150 } else {
4151 if (!IsAccess)
4152 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4153 APValue Val;
4154 LVal.moveInto(Val);
4155 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4156 << AK
4157 << Val.getAsString(Info.Ctx,
4158 Info.Ctx.getLValueReferenceType(LValType));
4159 NoteLValueLocation(Info, LVal.Base);
4160 return CompleteObject();
4161 }
4162 } else {
4163 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4164 assert(BaseVal && "missing value for temporary");
4165 }
4166 }
4167
4168 // In C++14, we can't safely access any mutable state when we might be
4169 // evaluating after an unmodeled side effect. Parameters are modeled as state
4170 // in the caller, but aren't visible once the call returns, so they can be
4171 // modified in a speculatively-evaluated call.
4172 //
4173 // FIXME: Not all local state is mutable. Allow local constant subobjects
4174 // to be read here (but take care with 'mutable' fields).
4175 unsigned VisibleDepth = Depth;
4176 if (llvm::isa_and_nonnull<ParmVarDecl>(
4177 LVal.Base.dyn_cast<const ValueDecl *>()))
4178 ++VisibleDepth;
4179 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4180 Info.EvalStatus.HasSideEffects) ||
4181 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4182 return CompleteObject();
4183
4184 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4185 }
4186
4187 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4188 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4189 /// glvalue referred to by an entity of reference type.
4190 ///
4191 /// \param Info - Information about the ongoing evaluation.
4192 /// \param Conv - The expression for which we are performing the conversion.
4193 /// Used for diagnostics.
4194 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4195 /// case of a non-class type).
4196 /// \param LVal - The glvalue on which we are attempting to perform this action.
4197 /// \param RVal - The produced value will be placed here.
4198 /// \param WantObjectRepresentation - If true, we're looking for the object
4199 /// representation rather than the value, and in particular,
4200 /// there is no requirement that the result be fully initialized.
4201 static bool
handleLValueToRValueConversion(EvalInfo & Info,const Expr * Conv,QualType Type,const LValue & LVal,APValue & RVal,bool WantObjectRepresentation=false)4202 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4203 const LValue &LVal, APValue &RVal,
4204 bool WantObjectRepresentation = false) {
4205 if (LVal.Designator.Invalid)
4206 return false;
4207
4208 // Check for special cases where there is no existing APValue to look at.
4209 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4210
4211 AccessKinds AK =
4212 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4213
4214 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4215 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4216 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4217 // initializer until now for such expressions. Such an expression can't be
4218 // an ICE in C, so this only matters for fold.
4219 if (Type.isVolatileQualified()) {
4220 Info.FFDiag(Conv);
4221 return false;
4222 }
4223 APValue Lit;
4224 if (!Evaluate(Lit, Info, CLE->getInitializer()))
4225 return false;
4226 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4227 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4228 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4229 // Special-case character extraction so we don't have to construct an
4230 // APValue for the whole string.
4231 assert(LVal.Designator.Entries.size() <= 1 &&
4232 "Can only read characters from string literals");
4233 if (LVal.Designator.Entries.empty()) {
4234 // Fail for now for LValue to RValue conversion of an array.
4235 // (This shouldn't show up in C/C++, but it could be triggered by a
4236 // weird EvaluateAsRValue call from a tool.)
4237 Info.FFDiag(Conv);
4238 return false;
4239 }
4240 if (LVal.Designator.isOnePastTheEnd()) {
4241 if (Info.getLangOpts().CPlusPlus11)
4242 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4243 else
4244 Info.FFDiag(Conv);
4245 return false;
4246 }
4247 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4248 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4249 return true;
4250 }
4251 }
4252
4253 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4254 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4255 }
4256
4257 /// Perform an assignment of Val to LVal. Takes ownership of Val.
handleAssignment(EvalInfo & Info,const Expr * E,const LValue & LVal,QualType LValType,APValue & Val)4258 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4259 QualType LValType, APValue &Val) {
4260 if (LVal.Designator.Invalid)
4261 return false;
4262
4263 if (!Info.getLangOpts().CPlusPlus14) {
4264 Info.FFDiag(E);
4265 return false;
4266 }
4267
4268 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4269 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4270 }
4271
4272 namespace {
4273 struct CompoundAssignSubobjectHandler {
4274 EvalInfo &Info;
4275 const CompoundAssignOperator *E;
4276 QualType PromotedLHSType;
4277 BinaryOperatorKind Opcode;
4278 const APValue &RHS;
4279
4280 static const AccessKinds AccessKind = AK_Assign;
4281
4282 typedef bool result_type;
4283
checkConst__anon4717f8730c11::CompoundAssignSubobjectHandler4284 bool checkConst(QualType QT) {
4285 // Assigning to a const object has undefined behavior.
4286 if (QT.isConstQualified()) {
4287 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4288 return false;
4289 }
4290 return true;
4291 }
4292
failed__anon4717f8730c11::CompoundAssignSubobjectHandler4293 bool failed() { return false; }
found__anon4717f8730c11::CompoundAssignSubobjectHandler4294 bool found(APValue &Subobj, QualType SubobjType) {
4295 switch (Subobj.getKind()) {
4296 case APValue::Int:
4297 return found(Subobj.getInt(), SubobjType);
4298 case APValue::Float:
4299 return found(Subobj.getFloat(), SubobjType);
4300 case APValue::ComplexInt:
4301 case APValue::ComplexFloat:
4302 // FIXME: Implement complex compound assignment.
4303 Info.FFDiag(E);
4304 return false;
4305 case APValue::LValue:
4306 return foundPointer(Subobj, SubobjType);
4307 case APValue::Vector:
4308 return foundVector(Subobj, SubobjType);
4309 default:
4310 // FIXME: can this happen?
4311 Info.FFDiag(E);
4312 return false;
4313 }
4314 }
4315
foundVector__anon4717f8730c11::CompoundAssignSubobjectHandler4316 bool foundVector(APValue &Value, QualType SubobjType) {
4317 if (!checkConst(SubobjType))
4318 return false;
4319
4320 if (!SubobjType->isVectorType()) {
4321 Info.FFDiag(E);
4322 return false;
4323 }
4324 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4325 }
4326
found__anon4717f8730c11::CompoundAssignSubobjectHandler4327 bool found(APSInt &Value, QualType SubobjType) {
4328 if (!checkConst(SubobjType))
4329 return false;
4330
4331 if (!SubobjType->isIntegerType()) {
4332 // We don't support compound assignment on integer-cast-to-pointer
4333 // values.
4334 Info.FFDiag(E);
4335 return false;
4336 }
4337
4338 if (RHS.isInt()) {
4339 APSInt LHS =
4340 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4341 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4342 return false;
4343 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4344 return true;
4345 } else if (RHS.isFloat()) {
4346 const FPOptions FPO = E->getFPFeaturesInEffect(
4347 Info.Ctx.getLangOpts());
4348 APFloat FValue(0.0);
4349 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4350 PromotedLHSType, FValue) &&
4351 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4352 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4353 Value);
4354 }
4355
4356 Info.FFDiag(E);
4357 return false;
4358 }
found__anon4717f8730c11::CompoundAssignSubobjectHandler4359 bool found(APFloat &Value, QualType SubobjType) {
4360 return checkConst(SubobjType) &&
4361 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4362 Value) &&
4363 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4364 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4365 }
foundPointer__anon4717f8730c11::CompoundAssignSubobjectHandler4366 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4367 if (!checkConst(SubobjType))
4368 return false;
4369
4370 QualType PointeeType;
4371 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4372 PointeeType = PT->getPointeeType();
4373
4374 if (PointeeType.isNull() || !RHS.isInt() ||
4375 (Opcode != BO_Add && Opcode != BO_Sub)) {
4376 Info.FFDiag(E);
4377 return false;
4378 }
4379
4380 APSInt Offset = RHS.getInt();
4381 if (Opcode == BO_Sub)
4382 negateAsSigned(Offset);
4383
4384 LValue LVal;
4385 LVal.setFrom(Info.Ctx, Subobj);
4386 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4387 return false;
4388 LVal.moveInto(Subobj);
4389 return true;
4390 }
4391 };
4392 } // end anonymous namespace
4393
4394 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4395
4396 /// Perform a compound assignment of LVal <op>= RVal.
handleCompoundAssignment(EvalInfo & Info,const CompoundAssignOperator * E,const LValue & LVal,QualType LValType,QualType PromotedLValType,BinaryOperatorKind Opcode,const APValue & RVal)4397 static bool handleCompoundAssignment(EvalInfo &Info,
4398 const CompoundAssignOperator *E,
4399 const LValue &LVal, QualType LValType,
4400 QualType PromotedLValType,
4401 BinaryOperatorKind Opcode,
4402 const APValue &RVal) {
4403 if (LVal.Designator.Invalid)
4404 return false;
4405
4406 if (!Info.getLangOpts().CPlusPlus14) {
4407 Info.FFDiag(E);
4408 return false;
4409 }
4410
4411 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4412 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4413 RVal };
4414 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4415 }
4416
4417 namespace {
4418 struct IncDecSubobjectHandler {
4419 EvalInfo &Info;
4420 const UnaryOperator *E;
4421 AccessKinds AccessKind;
4422 APValue *Old;
4423
4424 typedef bool result_type;
4425
checkConst__anon4717f8730d11::IncDecSubobjectHandler4426 bool checkConst(QualType QT) {
4427 // Assigning to a const object has undefined behavior.
4428 if (QT.isConstQualified()) {
4429 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4430 return false;
4431 }
4432 return true;
4433 }
4434
failed__anon4717f8730d11::IncDecSubobjectHandler4435 bool failed() { return false; }
found__anon4717f8730d11::IncDecSubobjectHandler4436 bool found(APValue &Subobj, QualType SubobjType) {
4437 // Stash the old value. Also clear Old, so we don't clobber it later
4438 // if we're post-incrementing a complex.
4439 if (Old) {
4440 *Old = Subobj;
4441 Old = nullptr;
4442 }
4443
4444 switch (Subobj.getKind()) {
4445 case APValue::Int:
4446 return found(Subobj.getInt(), SubobjType);
4447 case APValue::Float:
4448 return found(Subobj.getFloat(), SubobjType);
4449 case APValue::ComplexInt:
4450 return found(Subobj.getComplexIntReal(),
4451 SubobjType->castAs<ComplexType>()->getElementType()
4452 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4453 case APValue::ComplexFloat:
4454 return found(Subobj.getComplexFloatReal(),
4455 SubobjType->castAs<ComplexType>()->getElementType()
4456 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4457 case APValue::LValue:
4458 return foundPointer(Subobj, SubobjType);
4459 default:
4460 // FIXME: can this happen?
4461 Info.FFDiag(E);
4462 return false;
4463 }
4464 }
found__anon4717f8730d11::IncDecSubobjectHandler4465 bool found(APSInt &Value, QualType SubobjType) {
4466 if (!checkConst(SubobjType))
4467 return false;
4468
4469 if (!SubobjType->isIntegerType()) {
4470 // We don't support increment / decrement on integer-cast-to-pointer
4471 // values.
4472 Info.FFDiag(E);
4473 return false;
4474 }
4475
4476 if (Old) *Old = APValue(Value);
4477
4478 // bool arithmetic promotes to int, and the conversion back to bool
4479 // doesn't reduce mod 2^n, so special-case it.
4480 if (SubobjType->isBooleanType()) {
4481 if (AccessKind == AK_Increment)
4482 Value = 1;
4483 else
4484 Value = !Value;
4485 return true;
4486 }
4487
4488 bool WasNegative = Value.isNegative();
4489 if (AccessKind == AK_Increment) {
4490 ++Value;
4491
4492 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4493 APSInt ActualValue(Value, /*IsUnsigned*/true);
4494 return HandleOverflow(Info, E, ActualValue, SubobjType);
4495 }
4496 } else {
4497 --Value;
4498
4499 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4500 unsigned BitWidth = Value.getBitWidth();
4501 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4502 ActualValue.setBit(BitWidth);
4503 return HandleOverflow(Info, E, ActualValue, SubobjType);
4504 }
4505 }
4506 return true;
4507 }
found__anon4717f8730d11::IncDecSubobjectHandler4508 bool found(APFloat &Value, QualType SubobjType) {
4509 if (!checkConst(SubobjType))
4510 return false;
4511
4512 if (Old) *Old = APValue(Value);
4513
4514 APFloat One(Value.getSemantics(), 1);
4515 if (AccessKind == AK_Increment)
4516 Value.add(One, APFloat::rmNearestTiesToEven);
4517 else
4518 Value.subtract(One, APFloat::rmNearestTiesToEven);
4519 return true;
4520 }
foundPointer__anon4717f8730d11::IncDecSubobjectHandler4521 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4522 if (!checkConst(SubobjType))
4523 return false;
4524
4525 QualType PointeeType;
4526 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4527 PointeeType = PT->getPointeeType();
4528 else {
4529 Info.FFDiag(E);
4530 return false;
4531 }
4532
4533 LValue LVal;
4534 LVal.setFrom(Info.Ctx, Subobj);
4535 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4536 AccessKind == AK_Increment ? 1 : -1))
4537 return false;
4538 LVal.moveInto(Subobj);
4539 return true;
4540 }
4541 };
4542 } // end anonymous namespace
4543
4544 /// Perform an increment or decrement on LVal.
handleIncDec(EvalInfo & Info,const Expr * E,const LValue & LVal,QualType LValType,bool IsIncrement,APValue * Old)4545 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4546 QualType LValType, bool IsIncrement, APValue *Old) {
4547 if (LVal.Designator.Invalid)
4548 return false;
4549
4550 if (!Info.getLangOpts().CPlusPlus14) {
4551 Info.FFDiag(E);
4552 return false;
4553 }
4554
4555 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4556 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4557 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4558 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4559 }
4560
4561 /// Build an lvalue for the object argument of a member function call.
EvaluateObjectArgument(EvalInfo & Info,const Expr * Object,LValue & This)4562 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4563 LValue &This) {
4564 if (Object->getType()->isPointerType() && Object->isRValue())
4565 return EvaluatePointer(Object, This, Info);
4566
4567 if (Object->isGLValue())
4568 return EvaluateLValue(Object, This, Info);
4569
4570 if (Object->getType()->isLiteralType(Info.Ctx))
4571 return EvaluateTemporary(Object, This, Info);
4572
4573 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4574 return false;
4575 }
4576
4577 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4578 /// lvalue referring to the result.
4579 ///
4580 /// \param Info - Information about the ongoing evaluation.
4581 /// \param LV - An lvalue referring to the base of the member pointer.
4582 /// \param RHS - The member pointer expression.
4583 /// \param IncludeMember - Specifies whether the member itself is included in
4584 /// the resulting LValue subobject designator. This is not possible when
4585 /// creating a bound member function.
4586 /// \return The field or method declaration to which the member pointer refers,
4587 /// or 0 if evaluation fails.
HandleMemberPointerAccess(EvalInfo & Info,QualType LVType,LValue & LV,const Expr * RHS,bool IncludeMember=true)4588 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4589 QualType LVType,
4590 LValue &LV,
4591 const Expr *RHS,
4592 bool IncludeMember = true) {
4593 MemberPtr MemPtr;
4594 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4595 return nullptr;
4596
4597 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4598 // member value, the behavior is undefined.
4599 if (!MemPtr.getDecl()) {
4600 // FIXME: Specific diagnostic.
4601 Info.FFDiag(RHS);
4602 return nullptr;
4603 }
4604
4605 if (MemPtr.isDerivedMember()) {
4606 // This is a member of some derived class. Truncate LV appropriately.
4607 // The end of the derived-to-base path for the base object must match the
4608 // derived-to-base path for the member pointer.
4609 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4610 LV.Designator.Entries.size()) {
4611 Info.FFDiag(RHS);
4612 return nullptr;
4613 }
4614 unsigned PathLengthToMember =
4615 LV.Designator.Entries.size() - MemPtr.Path.size();
4616 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4617 const CXXRecordDecl *LVDecl = getAsBaseClass(
4618 LV.Designator.Entries[PathLengthToMember + I]);
4619 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4620 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4621 Info.FFDiag(RHS);
4622 return nullptr;
4623 }
4624 }
4625
4626 // Truncate the lvalue to the appropriate derived class.
4627 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4628 PathLengthToMember))
4629 return nullptr;
4630 } else if (!MemPtr.Path.empty()) {
4631 // Extend the LValue path with the member pointer's path.
4632 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4633 MemPtr.Path.size() + IncludeMember);
4634
4635 // Walk down to the appropriate base class.
4636 if (const PointerType *PT = LVType->getAs<PointerType>())
4637 LVType = PT->getPointeeType();
4638 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4639 assert(RD && "member pointer access on non-class-type expression");
4640 // The first class in the path is that of the lvalue.
4641 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4642 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4643 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4644 return nullptr;
4645 RD = Base;
4646 }
4647 // Finally cast to the class containing the member.
4648 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4649 MemPtr.getContainingRecord()))
4650 return nullptr;
4651 }
4652
4653 // Add the member. Note that we cannot build bound member functions here.
4654 if (IncludeMember) {
4655 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4656 if (!HandleLValueMember(Info, RHS, LV, FD))
4657 return nullptr;
4658 } else if (const IndirectFieldDecl *IFD =
4659 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4660 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4661 return nullptr;
4662 } else {
4663 llvm_unreachable("can't construct reference to bound member function");
4664 }
4665 }
4666
4667 return MemPtr.getDecl();
4668 }
4669
HandleMemberPointerAccess(EvalInfo & Info,const BinaryOperator * BO,LValue & LV,bool IncludeMember=true)4670 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4671 const BinaryOperator *BO,
4672 LValue &LV,
4673 bool IncludeMember = true) {
4674 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4675
4676 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4677 if (Info.noteFailure()) {
4678 MemberPtr MemPtr;
4679 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4680 }
4681 return nullptr;
4682 }
4683
4684 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4685 BO->getRHS(), IncludeMember);
4686 }
4687
4688 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4689 /// the provided lvalue, which currently refers to the base object.
HandleBaseToDerivedCast(EvalInfo & Info,const CastExpr * E,LValue & Result)4690 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4691 LValue &Result) {
4692 SubobjectDesignator &D = Result.Designator;
4693 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4694 return false;
4695
4696 QualType TargetQT = E->getType();
4697 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4698 TargetQT = PT->getPointeeType();
4699
4700 // Check this cast lands within the final derived-to-base subobject path.
4701 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4702 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4703 << D.MostDerivedType << TargetQT;
4704 return false;
4705 }
4706
4707 // Check the type of the final cast. We don't need to check the path,
4708 // since a cast can only be formed if the path is unique.
4709 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4710 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4711 const CXXRecordDecl *FinalType;
4712 if (NewEntriesSize == D.MostDerivedPathLength)
4713 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4714 else
4715 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4716 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4717 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4718 << D.MostDerivedType << TargetQT;
4719 return false;
4720 }
4721
4722 // Truncate the lvalue to the appropriate derived class.
4723 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4724 }
4725
4726 /// Get the value to use for a default-initialized object of type T.
4727 /// Return false if it encounters something invalid.
getDefaultInitValue(QualType T,APValue & Result)4728 static bool getDefaultInitValue(QualType T, APValue &Result) {
4729 bool Success = true;
4730 if (auto *RD = T->getAsCXXRecordDecl()) {
4731 if (RD->isInvalidDecl()) {
4732 Result = APValue();
4733 return false;
4734 }
4735 if (RD->isUnion()) {
4736 Result = APValue((const FieldDecl *)nullptr);
4737 return true;
4738 }
4739 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4740 std::distance(RD->field_begin(), RD->field_end()));
4741
4742 unsigned Index = 0;
4743 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4744 End = RD->bases_end();
4745 I != End; ++I, ++Index)
4746 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4747
4748 for (const auto *I : RD->fields()) {
4749 if (I->isUnnamedBitfield())
4750 continue;
4751 Success &= getDefaultInitValue(I->getType(),
4752 Result.getStructField(I->getFieldIndex()));
4753 }
4754 return Success;
4755 }
4756
4757 if (auto *AT =
4758 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4759 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4760 if (Result.hasArrayFiller())
4761 Success &=
4762 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4763
4764 return Success;
4765 }
4766
4767 Result = APValue::IndeterminateValue();
4768 return true;
4769 }
4770
4771 namespace {
4772 enum EvalStmtResult {
4773 /// Evaluation failed.
4774 ESR_Failed,
4775 /// Hit a 'return' statement.
4776 ESR_Returned,
4777 /// Evaluation succeeded.
4778 ESR_Succeeded,
4779 /// Hit a 'continue' statement.
4780 ESR_Continue,
4781 /// Hit a 'break' statement.
4782 ESR_Break,
4783 /// Still scanning for 'case' or 'default' statement.
4784 ESR_CaseNotFound
4785 };
4786 }
4787
EvaluateVarDecl(EvalInfo & Info,const VarDecl * VD)4788 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4789 // We don't need to evaluate the initializer for a static local.
4790 if (!VD->hasLocalStorage())
4791 return true;
4792
4793 LValue Result;
4794 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4795 ScopeKind::Block, Result);
4796
4797 const Expr *InitE = VD->getInit();
4798 if (!InitE)
4799 return getDefaultInitValue(VD->getType(), Val);
4800
4801 if (InitE->isValueDependent())
4802 return false;
4803
4804 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4805 // Wipe out any partially-computed value, to allow tracking that this
4806 // evaluation failed.
4807 Val = APValue();
4808 return false;
4809 }
4810
4811 return true;
4812 }
4813
EvaluateDecl(EvalInfo & Info,const Decl * D)4814 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4815 bool OK = true;
4816
4817 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4818 OK &= EvaluateVarDecl(Info, VD);
4819
4820 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4821 for (auto *BD : DD->bindings())
4822 if (auto *VD = BD->getHoldingVar())
4823 OK &= EvaluateDecl(Info, VD);
4824
4825 return OK;
4826 }
4827
4828
4829 /// Evaluate a condition (either a variable declaration or an expression).
EvaluateCond(EvalInfo & Info,const VarDecl * CondDecl,const Expr * Cond,bool & Result)4830 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4831 const Expr *Cond, bool &Result) {
4832 FullExpressionRAII Scope(Info);
4833 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4834 return false;
4835 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4836 return false;
4837 return Scope.destroy();
4838 }
4839
4840 namespace {
4841 /// A location where the result (returned value) of evaluating a
4842 /// statement should be stored.
4843 struct StmtResult {
4844 /// The APValue that should be filled in with the returned value.
4845 APValue &Value;
4846 /// The location containing the result, if any (used to support RVO).
4847 const LValue *Slot;
4848 };
4849
4850 struct TempVersionRAII {
4851 CallStackFrame &Frame;
4852
TempVersionRAII__anon4717f8730f11::TempVersionRAII4853 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4854 Frame.pushTempVersion();
4855 }
4856
~TempVersionRAII__anon4717f8730f11::TempVersionRAII4857 ~TempVersionRAII() {
4858 Frame.popTempVersion();
4859 }
4860 };
4861
4862 }
4863
4864 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4865 const Stmt *S,
4866 const SwitchCase *SC = nullptr);
4867
4868 /// Evaluate the body of a loop, and translate the result as appropriate.
EvaluateLoopBody(StmtResult & Result,EvalInfo & Info,const Stmt * Body,const SwitchCase * Case=nullptr)4869 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4870 const Stmt *Body,
4871 const SwitchCase *Case = nullptr) {
4872 BlockScopeRAII Scope(Info);
4873
4874 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4875 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4876 ESR = ESR_Failed;
4877
4878 switch (ESR) {
4879 case ESR_Break:
4880 return ESR_Succeeded;
4881 case ESR_Succeeded:
4882 case ESR_Continue:
4883 return ESR_Continue;
4884 case ESR_Failed:
4885 case ESR_Returned:
4886 case ESR_CaseNotFound:
4887 return ESR;
4888 }
4889 llvm_unreachable("Invalid EvalStmtResult!");
4890 }
4891
4892 /// Evaluate a switch statement.
EvaluateSwitch(StmtResult & Result,EvalInfo & Info,const SwitchStmt * SS)4893 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4894 const SwitchStmt *SS) {
4895 BlockScopeRAII Scope(Info);
4896
4897 // Evaluate the switch condition.
4898 APSInt Value;
4899 {
4900 if (const Stmt *Init = SS->getInit()) {
4901 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4902 if (ESR != ESR_Succeeded) {
4903 if (ESR != ESR_Failed && !Scope.destroy())
4904 ESR = ESR_Failed;
4905 return ESR;
4906 }
4907 }
4908
4909 FullExpressionRAII CondScope(Info);
4910 if (SS->getConditionVariable() &&
4911 !EvaluateDecl(Info, SS->getConditionVariable()))
4912 return ESR_Failed;
4913 if (!EvaluateInteger(SS->getCond(), Value, Info))
4914 return ESR_Failed;
4915 if (!CondScope.destroy())
4916 return ESR_Failed;
4917 }
4918
4919 // Find the switch case corresponding to the value of the condition.
4920 // FIXME: Cache this lookup.
4921 const SwitchCase *Found = nullptr;
4922 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4923 SC = SC->getNextSwitchCase()) {
4924 if (isa<DefaultStmt>(SC)) {
4925 Found = SC;
4926 continue;
4927 }
4928
4929 const CaseStmt *CS = cast<CaseStmt>(SC);
4930 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4931 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4932 : LHS;
4933 if (LHS <= Value && Value <= RHS) {
4934 Found = SC;
4935 break;
4936 }
4937 }
4938
4939 if (!Found)
4940 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4941
4942 // Search the switch body for the switch case and evaluate it from there.
4943 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4944 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4945 return ESR_Failed;
4946
4947 switch (ESR) {
4948 case ESR_Break:
4949 return ESR_Succeeded;
4950 case ESR_Succeeded:
4951 case ESR_Continue:
4952 case ESR_Failed:
4953 case ESR_Returned:
4954 return ESR;
4955 case ESR_CaseNotFound:
4956 // This can only happen if the switch case is nested within a statement
4957 // expression. We have no intention of supporting that.
4958 Info.FFDiag(Found->getBeginLoc(),
4959 diag::note_constexpr_stmt_expr_unsupported);
4960 return ESR_Failed;
4961 }
4962 llvm_unreachable("Invalid EvalStmtResult!");
4963 }
4964
4965 // Evaluate a statement.
EvaluateStmt(StmtResult & Result,EvalInfo & Info,const Stmt * S,const SwitchCase * Case)4966 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4967 const Stmt *S, const SwitchCase *Case) {
4968 if (!Info.nextStep(S))
4969 return ESR_Failed;
4970
4971 // If we're hunting down a 'case' or 'default' label, recurse through
4972 // substatements until we hit the label.
4973 if (Case) {
4974 switch (S->getStmtClass()) {
4975 case Stmt::CompoundStmtClass:
4976 // FIXME: Precompute which substatement of a compound statement we
4977 // would jump to, and go straight there rather than performing a
4978 // linear scan each time.
4979 case Stmt::LabelStmtClass:
4980 case Stmt::AttributedStmtClass:
4981 case Stmt::DoStmtClass:
4982 break;
4983
4984 case Stmt::CaseStmtClass:
4985 case Stmt::DefaultStmtClass:
4986 if (Case == S)
4987 Case = nullptr;
4988 break;
4989
4990 case Stmt::IfStmtClass: {
4991 // FIXME: Precompute which side of an 'if' we would jump to, and go
4992 // straight there rather than scanning both sides.
4993 const IfStmt *IS = cast<IfStmt>(S);
4994
4995 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4996 // preceded by our switch label.
4997 BlockScopeRAII Scope(Info);
4998
4999 // Step into the init statement in case it brings an (uninitialized)
5000 // variable into scope.
5001 if (const Stmt *Init = IS->getInit()) {
5002 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5003 if (ESR != ESR_CaseNotFound) {
5004 assert(ESR != ESR_Succeeded);
5005 return ESR;
5006 }
5007 }
5008
5009 // Condition variable must be initialized if it exists.
5010 // FIXME: We can skip evaluating the body if there's a condition
5011 // variable, as there can't be any case labels within it.
5012 // (The same is true for 'for' statements.)
5013
5014 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5015 if (ESR == ESR_Failed)
5016 return ESR;
5017 if (ESR != ESR_CaseNotFound)
5018 return Scope.destroy() ? ESR : ESR_Failed;
5019 if (!IS->getElse())
5020 return ESR_CaseNotFound;
5021
5022 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5023 if (ESR == ESR_Failed)
5024 return ESR;
5025 if (ESR != ESR_CaseNotFound)
5026 return Scope.destroy() ? ESR : ESR_Failed;
5027 return ESR_CaseNotFound;
5028 }
5029
5030 case Stmt::WhileStmtClass: {
5031 EvalStmtResult ESR =
5032 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5033 if (ESR != ESR_Continue)
5034 return ESR;
5035 break;
5036 }
5037
5038 case Stmt::ForStmtClass: {
5039 const ForStmt *FS = cast<ForStmt>(S);
5040 BlockScopeRAII Scope(Info);
5041
5042 // Step into the init statement in case it brings an (uninitialized)
5043 // variable into scope.
5044 if (const Stmt *Init = FS->getInit()) {
5045 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5046 if (ESR != ESR_CaseNotFound) {
5047 assert(ESR != ESR_Succeeded);
5048 return ESR;
5049 }
5050 }
5051
5052 EvalStmtResult ESR =
5053 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5054 if (ESR != ESR_Continue)
5055 return ESR;
5056 if (FS->getInc()) {
5057 FullExpressionRAII IncScope(Info);
5058 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
5059 return ESR_Failed;
5060 }
5061 break;
5062 }
5063
5064 case Stmt::DeclStmtClass: {
5065 // Start the lifetime of any uninitialized variables we encounter. They
5066 // might be used by the selected branch of the switch.
5067 const DeclStmt *DS = cast<DeclStmt>(S);
5068 for (const auto *D : DS->decls()) {
5069 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5070 if (VD->hasLocalStorage() && !VD->getInit())
5071 if (!EvaluateVarDecl(Info, VD))
5072 return ESR_Failed;
5073 // FIXME: If the variable has initialization that can't be jumped
5074 // over, bail out of any immediately-surrounding compound-statement
5075 // too. There can't be any case labels here.
5076 }
5077 }
5078 return ESR_CaseNotFound;
5079 }
5080
5081 default:
5082 return ESR_CaseNotFound;
5083 }
5084 }
5085
5086 switch (S->getStmtClass()) {
5087 default:
5088 if (const Expr *E = dyn_cast<Expr>(S)) {
5089 // Don't bother evaluating beyond an expression-statement which couldn't
5090 // be evaluated.
5091 // FIXME: Do we need the FullExpressionRAII object here?
5092 // VisitExprWithCleanups should create one when necessary.
5093 FullExpressionRAII Scope(Info);
5094 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5095 return ESR_Failed;
5096 return ESR_Succeeded;
5097 }
5098
5099 Info.FFDiag(S->getBeginLoc());
5100 return ESR_Failed;
5101
5102 case Stmt::NullStmtClass:
5103 return ESR_Succeeded;
5104
5105 case Stmt::DeclStmtClass: {
5106 const DeclStmt *DS = cast<DeclStmt>(S);
5107 for (const auto *D : DS->decls()) {
5108 // Each declaration initialization is its own full-expression.
5109 FullExpressionRAII Scope(Info);
5110 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5111 return ESR_Failed;
5112 if (!Scope.destroy())
5113 return ESR_Failed;
5114 }
5115 return ESR_Succeeded;
5116 }
5117
5118 case Stmt::ReturnStmtClass: {
5119 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5120 FullExpressionRAII Scope(Info);
5121 if (RetExpr &&
5122 !(Result.Slot
5123 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5124 : Evaluate(Result.Value, Info, RetExpr)))
5125 return ESR_Failed;
5126 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5127 }
5128
5129 case Stmt::CompoundStmtClass: {
5130 BlockScopeRAII Scope(Info);
5131
5132 const CompoundStmt *CS = cast<CompoundStmt>(S);
5133 for (const auto *BI : CS->body()) {
5134 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5135 if (ESR == ESR_Succeeded)
5136 Case = nullptr;
5137 else if (ESR != ESR_CaseNotFound) {
5138 if (ESR != ESR_Failed && !Scope.destroy())
5139 return ESR_Failed;
5140 return ESR;
5141 }
5142 }
5143 if (Case)
5144 return ESR_CaseNotFound;
5145 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5146 }
5147
5148 case Stmt::IfStmtClass: {
5149 const IfStmt *IS = cast<IfStmt>(S);
5150
5151 // Evaluate the condition, as either a var decl or as an expression.
5152 BlockScopeRAII Scope(Info);
5153 if (const Stmt *Init = IS->getInit()) {
5154 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5155 if (ESR != ESR_Succeeded) {
5156 if (ESR != ESR_Failed && !Scope.destroy())
5157 return ESR_Failed;
5158 return ESR;
5159 }
5160 }
5161 bool Cond;
5162 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
5163 return ESR_Failed;
5164
5165 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5166 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5167 if (ESR != ESR_Succeeded) {
5168 if (ESR != ESR_Failed && !Scope.destroy())
5169 return ESR_Failed;
5170 return ESR;
5171 }
5172 }
5173 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5174 }
5175
5176 case Stmt::WhileStmtClass: {
5177 const WhileStmt *WS = cast<WhileStmt>(S);
5178 while (true) {
5179 BlockScopeRAII Scope(Info);
5180 bool Continue;
5181 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5182 Continue))
5183 return ESR_Failed;
5184 if (!Continue)
5185 break;
5186
5187 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5188 if (ESR != ESR_Continue) {
5189 if (ESR != ESR_Failed && !Scope.destroy())
5190 return ESR_Failed;
5191 return ESR;
5192 }
5193 if (!Scope.destroy())
5194 return ESR_Failed;
5195 }
5196 return ESR_Succeeded;
5197 }
5198
5199 case Stmt::DoStmtClass: {
5200 const DoStmt *DS = cast<DoStmt>(S);
5201 bool Continue;
5202 do {
5203 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5204 if (ESR != ESR_Continue)
5205 return ESR;
5206 Case = nullptr;
5207
5208 FullExpressionRAII CondScope(Info);
5209 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5210 !CondScope.destroy())
5211 return ESR_Failed;
5212 } while (Continue);
5213 return ESR_Succeeded;
5214 }
5215
5216 case Stmt::ForStmtClass: {
5217 const ForStmt *FS = cast<ForStmt>(S);
5218 BlockScopeRAII ForScope(Info);
5219 if (FS->getInit()) {
5220 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5221 if (ESR != ESR_Succeeded) {
5222 if (ESR != ESR_Failed && !ForScope.destroy())
5223 return ESR_Failed;
5224 return ESR;
5225 }
5226 }
5227 while (true) {
5228 BlockScopeRAII IterScope(Info);
5229 bool Continue = true;
5230 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5231 FS->getCond(), Continue))
5232 return ESR_Failed;
5233 if (!Continue)
5234 break;
5235
5236 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5237 if (ESR != ESR_Continue) {
5238 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5239 return ESR_Failed;
5240 return ESR;
5241 }
5242
5243 if (FS->getInc()) {
5244 FullExpressionRAII IncScope(Info);
5245 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
5246 return ESR_Failed;
5247 }
5248
5249 if (!IterScope.destroy())
5250 return ESR_Failed;
5251 }
5252 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5253 }
5254
5255 case Stmt::CXXForRangeStmtClass: {
5256 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5257 BlockScopeRAII Scope(Info);
5258
5259 // Evaluate the init-statement if present.
5260 if (FS->getInit()) {
5261 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5262 if (ESR != ESR_Succeeded) {
5263 if (ESR != ESR_Failed && !Scope.destroy())
5264 return ESR_Failed;
5265 return ESR;
5266 }
5267 }
5268
5269 // Initialize the __range variable.
5270 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5271 if (ESR != ESR_Succeeded) {
5272 if (ESR != ESR_Failed && !Scope.destroy())
5273 return ESR_Failed;
5274 return ESR;
5275 }
5276
5277 // Create the __begin and __end iterators.
5278 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5279 if (ESR != ESR_Succeeded) {
5280 if (ESR != ESR_Failed && !Scope.destroy())
5281 return ESR_Failed;
5282 return ESR;
5283 }
5284 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5285 if (ESR != ESR_Succeeded) {
5286 if (ESR != ESR_Failed && !Scope.destroy())
5287 return ESR_Failed;
5288 return ESR;
5289 }
5290
5291 while (true) {
5292 // Condition: __begin != __end.
5293 {
5294 bool Continue = true;
5295 FullExpressionRAII CondExpr(Info);
5296 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5297 return ESR_Failed;
5298 if (!Continue)
5299 break;
5300 }
5301
5302 // User's variable declaration, initialized by *__begin.
5303 BlockScopeRAII InnerScope(Info);
5304 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5305 if (ESR != ESR_Succeeded) {
5306 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5307 return ESR_Failed;
5308 return ESR;
5309 }
5310
5311 // Loop body.
5312 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5313 if (ESR != ESR_Continue) {
5314 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5315 return ESR_Failed;
5316 return ESR;
5317 }
5318
5319 // Increment: ++__begin
5320 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5321 return ESR_Failed;
5322
5323 if (!InnerScope.destroy())
5324 return ESR_Failed;
5325 }
5326
5327 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5328 }
5329
5330 case Stmt::SwitchStmtClass:
5331 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5332
5333 case Stmt::ContinueStmtClass:
5334 return ESR_Continue;
5335
5336 case Stmt::BreakStmtClass:
5337 return ESR_Break;
5338
5339 case Stmt::LabelStmtClass:
5340 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5341
5342 case Stmt::AttributedStmtClass:
5343 // As a general principle, C++11 attributes can be ignored without
5344 // any semantic impact.
5345 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5346 Case);
5347
5348 case Stmt::CaseStmtClass:
5349 case Stmt::DefaultStmtClass:
5350 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5351 case Stmt::CXXTryStmtClass:
5352 // Evaluate try blocks by evaluating all sub statements.
5353 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5354 }
5355 }
5356
5357 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5358 /// default constructor. If so, we'll fold it whether or not it's marked as
5359 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5360 /// so we need special handling.
CheckTrivialDefaultConstructor(EvalInfo & Info,SourceLocation Loc,const CXXConstructorDecl * CD,bool IsValueInitialization)5361 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5362 const CXXConstructorDecl *CD,
5363 bool IsValueInitialization) {
5364 if (!CD->isTrivial() || !CD->isDefaultConstructor())
5365 return false;
5366
5367 // Value-initialization does not call a trivial default constructor, so such a
5368 // call is a core constant expression whether or not the constructor is
5369 // constexpr.
5370 if (!CD->isConstexpr() && !IsValueInitialization) {
5371 if (Info.getLangOpts().CPlusPlus11) {
5372 // FIXME: If DiagDecl is an implicitly-declared special member function,
5373 // we should be much more explicit about why it's not constexpr.
5374 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5375 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5376 Info.Note(CD->getLocation(), diag::note_declared_at);
5377 } else {
5378 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5379 }
5380 }
5381 return true;
5382 }
5383
5384 /// CheckConstexprFunction - Check that a function can be called in a constant
5385 /// expression.
CheckConstexprFunction(EvalInfo & Info,SourceLocation CallLoc,const FunctionDecl * Declaration,const FunctionDecl * Definition,const Stmt * Body)5386 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5387 const FunctionDecl *Declaration,
5388 const FunctionDecl *Definition,
5389 const Stmt *Body) {
5390 // Potential constant expressions can contain calls to declared, but not yet
5391 // defined, constexpr functions.
5392 if (Info.checkingPotentialConstantExpression() && !Definition &&
5393 Declaration->isConstexpr())
5394 return false;
5395
5396 // Bail out if the function declaration itself is invalid. We will
5397 // have produced a relevant diagnostic while parsing it, so just
5398 // note the problematic sub-expression.
5399 if (Declaration->isInvalidDecl()) {
5400 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5401 return false;
5402 }
5403
5404 // DR1872: An instantiated virtual constexpr function can't be called in a
5405 // constant expression (prior to C++20). We can still constant-fold such a
5406 // call.
5407 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5408 cast<CXXMethodDecl>(Declaration)->isVirtual())
5409 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5410
5411 if (Definition && Definition->isInvalidDecl()) {
5412 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5413 return false;
5414 }
5415
5416 if (const auto *CtorDecl = dyn_cast_or_null<CXXConstructorDecl>(Definition)) {
5417 for (const auto *InitExpr : CtorDecl->inits()) {
5418 if (InitExpr->getInit() && InitExpr->getInit()->containsErrors())
5419 return false;
5420 }
5421 }
5422
5423 // Can we evaluate this function call?
5424 if (Definition && Definition->isConstexpr() && Body)
5425 return true;
5426
5427 if (Info.getLangOpts().CPlusPlus11) {
5428 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5429
5430 // If this function is not constexpr because it is an inherited
5431 // non-constexpr constructor, diagnose that directly.
5432 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5433 if (CD && CD->isInheritingConstructor()) {
5434 auto *Inherited = CD->getInheritedConstructor().getConstructor();
5435 if (!Inherited->isConstexpr())
5436 DiagDecl = CD = Inherited;
5437 }
5438
5439 // FIXME: If DiagDecl is an implicitly-declared special member function
5440 // or an inheriting constructor, we should be much more explicit about why
5441 // it's not constexpr.
5442 if (CD && CD->isInheritingConstructor())
5443 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5444 << CD->getInheritedConstructor().getConstructor()->getParent();
5445 else
5446 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5447 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5448 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5449 } else {
5450 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5451 }
5452 return false;
5453 }
5454
5455 namespace {
5456 struct CheckDynamicTypeHandler {
5457 AccessKinds AccessKind;
5458 typedef bool result_type;
failed__anon4717f8731011::CheckDynamicTypeHandler5459 bool failed() { return false; }
found__anon4717f8731011::CheckDynamicTypeHandler5460 bool found(APValue &Subobj, QualType SubobjType) { return true; }
found__anon4717f8731011::CheckDynamicTypeHandler5461 bool found(APSInt &Value, QualType SubobjType) { return true; }
found__anon4717f8731011::CheckDynamicTypeHandler5462 bool found(APFloat &Value, QualType SubobjType) { return true; }
5463 };
5464 } // end anonymous namespace
5465
5466 /// Check that we can access the notional vptr of an object / determine its
5467 /// dynamic type.
checkDynamicType(EvalInfo & Info,const Expr * E,const LValue & This,AccessKinds AK,bool Polymorphic)5468 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5469 AccessKinds AK, bool Polymorphic) {
5470 if (This.Designator.Invalid)
5471 return false;
5472
5473 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5474
5475 if (!Obj)
5476 return false;
5477
5478 if (!Obj.Value) {
5479 // The object is not usable in constant expressions, so we can't inspect
5480 // its value to see if it's in-lifetime or what the active union members
5481 // are. We can still check for a one-past-the-end lvalue.
5482 if (This.Designator.isOnePastTheEnd() ||
5483 This.Designator.isMostDerivedAnUnsizedArray()) {
5484 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5485 ? diag::note_constexpr_access_past_end
5486 : diag::note_constexpr_access_unsized_array)
5487 << AK;
5488 return false;
5489 } else if (Polymorphic) {
5490 // Conservatively refuse to perform a polymorphic operation if we would
5491 // not be able to read a notional 'vptr' value.
5492 APValue Val;
5493 This.moveInto(Val);
5494 QualType StarThisType =
5495 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5496 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5497 << AK << Val.getAsString(Info.Ctx, StarThisType);
5498 return false;
5499 }
5500 return true;
5501 }
5502
5503 CheckDynamicTypeHandler Handler{AK};
5504 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5505 }
5506
5507 /// Check that the pointee of the 'this' pointer in a member function call is
5508 /// either within its lifetime or in its period of construction or destruction.
5509 static bool
checkNonVirtualMemberCallThisPointer(EvalInfo & Info,const Expr * E,const LValue & This,const CXXMethodDecl * NamedMember)5510 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5511 const LValue &This,
5512 const CXXMethodDecl *NamedMember) {
5513 return checkDynamicType(
5514 Info, E, This,
5515 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5516 }
5517
5518 struct DynamicType {
5519 /// The dynamic class type of the object.
5520 const CXXRecordDecl *Type;
5521 /// The corresponding path length in the lvalue.
5522 unsigned PathLength;
5523 };
5524
getBaseClassType(SubobjectDesignator & Designator,unsigned PathLength)5525 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5526 unsigned PathLength) {
5527 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5528 Designator.Entries.size() && "invalid path length");
5529 return (PathLength == Designator.MostDerivedPathLength)
5530 ? Designator.MostDerivedType->getAsCXXRecordDecl()
5531 : getAsBaseClass(Designator.Entries[PathLength - 1]);
5532 }
5533
5534 /// Determine the dynamic type of an object.
ComputeDynamicType(EvalInfo & Info,const Expr * E,LValue & This,AccessKinds AK)5535 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5536 LValue &This, AccessKinds AK) {
5537 // If we don't have an lvalue denoting an object of class type, there is no
5538 // meaningful dynamic type. (We consider objects of non-class type to have no
5539 // dynamic type.)
5540 if (!checkDynamicType(Info, E, This, AK, true))
5541 return None;
5542
5543 // Refuse to compute a dynamic type in the presence of virtual bases. This
5544 // shouldn't happen other than in constant-folding situations, since literal
5545 // types can't have virtual bases.
5546 //
5547 // Note that consumers of DynamicType assume that the type has no virtual
5548 // bases, and will need modifications if this restriction is relaxed.
5549 const CXXRecordDecl *Class =
5550 This.Designator.MostDerivedType->getAsCXXRecordDecl();
5551 if (!Class || Class->getNumVBases()) {
5552 Info.FFDiag(E);
5553 return None;
5554 }
5555
5556 // FIXME: For very deep class hierarchies, it might be beneficial to use a
5557 // binary search here instead. But the overwhelmingly common case is that
5558 // we're not in the middle of a constructor, so it probably doesn't matter
5559 // in practice.
5560 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5561 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5562 PathLength <= Path.size(); ++PathLength) {
5563 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5564 Path.slice(0, PathLength))) {
5565 case ConstructionPhase::Bases:
5566 case ConstructionPhase::DestroyingBases:
5567 // We're constructing or destroying a base class. This is not the dynamic
5568 // type.
5569 break;
5570
5571 case ConstructionPhase::None:
5572 case ConstructionPhase::AfterBases:
5573 case ConstructionPhase::AfterFields:
5574 case ConstructionPhase::Destroying:
5575 // We've finished constructing the base classes and not yet started
5576 // destroying them again, so this is the dynamic type.
5577 return DynamicType{getBaseClassType(This.Designator, PathLength),
5578 PathLength};
5579 }
5580 }
5581
5582 // CWG issue 1517: we're constructing a base class of the object described by
5583 // 'This', so that object has not yet begun its period of construction and
5584 // any polymorphic operation on it results in undefined behavior.
5585 Info.FFDiag(E);
5586 return None;
5587 }
5588
5589 /// Perform virtual dispatch.
HandleVirtualDispatch(EvalInfo & Info,const Expr * E,LValue & This,const CXXMethodDecl * Found,llvm::SmallVectorImpl<QualType> & CovariantAdjustmentPath)5590 static const CXXMethodDecl *HandleVirtualDispatch(
5591 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5592 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5593 Optional<DynamicType> DynType = ComputeDynamicType(
5594 Info, E, This,
5595 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5596 if (!DynType)
5597 return nullptr;
5598
5599 // Find the final overrider. It must be declared in one of the classes on the
5600 // path from the dynamic type to the static type.
5601 // FIXME: If we ever allow literal types to have virtual base classes, that
5602 // won't be true.
5603 const CXXMethodDecl *Callee = Found;
5604 unsigned PathLength = DynType->PathLength;
5605 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5606 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5607 const CXXMethodDecl *Overrider =
5608 Found->getCorrespondingMethodDeclaredInClass(Class, false);
5609 if (Overrider) {
5610 Callee = Overrider;
5611 break;
5612 }
5613 }
5614
5615 // C++2a [class.abstract]p6:
5616 // the effect of making a virtual call to a pure virtual function [...] is
5617 // undefined
5618 if (Callee->isPure()) {
5619 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5620 Info.Note(Callee->getLocation(), diag::note_declared_at);
5621 return nullptr;
5622 }
5623
5624 // If necessary, walk the rest of the path to determine the sequence of
5625 // covariant adjustment steps to apply.
5626 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5627 Found->getReturnType())) {
5628 CovariantAdjustmentPath.push_back(Callee->getReturnType());
5629 for (unsigned CovariantPathLength = PathLength + 1;
5630 CovariantPathLength != This.Designator.Entries.size();
5631 ++CovariantPathLength) {
5632 const CXXRecordDecl *NextClass =
5633 getBaseClassType(This.Designator, CovariantPathLength);
5634 const CXXMethodDecl *Next =
5635 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5636 if (Next && !Info.Ctx.hasSameUnqualifiedType(
5637 Next->getReturnType(), CovariantAdjustmentPath.back()))
5638 CovariantAdjustmentPath.push_back(Next->getReturnType());
5639 }
5640 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5641 CovariantAdjustmentPath.back()))
5642 CovariantAdjustmentPath.push_back(Found->getReturnType());
5643 }
5644
5645 // Perform 'this' adjustment.
5646 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5647 return nullptr;
5648
5649 return Callee;
5650 }
5651
5652 /// Perform the adjustment from a value returned by a virtual function to
5653 /// a value of the statically expected type, which may be a pointer or
5654 /// reference to a base class of the returned type.
HandleCovariantReturnAdjustment(EvalInfo & Info,const Expr * E,APValue & Result,ArrayRef<QualType> Path)5655 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5656 APValue &Result,
5657 ArrayRef<QualType> Path) {
5658 assert(Result.isLValue() &&
5659 "unexpected kind of APValue for covariant return");
5660 if (Result.isNullPointer())
5661 return true;
5662
5663 LValue LVal;
5664 LVal.setFrom(Info.Ctx, Result);
5665
5666 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5667 for (unsigned I = 1; I != Path.size(); ++I) {
5668 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5669 assert(OldClass && NewClass && "unexpected kind of covariant return");
5670 if (OldClass != NewClass &&
5671 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5672 return false;
5673 OldClass = NewClass;
5674 }
5675
5676 LVal.moveInto(Result);
5677 return true;
5678 }
5679
5680 /// Determine whether \p Base, which is known to be a direct base class of
5681 /// \p Derived, is a public base class.
isBaseClassPublic(const CXXRecordDecl * Derived,const CXXRecordDecl * Base)5682 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5683 const CXXRecordDecl *Base) {
5684 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5685 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5686 if (BaseClass && declaresSameEntity(BaseClass, Base))
5687 return BaseSpec.getAccessSpecifier() == AS_public;
5688 }
5689 llvm_unreachable("Base is not a direct base of Derived");
5690 }
5691
5692 /// Apply the given dynamic cast operation on the provided lvalue.
5693 ///
5694 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5695 /// to find a suitable target subobject.
HandleDynamicCast(EvalInfo & Info,const ExplicitCastExpr * E,LValue & Ptr)5696 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5697 LValue &Ptr) {
5698 // We can't do anything with a non-symbolic pointer value.
5699 SubobjectDesignator &D = Ptr.Designator;
5700 if (D.Invalid)
5701 return false;
5702
5703 // C++ [expr.dynamic.cast]p6:
5704 // If v is a null pointer value, the result is a null pointer value.
5705 if (Ptr.isNullPointer() && !E->isGLValue())
5706 return true;
5707
5708 // For all the other cases, we need the pointer to point to an object within
5709 // its lifetime / period of construction / destruction, and we need to know
5710 // its dynamic type.
5711 Optional<DynamicType> DynType =
5712 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5713 if (!DynType)
5714 return false;
5715
5716 // C++ [expr.dynamic.cast]p7:
5717 // If T is "pointer to cv void", then the result is a pointer to the most
5718 // derived object
5719 if (E->getType()->isVoidPointerType())
5720 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5721
5722 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5723 assert(C && "dynamic_cast target is not void pointer nor class");
5724 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5725
5726 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5727 // C++ [expr.dynamic.cast]p9:
5728 if (!E->isGLValue()) {
5729 // The value of a failed cast to pointer type is the null pointer value
5730 // of the required result type.
5731 Ptr.setNull(Info.Ctx, E->getType());
5732 return true;
5733 }
5734
5735 // A failed cast to reference type throws [...] std::bad_cast.
5736 unsigned DiagKind;
5737 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5738 DynType->Type->isDerivedFrom(C)))
5739 DiagKind = 0;
5740 else if (!Paths || Paths->begin() == Paths->end())
5741 DiagKind = 1;
5742 else if (Paths->isAmbiguous(CQT))
5743 DiagKind = 2;
5744 else {
5745 assert(Paths->front().Access != AS_public && "why did the cast fail?");
5746 DiagKind = 3;
5747 }
5748 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5749 << DiagKind << Ptr.Designator.getType(Info.Ctx)
5750 << Info.Ctx.getRecordType(DynType->Type)
5751 << E->getType().getUnqualifiedType();
5752 return false;
5753 };
5754
5755 // Runtime check, phase 1:
5756 // Walk from the base subobject towards the derived object looking for the
5757 // target type.
5758 for (int PathLength = Ptr.Designator.Entries.size();
5759 PathLength >= (int)DynType->PathLength; --PathLength) {
5760 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5761 if (declaresSameEntity(Class, C))
5762 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5763 // We can only walk across public inheritance edges.
5764 if (PathLength > (int)DynType->PathLength &&
5765 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5766 Class))
5767 return RuntimeCheckFailed(nullptr);
5768 }
5769
5770 // Runtime check, phase 2:
5771 // Search the dynamic type for an unambiguous public base of type C.
5772 CXXBasePaths Paths(/*FindAmbiguities=*/true,
5773 /*RecordPaths=*/true, /*DetectVirtual=*/false);
5774 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5775 Paths.front().Access == AS_public) {
5776 // Downcast to the dynamic type...
5777 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5778 return false;
5779 // ... then upcast to the chosen base class subobject.
5780 for (CXXBasePathElement &Elem : Paths.front())
5781 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5782 return false;
5783 return true;
5784 }
5785
5786 // Otherwise, the runtime check fails.
5787 return RuntimeCheckFailed(&Paths);
5788 }
5789
5790 namespace {
5791 struct StartLifetimeOfUnionMemberHandler {
5792 EvalInfo &Info;
5793 const Expr *LHSExpr;
5794 const FieldDecl *Field;
5795 bool DuringInit;
5796 bool Failed = false;
5797 static const AccessKinds AccessKind = AK_Assign;
5798
5799 typedef bool result_type;
failed__anon4717f8731211::StartLifetimeOfUnionMemberHandler5800 bool failed() { return Failed; }
found__anon4717f8731211::StartLifetimeOfUnionMemberHandler5801 bool found(APValue &Subobj, QualType SubobjType) {
5802 // We are supposed to perform no initialization but begin the lifetime of
5803 // the object. We interpret that as meaning to do what default
5804 // initialization of the object would do if all constructors involved were
5805 // trivial:
5806 // * All base, non-variant member, and array element subobjects' lifetimes
5807 // begin
5808 // * No variant members' lifetimes begin
5809 // * All scalar subobjects whose lifetimes begin have indeterminate values
5810 assert(SubobjType->isUnionType());
5811 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5812 // This union member is already active. If it's also in-lifetime, there's
5813 // nothing to do.
5814 if (Subobj.getUnionValue().hasValue())
5815 return true;
5816 } else if (DuringInit) {
5817 // We're currently in the process of initializing a different union
5818 // member. If we carried on, that initialization would attempt to
5819 // store to an inactive union member, resulting in undefined behavior.
5820 Info.FFDiag(LHSExpr,
5821 diag::note_constexpr_union_member_change_during_init);
5822 return false;
5823 }
5824 APValue Result;
5825 Failed = !getDefaultInitValue(Field->getType(), Result);
5826 Subobj.setUnion(Field, Result);
5827 return true;
5828 }
found__anon4717f8731211::StartLifetimeOfUnionMemberHandler5829 bool found(APSInt &Value, QualType SubobjType) {
5830 llvm_unreachable("wrong value kind for union object");
5831 }
found__anon4717f8731211::StartLifetimeOfUnionMemberHandler5832 bool found(APFloat &Value, QualType SubobjType) {
5833 llvm_unreachable("wrong value kind for union object");
5834 }
5835 };
5836 } // end anonymous namespace
5837
5838 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5839
5840 /// Handle a builtin simple-assignment or a call to a trivial assignment
5841 /// operator whose left-hand side might involve a union member access. If it
5842 /// does, implicitly start the lifetime of any accessed union elements per
5843 /// C++20 [class.union]5.
HandleUnionActiveMemberChange(EvalInfo & Info,const Expr * LHSExpr,const LValue & LHS)5844 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5845 const LValue &LHS) {
5846 if (LHS.InvalidBase || LHS.Designator.Invalid)
5847 return false;
5848
5849 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5850 // C++ [class.union]p5:
5851 // define the set S(E) of subexpressions of E as follows:
5852 unsigned PathLength = LHS.Designator.Entries.size();
5853 for (const Expr *E = LHSExpr; E != nullptr;) {
5854 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
5855 if (auto *ME = dyn_cast<MemberExpr>(E)) {
5856 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5857 // Note that we can't implicitly start the lifetime of a reference,
5858 // so we don't need to proceed any further if we reach one.
5859 if (!FD || FD->getType()->isReferenceType())
5860 break;
5861
5862 // ... and also contains A.B if B names a union member ...
5863 if (FD->getParent()->isUnion()) {
5864 // ... of a non-class, non-array type, or of a class type with a
5865 // trivial default constructor that is not deleted, or an array of
5866 // such types.
5867 auto *RD =
5868 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5869 if (!RD || RD->hasTrivialDefaultConstructor())
5870 UnionPathLengths.push_back({PathLength - 1, FD});
5871 }
5872
5873 E = ME->getBase();
5874 --PathLength;
5875 assert(declaresSameEntity(FD,
5876 LHS.Designator.Entries[PathLength]
5877 .getAsBaseOrMember().getPointer()));
5878
5879 // -- If E is of the form A[B] and is interpreted as a built-in array
5880 // subscripting operator, S(E) is [S(the array operand, if any)].
5881 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5882 // Step over an ArrayToPointerDecay implicit cast.
5883 auto *Base = ASE->getBase()->IgnoreImplicit();
5884 if (!Base->getType()->isArrayType())
5885 break;
5886
5887 E = Base;
5888 --PathLength;
5889
5890 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5891 // Step over a derived-to-base conversion.
5892 E = ICE->getSubExpr();
5893 if (ICE->getCastKind() == CK_NoOp)
5894 continue;
5895 if (ICE->getCastKind() != CK_DerivedToBase &&
5896 ICE->getCastKind() != CK_UncheckedDerivedToBase)
5897 break;
5898 // Walk path backwards as we walk up from the base to the derived class.
5899 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5900 --PathLength;
5901 (void)Elt;
5902 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5903 LHS.Designator.Entries[PathLength]
5904 .getAsBaseOrMember().getPointer()));
5905 }
5906
5907 // -- Otherwise, S(E) is empty.
5908 } else {
5909 break;
5910 }
5911 }
5912
5913 // Common case: no unions' lifetimes are started.
5914 if (UnionPathLengths.empty())
5915 return true;
5916
5917 // if modification of X [would access an inactive union member], an object
5918 // of the type of X is implicitly created
5919 CompleteObject Obj =
5920 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5921 if (!Obj)
5922 return false;
5923 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5924 llvm::reverse(UnionPathLengths)) {
5925 // Form a designator for the union object.
5926 SubobjectDesignator D = LHS.Designator;
5927 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5928
5929 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5930 ConstructionPhase::AfterBases;
5931 StartLifetimeOfUnionMemberHandler StartLifetime{
5932 Info, LHSExpr, LengthAndField.second, DuringInit};
5933 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5934 return false;
5935 }
5936
5937 return true;
5938 }
5939
EvaluateCallArg(const ParmVarDecl * PVD,const Expr * Arg,CallRef Call,EvalInfo & Info,bool NonNull=false)5940 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
5941 CallRef Call, EvalInfo &Info,
5942 bool NonNull = false) {
5943 LValue LV;
5944 // Create the parameter slot and register its destruction. For a vararg
5945 // argument, create a temporary.
5946 // FIXME: For calling conventions that destroy parameters in the callee,
5947 // should we consider performing destruction when the function returns
5948 // instead?
5949 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
5950 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
5951 ScopeKind::Call, LV);
5952 if (!EvaluateInPlace(V, Info, LV, Arg))
5953 return false;
5954
5955 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
5956 // undefined behavior, so is non-constant.
5957 if (NonNull && V.isLValue() && V.isNullPointer()) {
5958 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
5959 return false;
5960 }
5961
5962 return true;
5963 }
5964
5965 /// Evaluate the arguments to a function call.
EvaluateArgs(ArrayRef<const Expr * > Args,CallRef Call,EvalInfo & Info,const FunctionDecl * Callee,bool RightToLeft=false)5966 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
5967 EvalInfo &Info, const FunctionDecl *Callee,
5968 bool RightToLeft = false) {
5969 bool Success = true;
5970 llvm::SmallBitVector ForbiddenNullArgs;
5971 if (Callee->hasAttr<NonNullAttr>()) {
5972 ForbiddenNullArgs.resize(Args.size());
5973 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5974 if (!Attr->args_size()) {
5975 ForbiddenNullArgs.set();
5976 break;
5977 } else
5978 for (auto Idx : Attr->args()) {
5979 unsigned ASTIdx = Idx.getASTIndex();
5980 if (ASTIdx >= Args.size())
5981 continue;
5982 ForbiddenNullArgs[ASTIdx] = 1;
5983 }
5984 }
5985 }
5986 for (unsigned I = 0; I < Args.size(); I++) {
5987 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
5988 const ParmVarDecl *PVD =
5989 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
5990 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
5991 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
5992 // If we're checking for a potential constant expression, evaluate all
5993 // initializers even if some of them fail.
5994 if (!Info.noteFailure())
5995 return false;
5996 Success = false;
5997 }
5998 }
5999 return Success;
6000 }
6001
6002 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6003 /// constructor or assignment operator.
handleTrivialCopy(EvalInfo & Info,const ParmVarDecl * Param,const Expr * E,APValue & Result,bool CopyObjectRepresentation)6004 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6005 const Expr *E, APValue &Result,
6006 bool CopyObjectRepresentation) {
6007 // Find the reference argument.
6008 CallStackFrame *Frame = Info.CurrentCall;
6009 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6010 if (!RefValue) {
6011 Info.FFDiag(E);
6012 return false;
6013 }
6014
6015 // Copy out the contents of the RHS object.
6016 LValue RefLValue;
6017 RefLValue.setFrom(Info.Ctx, *RefValue);
6018 return handleLValueToRValueConversion(
6019 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6020 CopyObjectRepresentation);
6021 }
6022
6023 /// Evaluate a function call.
HandleFunctionCall(SourceLocation CallLoc,const FunctionDecl * Callee,const LValue * This,ArrayRef<const Expr * > Args,CallRef Call,const Stmt * Body,EvalInfo & Info,APValue & Result,const LValue * ResultSlot)6024 static bool HandleFunctionCall(SourceLocation CallLoc,
6025 const FunctionDecl *Callee, const LValue *This,
6026 ArrayRef<const Expr *> Args, CallRef Call,
6027 const Stmt *Body, EvalInfo &Info,
6028 APValue &Result, const LValue *ResultSlot) {
6029 if (!Info.CheckCallLimit(CallLoc))
6030 return false;
6031
6032 CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6033
6034 // For a trivial copy or move assignment, perform an APValue copy. This is
6035 // essential for unions, where the operations performed by the assignment
6036 // operator cannot be represented as statements.
6037 //
6038 // Skip this for non-union classes with no fields; in that case, the defaulted
6039 // copy/move does not actually read the object.
6040 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6041 if (MD && MD->isDefaulted() &&
6042 (MD->getParent()->isUnion() ||
6043 (MD->isTrivial() &&
6044 isReadByLvalueToRvalueConversion(MD->getParent())))) {
6045 assert(This &&
6046 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6047 APValue RHSValue;
6048 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6049 MD->getParent()->isUnion()))
6050 return false;
6051 if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
6052 !HandleUnionActiveMemberChange(Info, Args[0], *This))
6053 return false;
6054 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6055 RHSValue))
6056 return false;
6057 This->moveInto(Result);
6058 return true;
6059 } else if (MD && isLambdaCallOperator(MD)) {
6060 // We're in a lambda; determine the lambda capture field maps unless we're
6061 // just constexpr checking a lambda's call operator. constexpr checking is
6062 // done before the captures have been added to the closure object (unless
6063 // we're inferring constexpr-ness), so we don't have access to them in this
6064 // case. But since we don't need the captures to constexpr check, we can
6065 // just ignore them.
6066 if (!Info.checkingPotentialConstantExpression())
6067 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6068 Frame.LambdaThisCaptureField);
6069 }
6070
6071 StmtResult Ret = {Result, ResultSlot};
6072 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6073 if (ESR == ESR_Succeeded) {
6074 if (Callee->getReturnType()->isVoidType())
6075 return true;
6076 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6077 }
6078 return ESR == ESR_Returned;
6079 }
6080
6081 /// Evaluate a constructor call.
HandleConstructorCall(const Expr * E,const LValue & This,CallRef Call,const CXXConstructorDecl * Definition,EvalInfo & Info,APValue & Result)6082 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6083 CallRef Call,
6084 const CXXConstructorDecl *Definition,
6085 EvalInfo &Info, APValue &Result) {
6086 SourceLocation CallLoc = E->getExprLoc();
6087 if (!Info.CheckCallLimit(CallLoc))
6088 return false;
6089
6090 const CXXRecordDecl *RD = Definition->getParent();
6091 if (RD->getNumVBases()) {
6092 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6093 return false;
6094 }
6095
6096 EvalInfo::EvaluatingConstructorRAII EvalObj(
6097 Info,
6098 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6099 RD->getNumBases());
6100 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6101
6102 // FIXME: Creating an APValue just to hold a nonexistent return value is
6103 // wasteful.
6104 APValue RetVal;
6105 StmtResult Ret = {RetVal, nullptr};
6106
6107 // If it's a delegating constructor, delegate.
6108 if (Definition->isDelegatingConstructor()) {
6109 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6110 {
6111 FullExpressionRAII InitScope(Info);
6112 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6113 !InitScope.destroy())
6114 return false;
6115 }
6116 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6117 }
6118
6119 // For a trivial copy or move constructor, perform an APValue copy. This is
6120 // essential for unions (or classes with anonymous union members), where the
6121 // operations performed by the constructor cannot be represented by
6122 // ctor-initializers.
6123 //
6124 // Skip this for empty non-union classes; we should not perform an
6125 // lvalue-to-rvalue conversion on them because their copy constructor does not
6126 // actually read them.
6127 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6128 (Definition->getParent()->isUnion() ||
6129 (Definition->isTrivial() &&
6130 isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6131 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6132 Definition->getParent()->isUnion());
6133 }
6134
6135 // Reserve space for the struct members.
6136 if (!Result.hasValue()) {
6137 if (!RD->isUnion())
6138 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6139 std::distance(RD->field_begin(), RD->field_end()));
6140 else
6141 // A union starts with no active member.
6142 Result = APValue((const FieldDecl*)nullptr);
6143 }
6144
6145 if (RD->isInvalidDecl()) return false;
6146 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6147
6148 // A scope for temporaries lifetime-extended by reference members.
6149 BlockScopeRAII LifetimeExtendedScope(Info);
6150
6151 bool Success = true;
6152 unsigned BasesSeen = 0;
6153 #ifndef NDEBUG
6154 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6155 #endif
6156 CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6157 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6158 // We might be initializing the same field again if this is an indirect
6159 // field initialization.
6160 if (FieldIt == RD->field_end() ||
6161 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6162 assert(Indirect && "fields out of order?");
6163 return;
6164 }
6165
6166 // Default-initialize any fields with no explicit initializer.
6167 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6168 assert(FieldIt != RD->field_end() && "missing field?");
6169 if (!FieldIt->isUnnamedBitfield())
6170 Success &= getDefaultInitValue(
6171 FieldIt->getType(),
6172 Result.getStructField(FieldIt->getFieldIndex()));
6173 }
6174 ++FieldIt;
6175 };
6176 for (const auto *I : Definition->inits()) {
6177 LValue Subobject = This;
6178 LValue SubobjectParent = This;
6179 APValue *Value = &Result;
6180
6181 // Determine the subobject to initialize.
6182 FieldDecl *FD = nullptr;
6183 if (I->isBaseInitializer()) {
6184 QualType BaseType(I->getBaseClass(), 0);
6185 #ifndef NDEBUG
6186 // Non-virtual base classes are initialized in the order in the class
6187 // definition. We have already checked for virtual base classes.
6188 assert(!BaseIt->isVirtual() && "virtual base for literal type");
6189 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6190 "base class initializers not in expected order");
6191 ++BaseIt;
6192 #endif
6193 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6194 BaseType->getAsCXXRecordDecl(), &Layout))
6195 return false;
6196 Value = &Result.getStructBase(BasesSeen++);
6197 } else if ((FD = I->getMember())) {
6198 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6199 return false;
6200 if (RD->isUnion()) {
6201 Result = APValue(FD);
6202 Value = &Result.getUnionValue();
6203 } else {
6204 SkipToField(FD, false);
6205 Value = &Result.getStructField(FD->getFieldIndex());
6206 }
6207 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6208 // Walk the indirect field decl's chain to find the object to initialize,
6209 // and make sure we've initialized every step along it.
6210 auto IndirectFieldChain = IFD->chain();
6211 for (auto *C : IndirectFieldChain) {
6212 FD = cast<FieldDecl>(C);
6213 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6214 // Switch the union field if it differs. This happens if we had
6215 // preceding zero-initialization, and we're now initializing a union
6216 // subobject other than the first.
6217 // FIXME: In this case, the values of the other subobjects are
6218 // specified, since zero-initialization sets all padding bits to zero.
6219 if (!Value->hasValue() ||
6220 (Value->isUnion() && Value->getUnionField() != FD)) {
6221 if (CD->isUnion())
6222 *Value = APValue(FD);
6223 else
6224 // FIXME: This immediately starts the lifetime of all members of
6225 // an anonymous struct. It would be preferable to strictly start
6226 // member lifetime in initialization order.
6227 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6228 }
6229 // Store Subobject as its parent before updating it for the last element
6230 // in the chain.
6231 if (C == IndirectFieldChain.back())
6232 SubobjectParent = Subobject;
6233 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6234 return false;
6235 if (CD->isUnion())
6236 Value = &Value->getUnionValue();
6237 else {
6238 if (C == IndirectFieldChain.front() && !RD->isUnion())
6239 SkipToField(FD, true);
6240 Value = &Value->getStructField(FD->getFieldIndex());
6241 }
6242 }
6243 } else {
6244 llvm_unreachable("unknown base initializer kind");
6245 }
6246
6247 // Need to override This for implicit field initializers as in this case
6248 // This refers to innermost anonymous struct/union containing initializer,
6249 // not to currently constructed class.
6250 const Expr *Init = I->getInit();
6251 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6252 isa<CXXDefaultInitExpr>(Init));
6253 FullExpressionRAII InitScope(Info);
6254 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6255 (FD && FD->isBitField() &&
6256 !truncateBitfieldValue(Info, Init, *Value, FD))) {
6257 // If we're checking for a potential constant expression, evaluate all
6258 // initializers even if some of them fail.
6259 if (!Info.noteFailure())
6260 return false;
6261 Success = false;
6262 }
6263
6264 // This is the point at which the dynamic type of the object becomes this
6265 // class type.
6266 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6267 EvalObj.finishedConstructingBases();
6268 }
6269
6270 // Default-initialize any remaining fields.
6271 if (!RD->isUnion()) {
6272 for (; FieldIt != RD->field_end(); ++FieldIt) {
6273 if (!FieldIt->isUnnamedBitfield())
6274 Success &= getDefaultInitValue(
6275 FieldIt->getType(),
6276 Result.getStructField(FieldIt->getFieldIndex()));
6277 }
6278 }
6279
6280 EvalObj.finishedConstructingFields();
6281
6282 return Success &&
6283 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6284 LifetimeExtendedScope.destroy();
6285 }
6286
HandleConstructorCall(const Expr * E,const LValue & This,ArrayRef<const Expr * > Args,const CXXConstructorDecl * Definition,EvalInfo & Info,APValue & Result)6287 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6288 ArrayRef<const Expr*> Args,
6289 const CXXConstructorDecl *Definition,
6290 EvalInfo &Info, APValue &Result) {
6291 CallScopeRAII CallScope(Info);
6292 CallRef Call = Info.CurrentCall->createCall(Definition);
6293 if (!EvaluateArgs(Args, Call, Info, Definition))
6294 return false;
6295
6296 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6297 CallScope.destroy();
6298 }
6299
HandleDestructionImpl(EvalInfo & Info,SourceLocation CallLoc,const LValue & This,APValue & Value,QualType T)6300 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6301 const LValue &This, APValue &Value,
6302 QualType T) {
6303 // Objects can only be destroyed while they're within their lifetimes.
6304 // FIXME: We have no representation for whether an object of type nullptr_t
6305 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6306 // as indeterminate instead?
6307 if (Value.isAbsent() && !T->isNullPtrType()) {
6308 APValue Printable;
6309 This.moveInto(Printable);
6310 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6311 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6312 return false;
6313 }
6314
6315 // Invent an expression for location purposes.
6316 // FIXME: We shouldn't need to do this.
6317 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
6318
6319 // For arrays, destroy elements right-to-left.
6320 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6321 uint64_t Size = CAT->getSize().getZExtValue();
6322 QualType ElemT = CAT->getElementType();
6323
6324 LValue ElemLV = This;
6325 ElemLV.addArray(Info, &LocE, CAT);
6326 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6327 return false;
6328
6329 // Ensure that we have actual array elements available to destroy; the
6330 // destructors might mutate the value, so we can't run them on the array
6331 // filler.
6332 if (Size && Size > Value.getArrayInitializedElts())
6333 expandArray(Value, Value.getArraySize() - 1);
6334
6335 for (; Size != 0; --Size) {
6336 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6337 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6338 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6339 return false;
6340 }
6341
6342 // End the lifetime of this array now.
6343 Value = APValue();
6344 return true;
6345 }
6346
6347 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6348 if (!RD) {
6349 if (T.isDestructedType()) {
6350 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6351 return false;
6352 }
6353
6354 Value = APValue();
6355 return true;
6356 }
6357
6358 if (RD->getNumVBases()) {
6359 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6360 return false;
6361 }
6362
6363 const CXXDestructorDecl *DD = RD->getDestructor();
6364 if (!DD && !RD->hasTrivialDestructor()) {
6365 Info.FFDiag(CallLoc);
6366 return false;
6367 }
6368
6369 if (!DD || DD->isTrivial() ||
6370 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6371 // A trivial destructor just ends the lifetime of the object. Check for
6372 // this case before checking for a body, because we might not bother
6373 // building a body for a trivial destructor. Note that it doesn't matter
6374 // whether the destructor is constexpr in this case; all trivial
6375 // destructors are constexpr.
6376 //
6377 // If an anonymous union would be destroyed, some enclosing destructor must
6378 // have been explicitly defined, and the anonymous union destruction should
6379 // have no effect.
6380 Value = APValue();
6381 return true;
6382 }
6383
6384 if (!Info.CheckCallLimit(CallLoc))
6385 return false;
6386
6387 const FunctionDecl *Definition = nullptr;
6388 const Stmt *Body = DD->getBody(Definition);
6389
6390 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6391 return false;
6392
6393 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6394
6395 // We're now in the period of destruction of this object.
6396 unsigned BasesLeft = RD->getNumBases();
6397 EvalInfo::EvaluatingDestructorRAII EvalObj(
6398 Info,
6399 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6400 if (!EvalObj.DidInsert) {
6401 // C++2a [class.dtor]p19:
6402 // the behavior is undefined if the destructor is invoked for an object
6403 // whose lifetime has ended
6404 // (Note that formally the lifetime ends when the period of destruction
6405 // begins, even though certain uses of the object remain valid until the
6406 // period of destruction ends.)
6407 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6408 return false;
6409 }
6410
6411 // FIXME: Creating an APValue just to hold a nonexistent return value is
6412 // wasteful.
6413 APValue RetVal;
6414 StmtResult Ret = {RetVal, nullptr};
6415 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6416 return false;
6417
6418 // A union destructor does not implicitly destroy its members.
6419 if (RD->isUnion())
6420 return true;
6421
6422 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6423
6424 // We don't have a good way to iterate fields in reverse, so collect all the
6425 // fields first and then walk them backwards.
6426 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6427 for (const FieldDecl *FD : llvm::reverse(Fields)) {
6428 if (FD->isUnnamedBitfield())
6429 continue;
6430
6431 LValue Subobject = This;
6432 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6433 return false;
6434
6435 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6436 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6437 FD->getType()))
6438 return false;
6439 }
6440
6441 if (BasesLeft != 0)
6442 EvalObj.startedDestroyingBases();
6443
6444 // Destroy base classes in reverse order.
6445 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6446 --BasesLeft;
6447
6448 QualType BaseType = Base.getType();
6449 LValue Subobject = This;
6450 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6451 BaseType->getAsCXXRecordDecl(), &Layout))
6452 return false;
6453
6454 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6455 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6456 BaseType))
6457 return false;
6458 }
6459 assert(BasesLeft == 0 && "NumBases was wrong?");
6460
6461 // The period of destruction ends now. The object is gone.
6462 Value = APValue();
6463 return true;
6464 }
6465
6466 namespace {
6467 struct DestroyObjectHandler {
6468 EvalInfo &Info;
6469 const Expr *E;
6470 const LValue &This;
6471 const AccessKinds AccessKind;
6472
6473 typedef bool result_type;
failed__anon4717f8731411::DestroyObjectHandler6474 bool failed() { return false; }
found__anon4717f8731411::DestroyObjectHandler6475 bool found(APValue &Subobj, QualType SubobjType) {
6476 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6477 SubobjType);
6478 }
found__anon4717f8731411::DestroyObjectHandler6479 bool found(APSInt &Value, QualType SubobjType) {
6480 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6481 return false;
6482 }
found__anon4717f8731411::DestroyObjectHandler6483 bool found(APFloat &Value, QualType SubobjType) {
6484 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6485 return false;
6486 }
6487 };
6488 }
6489
6490 /// Perform a destructor or pseudo-destructor call on the given object, which
6491 /// might in general not be a complete object.
HandleDestruction(EvalInfo & Info,const Expr * E,const LValue & This,QualType ThisType)6492 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6493 const LValue &This, QualType ThisType) {
6494 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6495 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6496 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6497 }
6498
6499 /// Destroy and end the lifetime of the given complete object.
HandleDestruction(EvalInfo & Info,SourceLocation Loc,APValue::LValueBase LVBase,APValue & Value,QualType T)6500 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6501 APValue::LValueBase LVBase, APValue &Value,
6502 QualType T) {
6503 // If we've had an unmodeled side-effect, we can't rely on mutable state
6504 // (such as the object we're about to destroy) being correct.
6505 if (Info.EvalStatus.HasSideEffects)
6506 return false;
6507
6508 LValue LV;
6509 LV.set({LVBase});
6510 return HandleDestructionImpl(Info, Loc, LV, Value, T);
6511 }
6512
6513 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
HandleOperatorNewCall(EvalInfo & Info,const CallExpr * E,LValue & Result)6514 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6515 LValue &Result) {
6516 if (Info.checkingPotentialConstantExpression() ||
6517 Info.SpeculativeEvaluationDepth)
6518 return false;
6519
6520 // This is permitted only within a call to std::allocator<T>::allocate.
6521 auto Caller = Info.getStdAllocatorCaller("allocate");
6522 if (!Caller) {
6523 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6524 ? diag::note_constexpr_new_untyped
6525 : diag::note_constexpr_new);
6526 return false;
6527 }
6528
6529 QualType ElemType = Caller.ElemType;
6530 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6531 Info.FFDiag(E->getExprLoc(),
6532 diag::note_constexpr_new_not_complete_object_type)
6533 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6534 return false;
6535 }
6536
6537 APSInt ByteSize;
6538 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6539 return false;
6540 bool IsNothrow = false;
6541 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6542 EvaluateIgnoredValue(Info, E->getArg(I));
6543 IsNothrow |= E->getType()->isNothrowT();
6544 }
6545
6546 CharUnits ElemSize;
6547 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6548 return false;
6549 APInt Size, Remainder;
6550 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6551 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6552 if (Remainder != 0) {
6553 // This likely indicates a bug in the implementation of 'std::allocator'.
6554 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6555 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6556 return false;
6557 }
6558
6559 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6560 if (IsNothrow) {
6561 Result.setNull(Info.Ctx, E->getType());
6562 return true;
6563 }
6564
6565 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6566 return false;
6567 }
6568
6569 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6570 ArrayType::Normal, 0);
6571 APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6572 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6573 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6574 return true;
6575 }
6576
hasVirtualDestructor(QualType T)6577 static bool hasVirtualDestructor(QualType T) {
6578 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6579 if (CXXDestructorDecl *DD = RD->getDestructor())
6580 return DD->isVirtual();
6581 return false;
6582 }
6583
getVirtualOperatorDelete(QualType T)6584 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6585 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6586 if (CXXDestructorDecl *DD = RD->getDestructor())
6587 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6588 return nullptr;
6589 }
6590
6591 /// Check that the given object is a suitable pointer to a heap allocation that
6592 /// still exists and is of the right kind for the purpose of a deletion.
6593 ///
6594 /// On success, returns the heap allocation to deallocate. On failure, produces
6595 /// a diagnostic and returns None.
CheckDeleteKind(EvalInfo & Info,const Expr * E,const LValue & Pointer,DynAlloc::Kind DeallocKind)6596 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6597 const LValue &Pointer,
6598 DynAlloc::Kind DeallocKind) {
6599 auto PointerAsString = [&] {
6600 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6601 };
6602
6603 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6604 if (!DA) {
6605 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6606 << PointerAsString();
6607 if (Pointer.Base)
6608 NoteLValueLocation(Info, Pointer.Base);
6609 return None;
6610 }
6611
6612 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6613 if (!Alloc) {
6614 Info.FFDiag(E, diag::note_constexpr_double_delete);
6615 return None;
6616 }
6617
6618 QualType AllocType = Pointer.Base.getDynamicAllocType();
6619 if (DeallocKind != (*Alloc)->getKind()) {
6620 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6621 << DeallocKind << (*Alloc)->getKind() << AllocType;
6622 NoteLValueLocation(Info, Pointer.Base);
6623 return None;
6624 }
6625
6626 bool Subobject = false;
6627 if (DeallocKind == DynAlloc::New) {
6628 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6629 Pointer.Designator.isOnePastTheEnd();
6630 } else {
6631 Subobject = Pointer.Designator.Entries.size() != 1 ||
6632 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6633 }
6634 if (Subobject) {
6635 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6636 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6637 return None;
6638 }
6639
6640 return Alloc;
6641 }
6642
6643 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
HandleOperatorDeleteCall(EvalInfo & Info,const CallExpr * E)6644 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6645 if (Info.checkingPotentialConstantExpression() ||
6646 Info.SpeculativeEvaluationDepth)
6647 return false;
6648
6649 // This is permitted only within a call to std::allocator<T>::deallocate.
6650 if (!Info.getStdAllocatorCaller("deallocate")) {
6651 Info.FFDiag(E->getExprLoc());
6652 return true;
6653 }
6654
6655 LValue Pointer;
6656 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6657 return false;
6658 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6659 EvaluateIgnoredValue(Info, E->getArg(I));
6660
6661 if (Pointer.Designator.Invalid)
6662 return false;
6663
6664 // Deleting a null pointer has no effect.
6665 if (Pointer.isNullPointer())
6666 return true;
6667
6668 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6669 return false;
6670
6671 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6672 return true;
6673 }
6674
6675 //===----------------------------------------------------------------------===//
6676 // Generic Evaluation
6677 //===----------------------------------------------------------------------===//
6678 namespace {
6679
6680 class BitCastBuffer {
6681 // FIXME: We're going to need bit-level granularity when we support
6682 // bit-fields.
6683 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6684 // we don't support a host or target where that is the case. Still, we should
6685 // use a more generic type in case we ever do.
6686 SmallVector<Optional<unsigned char>, 32> Bytes;
6687
6688 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6689 "Need at least 8 bit unsigned char");
6690
6691 bool TargetIsLittleEndian;
6692
6693 public:
BitCastBuffer(CharUnits Width,bool TargetIsLittleEndian)6694 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6695 : Bytes(Width.getQuantity()),
6696 TargetIsLittleEndian(TargetIsLittleEndian) {}
6697
6698 LLVM_NODISCARD
readObject(CharUnits Offset,CharUnits Width,SmallVectorImpl<unsigned char> & Output) const6699 bool readObject(CharUnits Offset, CharUnits Width,
6700 SmallVectorImpl<unsigned char> &Output) const {
6701 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6702 // If a byte of an integer is uninitialized, then the whole integer is
6703 // uninitalized.
6704 if (!Bytes[I.getQuantity()])
6705 return false;
6706 Output.push_back(*Bytes[I.getQuantity()]);
6707 }
6708 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6709 std::reverse(Output.begin(), Output.end());
6710 return true;
6711 }
6712
writeObject(CharUnits Offset,SmallVectorImpl<unsigned char> & Input)6713 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6714 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6715 std::reverse(Input.begin(), Input.end());
6716
6717 size_t Index = 0;
6718 for (unsigned char Byte : Input) {
6719 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6720 Bytes[Offset.getQuantity() + Index] = Byte;
6721 ++Index;
6722 }
6723 }
6724
size()6725 size_t size() { return Bytes.size(); }
6726 };
6727
6728 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6729 /// target would represent the value at runtime.
6730 class APValueToBufferConverter {
6731 EvalInfo &Info;
6732 BitCastBuffer Buffer;
6733 const CastExpr *BCE;
6734
APValueToBufferConverter(EvalInfo & Info,CharUnits ObjectWidth,const CastExpr * BCE)6735 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6736 const CastExpr *BCE)
6737 : Info(Info),
6738 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6739 BCE(BCE) {}
6740
visit(const APValue & Val,QualType Ty)6741 bool visit(const APValue &Val, QualType Ty) {
6742 return visit(Val, Ty, CharUnits::fromQuantity(0));
6743 }
6744
6745 // Write out Val with type Ty into Buffer starting at Offset.
visit(const APValue & Val,QualType Ty,CharUnits Offset)6746 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6747 assert((size_t)Offset.getQuantity() <= Buffer.size());
6748
6749 // As a special case, nullptr_t has an indeterminate value.
6750 if (Ty->isNullPtrType())
6751 return true;
6752
6753 // Dig through Src to find the byte at SrcOffset.
6754 switch (Val.getKind()) {
6755 case APValue::Indeterminate:
6756 case APValue::None:
6757 return true;
6758
6759 case APValue::Int:
6760 return visitInt(Val.getInt(), Ty, Offset);
6761 case APValue::Float:
6762 return visitFloat(Val.getFloat(), Ty, Offset);
6763 case APValue::Array:
6764 return visitArray(Val, Ty, Offset);
6765 case APValue::Struct:
6766 return visitRecord(Val, Ty, Offset);
6767
6768 case APValue::ComplexInt:
6769 case APValue::ComplexFloat:
6770 case APValue::Vector:
6771 case APValue::FixedPoint:
6772 // FIXME: We should support these.
6773
6774 case APValue::Union:
6775 case APValue::MemberPointer:
6776 case APValue::AddrLabelDiff: {
6777 Info.FFDiag(BCE->getBeginLoc(),
6778 diag::note_constexpr_bit_cast_unsupported_type)
6779 << Ty;
6780 return false;
6781 }
6782
6783 case APValue::LValue:
6784 llvm_unreachable("LValue subobject in bit_cast?");
6785 }
6786 llvm_unreachable("Unhandled APValue::ValueKind");
6787 }
6788
visitRecord(const APValue & Val,QualType Ty,CharUnits Offset)6789 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6790 const RecordDecl *RD = Ty->getAsRecordDecl();
6791 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6792
6793 // Visit the base classes.
6794 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6795 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6796 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6797 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6798
6799 if (!visitRecord(Val.getStructBase(I), BS.getType(),
6800 Layout.getBaseClassOffset(BaseDecl) + Offset))
6801 return false;
6802 }
6803 }
6804
6805 // Visit the fields.
6806 unsigned FieldIdx = 0;
6807 for (FieldDecl *FD : RD->fields()) {
6808 if (FD->isBitField()) {
6809 Info.FFDiag(BCE->getBeginLoc(),
6810 diag::note_constexpr_bit_cast_unsupported_bitfield);
6811 return false;
6812 }
6813
6814 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6815
6816 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6817 "only bit-fields can have sub-char alignment");
6818 CharUnits FieldOffset =
6819 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6820 QualType FieldTy = FD->getType();
6821 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6822 return false;
6823 ++FieldIdx;
6824 }
6825
6826 return true;
6827 }
6828
visitArray(const APValue & Val,QualType Ty,CharUnits Offset)6829 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6830 const auto *CAT =
6831 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6832 if (!CAT)
6833 return false;
6834
6835 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6836 unsigned NumInitializedElts = Val.getArrayInitializedElts();
6837 unsigned ArraySize = Val.getArraySize();
6838 // First, initialize the initialized elements.
6839 for (unsigned I = 0; I != NumInitializedElts; ++I) {
6840 const APValue &SubObj = Val.getArrayInitializedElt(I);
6841 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6842 return false;
6843 }
6844
6845 // Next, initialize the rest of the array using the filler.
6846 if (Val.hasArrayFiller()) {
6847 const APValue &Filler = Val.getArrayFiller();
6848 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6849 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6850 return false;
6851 }
6852 }
6853
6854 return true;
6855 }
6856
visitInt(const APSInt & Val,QualType Ty,CharUnits Offset)6857 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6858 APSInt AdjustedVal = Val;
6859 unsigned Width = AdjustedVal.getBitWidth();
6860 if (Ty->isBooleanType()) {
6861 Width = Info.Ctx.getTypeSize(Ty);
6862 AdjustedVal = AdjustedVal.extend(Width);
6863 }
6864
6865 SmallVector<unsigned char, 8> Bytes(Width / 8);
6866 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6867 Buffer.writeObject(Offset, Bytes);
6868 return true;
6869 }
6870
visitFloat(const APFloat & Val,QualType Ty,CharUnits Offset)6871 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6872 APSInt AsInt(Val.bitcastToAPInt());
6873 return visitInt(AsInt, Ty, Offset);
6874 }
6875
6876 public:
convert(EvalInfo & Info,const APValue & Src,const CastExpr * BCE)6877 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6878 const CastExpr *BCE) {
6879 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6880 APValueToBufferConverter Converter(Info, DstSize, BCE);
6881 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6882 return None;
6883 return Converter.Buffer;
6884 }
6885 };
6886
6887 /// Write an BitCastBuffer into an APValue.
6888 class BufferToAPValueConverter {
6889 EvalInfo &Info;
6890 const BitCastBuffer &Buffer;
6891 const CastExpr *BCE;
6892
BufferToAPValueConverter(EvalInfo & Info,const BitCastBuffer & Buffer,const CastExpr * BCE)6893 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6894 const CastExpr *BCE)
6895 : Info(Info), Buffer(Buffer), BCE(BCE) {}
6896
6897 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6898 // with an invalid type, so anything left is a deficiency on our part (FIXME).
6899 // Ideally this will be unreachable.
unsupportedType(QualType Ty)6900 llvm::NoneType unsupportedType(QualType Ty) {
6901 Info.FFDiag(BCE->getBeginLoc(),
6902 diag::note_constexpr_bit_cast_unsupported_type)
6903 << Ty;
6904 return None;
6905 }
6906
unrepresentableValue(QualType Ty,const APSInt & Val)6907 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
6908 Info.FFDiag(BCE->getBeginLoc(),
6909 diag::note_constexpr_bit_cast_unrepresentable_value)
6910 << Ty << Val.toString(/*Radix=*/10);
6911 return None;
6912 }
6913
visit(const BuiltinType * T,CharUnits Offset,const EnumType * EnumSugar=nullptr)6914 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6915 const EnumType *EnumSugar = nullptr) {
6916 if (T->isNullPtrType()) {
6917 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6918 return APValue((Expr *)nullptr,
6919 /*Offset=*/CharUnits::fromQuantity(NullValue),
6920 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6921 }
6922
6923 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6924
6925 // Work around floating point types that contain unused padding bytes. This
6926 // is really just `long double` on x86, which is the only fundamental type
6927 // with padding bytes.
6928 if (T->isRealFloatingType()) {
6929 const llvm::fltSemantics &Semantics =
6930 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6931 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
6932 assert(NumBits % 8 == 0);
6933 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
6934 if (NumBytes != SizeOf)
6935 SizeOf = NumBytes;
6936 }
6937
6938 SmallVector<uint8_t, 8> Bytes;
6939 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6940 // If this is std::byte or unsigned char, then its okay to store an
6941 // indeterminate value.
6942 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6943 bool IsUChar =
6944 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6945 T->isSpecificBuiltinType(BuiltinType::Char_U));
6946 if (!IsStdByte && !IsUChar) {
6947 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
6948 Info.FFDiag(BCE->getExprLoc(),
6949 diag::note_constexpr_bit_cast_indet_dest)
6950 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6951 return None;
6952 }
6953
6954 return APValue::IndeterminateValue();
6955 }
6956
6957 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
6958 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
6959
6960 if (T->isIntegralOrEnumerationType()) {
6961 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
6962
6963 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
6964 if (IntWidth != Val.getBitWidth()) {
6965 APSInt Truncated = Val.trunc(IntWidth);
6966 if (Truncated.extend(Val.getBitWidth()) != Val)
6967 return unrepresentableValue(QualType(T, 0), Val);
6968 Val = Truncated;
6969 }
6970
6971 return APValue(Val);
6972 }
6973
6974 if (T->isRealFloatingType()) {
6975 const llvm::fltSemantics &Semantics =
6976 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6977 return APValue(APFloat(Semantics, Val));
6978 }
6979
6980 return unsupportedType(QualType(T, 0));
6981 }
6982
visit(const RecordType * RTy,CharUnits Offset)6983 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
6984 const RecordDecl *RD = RTy->getAsRecordDecl();
6985 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6986
6987 unsigned NumBases = 0;
6988 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6989 NumBases = CXXRD->getNumBases();
6990
6991 APValue ResultVal(APValue::UninitStruct(), NumBases,
6992 std::distance(RD->field_begin(), RD->field_end()));
6993
6994 // Visit the base classes.
6995 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6996 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6997 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6998 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6999 if (BaseDecl->isEmpty() ||
7000 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7001 continue;
7002
7003 Optional<APValue> SubObj = visitType(
7004 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7005 if (!SubObj)
7006 return None;
7007 ResultVal.getStructBase(I) = *SubObj;
7008 }
7009 }
7010
7011 // Visit the fields.
7012 unsigned FieldIdx = 0;
7013 for (FieldDecl *FD : RD->fields()) {
7014 // FIXME: We don't currently support bit-fields. A lot of the logic for
7015 // this is in CodeGen, so we need to factor it around.
7016 if (FD->isBitField()) {
7017 Info.FFDiag(BCE->getBeginLoc(),
7018 diag::note_constexpr_bit_cast_unsupported_bitfield);
7019 return None;
7020 }
7021
7022 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7023 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7024
7025 CharUnits FieldOffset =
7026 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7027 Offset;
7028 QualType FieldTy = FD->getType();
7029 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7030 if (!SubObj)
7031 return None;
7032 ResultVal.getStructField(FieldIdx) = *SubObj;
7033 ++FieldIdx;
7034 }
7035
7036 return ResultVal;
7037 }
7038
visit(const EnumType * Ty,CharUnits Offset)7039 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7040 QualType RepresentationType = Ty->getDecl()->getIntegerType();
7041 assert(!RepresentationType.isNull() &&
7042 "enum forward decl should be caught by Sema");
7043 const auto *AsBuiltin =
7044 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7045 // Recurse into the underlying type. Treat std::byte transparently as
7046 // unsigned char.
7047 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7048 }
7049
visit(const ConstantArrayType * Ty,CharUnits Offset)7050 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7051 size_t Size = Ty->getSize().getLimitedValue();
7052 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7053
7054 APValue ArrayValue(APValue::UninitArray(), Size, Size);
7055 for (size_t I = 0; I != Size; ++I) {
7056 Optional<APValue> ElementValue =
7057 visitType(Ty->getElementType(), Offset + I * ElementWidth);
7058 if (!ElementValue)
7059 return None;
7060 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7061 }
7062
7063 return ArrayValue;
7064 }
7065
visit(const Type * Ty,CharUnits Offset)7066 Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7067 return unsupportedType(QualType(Ty, 0));
7068 }
7069
visitType(QualType Ty,CharUnits Offset)7070 Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7071 QualType Can = Ty.getCanonicalType();
7072
7073 switch (Can->getTypeClass()) {
7074 #define TYPE(Class, Base) \
7075 case Type::Class: \
7076 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7077 #define ABSTRACT_TYPE(Class, Base)
7078 #define NON_CANONICAL_TYPE(Class, Base) \
7079 case Type::Class: \
7080 llvm_unreachable("non-canonical type should be impossible!");
7081 #define DEPENDENT_TYPE(Class, Base) \
7082 case Type::Class: \
7083 llvm_unreachable( \
7084 "dependent types aren't supported in the constant evaluator!");
7085 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
7086 case Type::Class: \
7087 llvm_unreachable("either dependent or not canonical!");
7088 #include "clang/AST/TypeNodes.inc"
7089 }
7090 llvm_unreachable("Unhandled Type::TypeClass");
7091 }
7092
7093 public:
7094 // Pull out a full value of type DstType.
convert(EvalInfo & Info,BitCastBuffer & Buffer,const CastExpr * BCE)7095 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7096 const CastExpr *BCE) {
7097 BufferToAPValueConverter Converter(Info, Buffer, BCE);
7098 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7099 }
7100 };
7101
checkBitCastConstexprEligibilityType(SourceLocation Loc,QualType Ty,EvalInfo * Info,const ASTContext & Ctx,bool CheckingDest)7102 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7103 QualType Ty, EvalInfo *Info,
7104 const ASTContext &Ctx,
7105 bool CheckingDest) {
7106 Ty = Ty.getCanonicalType();
7107
7108 auto diag = [&](int Reason) {
7109 if (Info)
7110 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7111 << CheckingDest << (Reason == 4) << Reason;
7112 return false;
7113 };
7114 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7115 if (Info)
7116 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7117 << NoteTy << Construct << Ty;
7118 return false;
7119 };
7120
7121 if (Ty->isUnionType())
7122 return diag(0);
7123 if (Ty->isPointerType())
7124 return diag(1);
7125 if (Ty->isMemberPointerType())
7126 return diag(2);
7127 if (Ty.isVolatileQualified())
7128 return diag(3);
7129
7130 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7131 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7132 for (CXXBaseSpecifier &BS : CXXRD->bases())
7133 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7134 CheckingDest))
7135 return note(1, BS.getType(), BS.getBeginLoc());
7136 }
7137 for (FieldDecl *FD : Record->fields()) {
7138 if (FD->getType()->isReferenceType())
7139 return diag(4);
7140 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7141 CheckingDest))
7142 return note(0, FD->getType(), FD->getBeginLoc());
7143 }
7144 }
7145
7146 if (Ty->isArrayType() &&
7147 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7148 Info, Ctx, CheckingDest))
7149 return false;
7150
7151 return true;
7152 }
7153
checkBitCastConstexprEligibility(EvalInfo * Info,const ASTContext & Ctx,const CastExpr * BCE)7154 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7155 const ASTContext &Ctx,
7156 const CastExpr *BCE) {
7157 bool DestOK = checkBitCastConstexprEligibilityType(
7158 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7159 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7160 BCE->getBeginLoc(),
7161 BCE->getSubExpr()->getType(), Info, Ctx, false);
7162 return SourceOK;
7163 }
7164
handleLValueToRValueBitCast(EvalInfo & Info,APValue & DestValue,APValue & SourceValue,const CastExpr * BCE)7165 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7166 APValue &SourceValue,
7167 const CastExpr *BCE) {
7168 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7169 "no host or target supports non 8-bit chars");
7170 assert(SourceValue.isLValue() &&
7171 "LValueToRValueBitcast requires an lvalue operand!");
7172
7173 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7174 return false;
7175
7176 LValue SourceLValue;
7177 APValue SourceRValue;
7178 SourceLValue.setFrom(Info.Ctx, SourceValue);
7179 if (!handleLValueToRValueConversion(
7180 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7181 SourceRValue, /*WantObjectRepresentation=*/true))
7182 return false;
7183
7184 // Read out SourceValue into a char buffer.
7185 Optional<BitCastBuffer> Buffer =
7186 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7187 if (!Buffer)
7188 return false;
7189
7190 // Write out the buffer into a new APValue.
7191 Optional<APValue> MaybeDestValue =
7192 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7193 if (!MaybeDestValue)
7194 return false;
7195
7196 DestValue = std::move(*MaybeDestValue);
7197 return true;
7198 }
7199
7200 template <class Derived>
7201 class ExprEvaluatorBase
7202 : public ConstStmtVisitor<Derived, bool> {
7203 private:
getDerived()7204 Derived &getDerived() { return static_cast<Derived&>(*this); }
DerivedSuccess(const APValue & V,const Expr * E)7205 bool DerivedSuccess(const APValue &V, const Expr *E) {
7206 return getDerived().Success(V, E);
7207 }
DerivedZeroInitialization(const Expr * E)7208 bool DerivedZeroInitialization(const Expr *E) {
7209 return getDerived().ZeroInitialization(E);
7210 }
7211
7212 // Check whether a conditional operator with a non-constant condition is a
7213 // potential constant expression. If neither arm is a potential constant
7214 // expression, then the conditional operator is not either.
7215 template<typename ConditionalOperator>
CheckPotentialConstantConditional(const ConditionalOperator * E)7216 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7217 assert(Info.checkingPotentialConstantExpression());
7218
7219 // Speculatively evaluate both arms.
7220 SmallVector<PartialDiagnosticAt, 8> Diag;
7221 {
7222 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7223 StmtVisitorTy::Visit(E->getFalseExpr());
7224 if (Diag.empty())
7225 return;
7226 }
7227
7228 {
7229 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7230 Diag.clear();
7231 StmtVisitorTy::Visit(E->getTrueExpr());
7232 if (Diag.empty())
7233 return;
7234 }
7235
7236 Error(E, diag::note_constexpr_conditional_never_const);
7237 }
7238
7239
7240 template<typename ConditionalOperator>
HandleConditionalOperator(const ConditionalOperator * E)7241 bool HandleConditionalOperator(const ConditionalOperator *E) {
7242 bool BoolResult;
7243 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7244 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7245 CheckPotentialConstantConditional(E);
7246 return false;
7247 }
7248 if (Info.noteFailure()) {
7249 StmtVisitorTy::Visit(E->getTrueExpr());
7250 StmtVisitorTy::Visit(E->getFalseExpr());
7251 }
7252 return false;
7253 }
7254
7255 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7256 return StmtVisitorTy::Visit(EvalExpr);
7257 }
7258
7259 protected:
7260 EvalInfo &Info;
7261 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7262 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7263
CCEDiag(const Expr * E,diag::kind D)7264 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7265 return Info.CCEDiag(E, D);
7266 }
7267
ZeroInitialization(const Expr * E)7268 bool ZeroInitialization(const Expr *E) { return Error(E); }
7269
7270 public:
ExprEvaluatorBase(EvalInfo & Info)7271 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7272
getEvalInfo()7273 EvalInfo &getEvalInfo() { return Info; }
7274
7275 /// Report an evaluation error. This should only be called when an error is
7276 /// first discovered. When propagating an error, just return false.
Error(const Expr * E,diag::kind D)7277 bool Error(const Expr *E, diag::kind D) {
7278 Info.FFDiag(E, D);
7279 return false;
7280 }
Error(const Expr * E)7281 bool Error(const Expr *E) {
7282 return Error(E, diag::note_invalid_subexpr_in_const_expr);
7283 }
7284
VisitStmt(const Stmt *)7285 bool VisitStmt(const Stmt *) {
7286 llvm_unreachable("Expression evaluator should not be called on stmts");
7287 }
VisitExpr(const Expr * E)7288 bool VisitExpr(const Expr *E) {
7289 return Error(E);
7290 }
7291
VisitConstantExpr(const ConstantExpr * E)7292 bool VisitConstantExpr(const ConstantExpr *E) {
7293 if (E->hasAPValueResult())
7294 return DerivedSuccess(E->getAPValueResult(), E);
7295
7296 return StmtVisitorTy::Visit(E->getSubExpr());
7297 }
7298
VisitParenExpr(const ParenExpr * E)7299 bool VisitParenExpr(const ParenExpr *E)
7300 { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitUnaryExtension(const UnaryOperator * E)7301 bool VisitUnaryExtension(const UnaryOperator *E)
7302 { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitUnaryPlus(const UnaryOperator * E)7303 bool VisitUnaryPlus(const UnaryOperator *E)
7304 { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitChooseExpr(const ChooseExpr * E)7305 bool VisitChooseExpr(const ChooseExpr *E)
7306 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
VisitGenericSelectionExpr(const GenericSelectionExpr * E)7307 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7308 { return StmtVisitorTy::Visit(E->getResultExpr()); }
VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr * E)7309 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7310 { return StmtVisitorTy::Visit(E->getReplacement()); }
VisitCXXDefaultArgExpr(const CXXDefaultArgExpr * E)7311 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7312 TempVersionRAII RAII(*Info.CurrentCall);
7313 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7314 return StmtVisitorTy::Visit(E->getExpr());
7315 }
VisitCXXDefaultInitExpr(const CXXDefaultInitExpr * E)7316 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7317 TempVersionRAII RAII(*Info.CurrentCall);
7318 // The initializer may not have been parsed yet, or might be erroneous.
7319 if (!E->getExpr())
7320 return Error(E);
7321 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7322 return StmtVisitorTy::Visit(E->getExpr());
7323 }
7324
VisitExprWithCleanups(const ExprWithCleanups * E)7325 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7326 FullExpressionRAII Scope(Info);
7327 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7328 }
7329
7330 // Temporaries are registered when created, so we don't care about
7331 // CXXBindTemporaryExpr.
VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr * E)7332 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7333 return StmtVisitorTy::Visit(E->getSubExpr());
7334 }
7335
VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr * E)7336 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7337 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7338 return static_cast<Derived*>(this)->VisitCastExpr(E);
7339 }
VisitCXXDynamicCastExpr(const CXXDynamicCastExpr * E)7340 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7341 if (!Info.Ctx.getLangOpts().CPlusPlus20)
7342 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7343 return static_cast<Derived*>(this)->VisitCastExpr(E);
7344 }
VisitBuiltinBitCastExpr(const BuiltinBitCastExpr * E)7345 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7346 return static_cast<Derived*>(this)->VisitCastExpr(E);
7347 }
7348
VisitBinaryOperator(const BinaryOperator * E)7349 bool VisitBinaryOperator(const BinaryOperator *E) {
7350 switch (E->getOpcode()) {
7351 default:
7352 return Error(E);
7353
7354 case BO_Comma:
7355 VisitIgnoredValue(E->getLHS());
7356 return StmtVisitorTy::Visit(E->getRHS());
7357
7358 case BO_PtrMemD:
7359 case BO_PtrMemI: {
7360 LValue Obj;
7361 if (!HandleMemberPointerAccess(Info, E, Obj))
7362 return false;
7363 APValue Result;
7364 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7365 return false;
7366 return DerivedSuccess(Result, E);
7367 }
7368 }
7369 }
7370
VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator * E)7371 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7372 return StmtVisitorTy::Visit(E->getSemanticForm());
7373 }
7374
VisitBinaryConditionalOperator(const BinaryConditionalOperator * E)7375 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7376 // Evaluate and cache the common expression. We treat it as a temporary,
7377 // even though it's not quite the same thing.
7378 LValue CommonLV;
7379 if (!Evaluate(Info.CurrentCall->createTemporary(
7380 E->getOpaqueValue(),
7381 getStorageType(Info.Ctx, E->getOpaqueValue()),
7382 ScopeKind::FullExpression, CommonLV),
7383 Info, E->getCommon()))
7384 return false;
7385
7386 return HandleConditionalOperator(E);
7387 }
7388
VisitConditionalOperator(const ConditionalOperator * E)7389 bool VisitConditionalOperator(const ConditionalOperator *E) {
7390 bool IsBcpCall = false;
7391 // If the condition (ignoring parens) is a __builtin_constant_p call,
7392 // the result is a constant expression if it can be folded without
7393 // side-effects. This is an important GNU extension. See GCC PR38377
7394 // for discussion.
7395 if (const CallExpr *CallCE =
7396 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7397 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7398 IsBcpCall = true;
7399
7400 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7401 // constant expression; we can't check whether it's potentially foldable.
7402 // FIXME: We should instead treat __builtin_constant_p as non-constant if
7403 // it would return 'false' in this mode.
7404 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7405 return false;
7406
7407 FoldConstant Fold(Info, IsBcpCall);
7408 if (!HandleConditionalOperator(E)) {
7409 Fold.keepDiagnostics();
7410 return false;
7411 }
7412
7413 return true;
7414 }
7415
VisitOpaqueValueExpr(const OpaqueValueExpr * E)7416 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7417 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7418 return DerivedSuccess(*Value, E);
7419
7420 const Expr *Source = E->getSourceExpr();
7421 if (!Source)
7422 return Error(E);
7423 if (Source == E) { // sanity checking.
7424 assert(0 && "OpaqueValueExpr recursively refers to itself");
7425 return Error(E);
7426 }
7427 return StmtVisitorTy::Visit(Source);
7428 }
7429
VisitPseudoObjectExpr(const PseudoObjectExpr * E)7430 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7431 for (const Expr *SemE : E->semantics()) {
7432 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7433 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7434 // result expression: there could be two different LValues that would
7435 // refer to the same object in that case, and we can't model that.
7436 if (SemE == E->getResultExpr())
7437 return Error(E);
7438
7439 // Unique OVEs get evaluated if and when we encounter them when
7440 // emitting the rest of the semantic form, rather than eagerly.
7441 if (OVE->isUnique())
7442 continue;
7443
7444 LValue LV;
7445 if (!Evaluate(Info.CurrentCall->createTemporary(
7446 OVE, getStorageType(Info.Ctx, OVE),
7447 ScopeKind::FullExpression, LV),
7448 Info, OVE->getSourceExpr()))
7449 return false;
7450 } else if (SemE == E->getResultExpr()) {
7451 if (!StmtVisitorTy::Visit(SemE))
7452 return false;
7453 } else {
7454 if (!EvaluateIgnoredValue(Info, SemE))
7455 return false;
7456 }
7457 }
7458 return true;
7459 }
7460
VisitCallExpr(const CallExpr * E)7461 bool VisitCallExpr(const CallExpr *E) {
7462 APValue Result;
7463 if (!handleCallExpr(E, Result, nullptr))
7464 return false;
7465 return DerivedSuccess(Result, E);
7466 }
7467
handleCallExpr(const CallExpr * E,APValue & Result,const LValue * ResultSlot)7468 bool handleCallExpr(const CallExpr *E, APValue &Result,
7469 const LValue *ResultSlot) {
7470 CallScopeRAII CallScope(Info);
7471
7472 const Expr *Callee = E->getCallee()->IgnoreParens();
7473 QualType CalleeType = Callee->getType();
7474
7475 const FunctionDecl *FD = nullptr;
7476 LValue *This = nullptr, ThisVal;
7477 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7478 bool HasQualifier = false;
7479
7480 CallRef Call;
7481
7482 // Extract function decl and 'this' pointer from the callee.
7483 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7484 const CXXMethodDecl *Member = nullptr;
7485 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7486 // Explicit bound member calls, such as x.f() or p->g();
7487 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7488 return false;
7489 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7490 if (!Member)
7491 return Error(Callee);
7492 This = &ThisVal;
7493 HasQualifier = ME->hasQualifier();
7494 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7495 // Indirect bound member calls ('.*' or '->*').
7496 const ValueDecl *D =
7497 HandleMemberPointerAccess(Info, BE, ThisVal, false);
7498 if (!D)
7499 return false;
7500 Member = dyn_cast<CXXMethodDecl>(D);
7501 if (!Member)
7502 return Error(Callee);
7503 This = &ThisVal;
7504 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7505 if (!Info.getLangOpts().CPlusPlus20)
7506 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7507 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7508 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7509 } else
7510 return Error(Callee);
7511 FD = Member;
7512 } else if (CalleeType->isFunctionPointerType()) {
7513 LValue CalleeLV;
7514 if (!EvaluatePointer(Callee, CalleeLV, Info))
7515 return false;
7516
7517 if (!CalleeLV.getLValueOffset().isZero())
7518 return Error(Callee);
7519 FD = dyn_cast_or_null<FunctionDecl>(
7520 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7521 if (!FD)
7522 return Error(Callee);
7523 // Don't call function pointers which have been cast to some other type.
7524 // Per DR (no number yet), the caller and callee can differ in noexcept.
7525 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7526 CalleeType->getPointeeType(), FD->getType())) {
7527 return Error(E);
7528 }
7529
7530 // For an (overloaded) assignment expression, evaluate the RHS before the
7531 // LHS.
7532 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7533 if (OCE && OCE->isAssignmentOp()) {
7534 assert(Args.size() == 2 && "wrong number of arguments in assignment");
7535 Call = Info.CurrentCall->createCall(FD);
7536 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7537 Info, FD, /*RightToLeft=*/true))
7538 return false;
7539 }
7540
7541 // Overloaded operator calls to member functions are represented as normal
7542 // calls with '*this' as the first argument.
7543 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7544 if (MD && !MD->isStatic()) {
7545 // FIXME: When selecting an implicit conversion for an overloaded
7546 // operator delete, we sometimes try to evaluate calls to conversion
7547 // operators without a 'this' parameter!
7548 if (Args.empty())
7549 return Error(E);
7550
7551 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7552 return false;
7553 This = &ThisVal;
7554 Args = Args.slice(1);
7555 } else if (MD && MD->isLambdaStaticInvoker()) {
7556 // Map the static invoker for the lambda back to the call operator.
7557 // Conveniently, we don't have to slice out the 'this' argument (as is
7558 // being done for the non-static case), since a static member function
7559 // doesn't have an implicit argument passed in.
7560 const CXXRecordDecl *ClosureClass = MD->getParent();
7561 assert(
7562 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7563 "Number of captures must be zero for conversion to function-ptr");
7564
7565 const CXXMethodDecl *LambdaCallOp =
7566 ClosureClass->getLambdaCallOperator();
7567
7568 // Set 'FD', the function that will be called below, to the call
7569 // operator. If the closure object represents a generic lambda, find
7570 // the corresponding specialization of the call operator.
7571
7572 if (ClosureClass->isGenericLambda()) {
7573 assert(MD->isFunctionTemplateSpecialization() &&
7574 "A generic lambda's static-invoker function must be a "
7575 "template specialization");
7576 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7577 FunctionTemplateDecl *CallOpTemplate =
7578 LambdaCallOp->getDescribedFunctionTemplate();
7579 void *InsertPos = nullptr;
7580 FunctionDecl *CorrespondingCallOpSpecialization =
7581 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7582 assert(CorrespondingCallOpSpecialization &&
7583 "We must always have a function call operator specialization "
7584 "that corresponds to our static invoker specialization");
7585 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7586 } else
7587 FD = LambdaCallOp;
7588 } else if (FD->isReplaceableGlobalAllocationFunction()) {
7589 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7590 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7591 LValue Ptr;
7592 if (!HandleOperatorNewCall(Info, E, Ptr))
7593 return false;
7594 Ptr.moveInto(Result);
7595 return CallScope.destroy();
7596 } else {
7597 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7598 }
7599 }
7600 } else
7601 return Error(E);
7602
7603 // Evaluate the arguments now if we've not already done so.
7604 if (!Call) {
7605 Call = Info.CurrentCall->createCall(FD);
7606 if (!EvaluateArgs(Args, Call, Info, FD))
7607 return false;
7608 }
7609
7610 SmallVector<QualType, 4> CovariantAdjustmentPath;
7611 if (This) {
7612 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7613 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7614 // Perform virtual dispatch, if necessary.
7615 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7616 CovariantAdjustmentPath);
7617 if (!FD)
7618 return false;
7619 } else {
7620 // Check that the 'this' pointer points to an object of the right type.
7621 // FIXME: If this is an assignment operator call, we may need to change
7622 // the active union member before we check this.
7623 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7624 return false;
7625 }
7626 }
7627
7628 // Destructor calls are different enough that they have their own codepath.
7629 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7630 assert(This && "no 'this' pointer for destructor call");
7631 return HandleDestruction(Info, E, *This,
7632 Info.Ctx.getRecordType(DD->getParent())) &&
7633 CallScope.destroy();
7634 }
7635
7636 const FunctionDecl *Definition = nullptr;
7637 Stmt *Body = FD->getBody(Definition);
7638
7639 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7640 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7641 Body, Info, Result, ResultSlot))
7642 return false;
7643
7644 if (!CovariantAdjustmentPath.empty() &&
7645 !HandleCovariantReturnAdjustment(Info, E, Result,
7646 CovariantAdjustmentPath))
7647 return false;
7648
7649 return CallScope.destroy();
7650 }
7651
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)7652 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7653 return StmtVisitorTy::Visit(E->getInitializer());
7654 }
VisitInitListExpr(const InitListExpr * E)7655 bool VisitInitListExpr(const InitListExpr *E) {
7656 if (E->getNumInits() == 0)
7657 return DerivedZeroInitialization(E);
7658 if (E->getNumInits() == 1)
7659 return StmtVisitorTy::Visit(E->getInit(0));
7660 return Error(E);
7661 }
VisitImplicitValueInitExpr(const ImplicitValueInitExpr * E)7662 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7663 return DerivedZeroInitialization(E);
7664 }
VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr * E)7665 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7666 return DerivedZeroInitialization(E);
7667 }
VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr * E)7668 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7669 return DerivedZeroInitialization(E);
7670 }
7671
7672 /// A member expression where the object is a prvalue is itself a prvalue.
VisitMemberExpr(const MemberExpr * E)7673 bool VisitMemberExpr(const MemberExpr *E) {
7674 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7675 "missing temporary materialization conversion");
7676 assert(!E->isArrow() && "missing call to bound member function?");
7677
7678 APValue Val;
7679 if (!Evaluate(Val, Info, E->getBase()))
7680 return false;
7681
7682 QualType BaseTy = E->getBase()->getType();
7683
7684 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7685 if (!FD) return Error(E);
7686 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7687 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7688 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7689
7690 // Note: there is no lvalue base here. But this case should only ever
7691 // happen in C or in C++98, where we cannot be evaluating a constexpr
7692 // constructor, which is the only case the base matters.
7693 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7694 SubobjectDesignator Designator(BaseTy);
7695 Designator.addDeclUnchecked(FD);
7696
7697 APValue Result;
7698 return extractSubobject(Info, E, Obj, Designator, Result) &&
7699 DerivedSuccess(Result, E);
7700 }
7701
VisitExtVectorElementExpr(const ExtVectorElementExpr * E)7702 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7703 APValue Val;
7704 if (!Evaluate(Val, Info, E->getBase()))
7705 return false;
7706
7707 if (Val.isVector()) {
7708 SmallVector<uint32_t, 4> Indices;
7709 E->getEncodedElementAccess(Indices);
7710 if (Indices.size() == 1) {
7711 // Return scalar.
7712 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7713 } else {
7714 // Construct new APValue vector.
7715 SmallVector<APValue, 4> Elts;
7716 for (unsigned I = 0; I < Indices.size(); ++I) {
7717 Elts.push_back(Val.getVectorElt(Indices[I]));
7718 }
7719 APValue VecResult(Elts.data(), Indices.size());
7720 return DerivedSuccess(VecResult, E);
7721 }
7722 }
7723
7724 return false;
7725 }
7726
VisitCastExpr(const CastExpr * E)7727 bool VisitCastExpr(const CastExpr *E) {
7728 switch (E->getCastKind()) {
7729 default:
7730 break;
7731
7732 case CK_AtomicToNonAtomic: {
7733 APValue AtomicVal;
7734 // This does not need to be done in place even for class/array types:
7735 // atomic-to-non-atomic conversion implies copying the object
7736 // representation.
7737 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7738 return false;
7739 return DerivedSuccess(AtomicVal, E);
7740 }
7741
7742 case CK_NoOp:
7743 case CK_UserDefinedConversion:
7744 return StmtVisitorTy::Visit(E->getSubExpr());
7745
7746 case CK_LValueToRValue: {
7747 LValue LVal;
7748 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7749 return false;
7750 APValue RVal;
7751 // Note, we use the subexpression's type in order to retain cv-qualifiers.
7752 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7753 LVal, RVal))
7754 return false;
7755 return DerivedSuccess(RVal, E);
7756 }
7757 case CK_LValueToRValueBitCast: {
7758 APValue DestValue, SourceValue;
7759 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7760 return false;
7761 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7762 return false;
7763 return DerivedSuccess(DestValue, E);
7764 }
7765
7766 case CK_AddressSpaceConversion: {
7767 APValue Value;
7768 if (!Evaluate(Value, Info, E->getSubExpr()))
7769 return false;
7770 return DerivedSuccess(Value, E);
7771 }
7772 }
7773
7774 return Error(E);
7775 }
7776
VisitUnaryPostInc(const UnaryOperator * UO)7777 bool VisitUnaryPostInc(const UnaryOperator *UO) {
7778 return VisitUnaryPostIncDec(UO);
7779 }
VisitUnaryPostDec(const UnaryOperator * UO)7780 bool VisitUnaryPostDec(const UnaryOperator *UO) {
7781 return VisitUnaryPostIncDec(UO);
7782 }
VisitUnaryPostIncDec(const UnaryOperator * UO)7783 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7784 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7785 return Error(UO);
7786
7787 LValue LVal;
7788 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7789 return false;
7790 APValue RVal;
7791 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7792 UO->isIncrementOp(), &RVal))
7793 return false;
7794 return DerivedSuccess(RVal, UO);
7795 }
7796
VisitStmtExpr(const StmtExpr * E)7797 bool VisitStmtExpr(const StmtExpr *E) {
7798 // We will have checked the full-expressions inside the statement expression
7799 // when they were completed, and don't need to check them again now.
7800 if (Info.checkingForUndefinedBehavior())
7801 return Error(E);
7802
7803 const CompoundStmt *CS = E->getSubStmt();
7804 if (CS->body_empty())
7805 return true;
7806
7807 BlockScopeRAII Scope(Info);
7808 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7809 BE = CS->body_end();
7810 /**/; ++BI) {
7811 if (BI + 1 == BE) {
7812 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7813 if (!FinalExpr) {
7814 Info.FFDiag((*BI)->getBeginLoc(),
7815 diag::note_constexpr_stmt_expr_unsupported);
7816 return false;
7817 }
7818 return this->Visit(FinalExpr) && Scope.destroy();
7819 }
7820
7821 APValue ReturnValue;
7822 StmtResult Result = { ReturnValue, nullptr };
7823 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7824 if (ESR != ESR_Succeeded) {
7825 // FIXME: If the statement-expression terminated due to 'return',
7826 // 'break', or 'continue', it would be nice to propagate that to
7827 // the outer statement evaluation rather than bailing out.
7828 if (ESR != ESR_Failed)
7829 Info.FFDiag((*BI)->getBeginLoc(),
7830 diag::note_constexpr_stmt_expr_unsupported);
7831 return false;
7832 }
7833 }
7834
7835 llvm_unreachable("Return from function from the loop above.");
7836 }
7837
7838 /// Visit a value which is evaluated, but whose value is ignored.
VisitIgnoredValue(const Expr * E)7839 void VisitIgnoredValue(const Expr *E) {
7840 EvaluateIgnoredValue(Info, E);
7841 }
7842
7843 /// Potentially visit a MemberExpr's base expression.
VisitIgnoredBaseExpression(const Expr * E)7844 void VisitIgnoredBaseExpression(const Expr *E) {
7845 // While MSVC doesn't evaluate the base expression, it does diagnose the
7846 // presence of side-effecting behavior.
7847 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7848 return;
7849 VisitIgnoredValue(E);
7850 }
7851 };
7852
7853 } // namespace
7854
7855 //===----------------------------------------------------------------------===//
7856 // Common base class for lvalue and temporary evaluation.
7857 //===----------------------------------------------------------------------===//
7858 namespace {
7859 template<class Derived>
7860 class LValueExprEvaluatorBase
7861 : public ExprEvaluatorBase<Derived> {
7862 protected:
7863 LValue &Result;
7864 bool InvalidBaseOK;
7865 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7866 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7867
Success(APValue::LValueBase B)7868 bool Success(APValue::LValueBase B) {
7869 Result.set(B);
7870 return true;
7871 }
7872
evaluatePointer(const Expr * E,LValue & Result)7873 bool evaluatePointer(const Expr *E, LValue &Result) {
7874 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7875 }
7876
7877 public:
LValueExprEvaluatorBase(EvalInfo & Info,LValue & Result,bool InvalidBaseOK)7878 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7879 : ExprEvaluatorBaseTy(Info), Result(Result),
7880 InvalidBaseOK(InvalidBaseOK) {}
7881
Success(const APValue & V,const Expr * E)7882 bool Success(const APValue &V, const Expr *E) {
7883 Result.setFrom(this->Info.Ctx, V);
7884 return true;
7885 }
7886
VisitMemberExpr(const MemberExpr * E)7887 bool VisitMemberExpr(const MemberExpr *E) {
7888 // Handle non-static data members.
7889 QualType BaseTy;
7890 bool EvalOK;
7891 if (E->isArrow()) {
7892 EvalOK = evaluatePointer(E->getBase(), Result);
7893 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7894 } else if (E->getBase()->isRValue()) {
7895 assert(E->getBase()->getType()->isRecordType());
7896 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7897 BaseTy = E->getBase()->getType();
7898 } else {
7899 EvalOK = this->Visit(E->getBase());
7900 BaseTy = E->getBase()->getType();
7901 }
7902 if (!EvalOK) {
7903 if (!InvalidBaseOK)
7904 return false;
7905 Result.setInvalid(E);
7906 return true;
7907 }
7908
7909 const ValueDecl *MD = E->getMemberDecl();
7910 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7911 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7912 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7913 (void)BaseTy;
7914 if (!HandleLValueMember(this->Info, E, Result, FD))
7915 return false;
7916 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7917 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7918 return false;
7919 } else
7920 return this->Error(E);
7921
7922 if (MD->getType()->isReferenceType()) {
7923 APValue RefValue;
7924 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7925 RefValue))
7926 return false;
7927 return Success(RefValue, E);
7928 }
7929 return true;
7930 }
7931
VisitBinaryOperator(const BinaryOperator * E)7932 bool VisitBinaryOperator(const BinaryOperator *E) {
7933 switch (E->getOpcode()) {
7934 default:
7935 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7936
7937 case BO_PtrMemD:
7938 case BO_PtrMemI:
7939 return HandleMemberPointerAccess(this->Info, E, Result);
7940 }
7941 }
7942
VisitCastExpr(const CastExpr * E)7943 bool VisitCastExpr(const CastExpr *E) {
7944 switch (E->getCastKind()) {
7945 default:
7946 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7947
7948 case CK_DerivedToBase:
7949 case CK_UncheckedDerivedToBase:
7950 if (!this->Visit(E->getSubExpr()))
7951 return false;
7952
7953 // Now figure out the necessary offset to add to the base LV to get from
7954 // the derived class to the base class.
7955 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
7956 Result);
7957 }
7958 }
7959 };
7960 }
7961
7962 //===----------------------------------------------------------------------===//
7963 // LValue Evaluation
7964 //
7965 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
7966 // function designators (in C), decl references to void objects (in C), and
7967 // temporaries (if building with -Wno-address-of-temporary).
7968 //
7969 // LValue evaluation produces values comprising a base expression of one of the
7970 // following types:
7971 // - Declarations
7972 // * VarDecl
7973 // * FunctionDecl
7974 // - Literals
7975 // * CompoundLiteralExpr in C (and in global scope in C++)
7976 // * StringLiteral
7977 // * PredefinedExpr
7978 // * ObjCStringLiteralExpr
7979 // * ObjCEncodeExpr
7980 // * AddrLabelExpr
7981 // * BlockExpr
7982 // * CallExpr for a MakeStringConstant builtin
7983 // - typeid(T) expressions, as TypeInfoLValues
7984 // - Locals and temporaries
7985 // * MaterializeTemporaryExpr
7986 // * Any Expr, with a CallIndex indicating the function in which the temporary
7987 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
7988 // from the AST (FIXME).
7989 // * A MaterializeTemporaryExpr that has static storage duration, with no
7990 // CallIndex, for a lifetime-extended temporary.
7991 // * The ConstantExpr that is currently being evaluated during evaluation of an
7992 // immediate invocation.
7993 // plus an offset in bytes.
7994 //===----------------------------------------------------------------------===//
7995 namespace {
7996 class LValueExprEvaluator
7997 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
7998 public:
LValueExprEvaluator(EvalInfo & Info,LValue & Result,bool InvalidBaseOK)7999 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8000 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8001
8002 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8003 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8004
8005 bool VisitDeclRefExpr(const DeclRefExpr *E);
VisitPredefinedExpr(const PredefinedExpr * E)8006 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8007 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8008 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8009 bool VisitMemberExpr(const MemberExpr *E);
VisitStringLiteral(const StringLiteral * E)8010 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
VisitObjCEncodeExpr(const ObjCEncodeExpr * E)8011 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8012 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8013 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8014 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8015 bool VisitUnaryDeref(const UnaryOperator *E);
8016 bool VisitUnaryReal(const UnaryOperator *E);
8017 bool VisitUnaryImag(const UnaryOperator *E);
VisitUnaryPreInc(const UnaryOperator * UO)8018 bool VisitUnaryPreInc(const UnaryOperator *UO) {
8019 return VisitUnaryPreIncDec(UO);
8020 }
VisitUnaryPreDec(const UnaryOperator * UO)8021 bool VisitUnaryPreDec(const UnaryOperator *UO) {
8022 return VisitUnaryPreIncDec(UO);
8023 }
8024 bool VisitBinAssign(const BinaryOperator *BO);
8025 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8026
VisitCastExpr(const CastExpr * E)8027 bool VisitCastExpr(const CastExpr *E) {
8028 switch (E->getCastKind()) {
8029 default:
8030 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8031
8032 case CK_LValueBitCast:
8033 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8034 if (!Visit(E->getSubExpr()))
8035 return false;
8036 Result.Designator.setInvalid();
8037 return true;
8038
8039 case CK_BaseToDerived:
8040 if (!Visit(E->getSubExpr()))
8041 return false;
8042 return HandleBaseToDerivedCast(Info, E, Result);
8043
8044 case CK_Dynamic:
8045 if (!Visit(E->getSubExpr()))
8046 return false;
8047 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8048 }
8049 }
8050 };
8051 } // end anonymous namespace
8052
8053 /// Evaluate an expression as an lvalue. This can be legitimately called on
8054 /// expressions which are not glvalues, in three cases:
8055 /// * function designators in C, and
8056 /// * "extern void" objects
8057 /// * @selector() expressions in Objective-C
EvaluateLValue(const Expr * E,LValue & Result,EvalInfo & Info,bool InvalidBaseOK)8058 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8059 bool InvalidBaseOK) {
8060 assert(E->isGLValue() || E->getType()->isFunctionType() ||
8061 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8062 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8063 }
8064
VisitDeclRefExpr(const DeclRefExpr * E)8065 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8066 const NamedDecl *D = E->getDecl();
8067 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D))
8068 return Success(cast<ValueDecl>(D));
8069 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8070 return VisitVarDecl(E, VD);
8071 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8072 return Visit(BD->getBinding());
8073 return Error(E);
8074 }
8075
8076
VisitVarDecl(const Expr * E,const VarDecl * VD)8077 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8078
8079 // If we are within a lambda's call operator, check whether the 'VD' referred
8080 // to within 'E' actually represents a lambda-capture that maps to a
8081 // data-member/field within the closure object, and if so, evaluate to the
8082 // field or what the field refers to.
8083 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8084 isa<DeclRefExpr>(E) &&
8085 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8086 // We don't always have a complete capture-map when checking or inferring if
8087 // the function call operator meets the requirements of a constexpr function
8088 // - but we don't need to evaluate the captures to determine constexprness
8089 // (dcl.constexpr C++17).
8090 if (Info.checkingPotentialConstantExpression())
8091 return false;
8092
8093 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8094 // Start with 'Result' referring to the complete closure object...
8095 Result = *Info.CurrentCall->This;
8096 // ... then update it to refer to the field of the closure object
8097 // that represents the capture.
8098 if (!HandleLValueMember(Info, E, Result, FD))
8099 return false;
8100 // And if the field is of reference type, update 'Result' to refer to what
8101 // the field refers to.
8102 if (FD->getType()->isReferenceType()) {
8103 APValue RVal;
8104 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8105 RVal))
8106 return false;
8107 Result.setFrom(Info.Ctx, RVal);
8108 }
8109 return true;
8110 }
8111 }
8112
8113 CallStackFrame *Frame = nullptr;
8114 unsigned Version = 0;
8115 if (VD->hasLocalStorage()) {
8116 // Only if a local variable was declared in the function currently being
8117 // evaluated, do we expect to be able to find its value in the current
8118 // frame. (Otherwise it was likely declared in an enclosing context and
8119 // could either have a valid evaluatable value (for e.g. a constexpr
8120 // variable) or be ill-formed (and trigger an appropriate evaluation
8121 // diagnostic)).
8122 CallStackFrame *CurrFrame = Info.CurrentCall;
8123 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8124 // Function parameters are stored in some caller's frame. (Usually the
8125 // immediate caller, but for an inherited constructor they may be more
8126 // distant.)
8127 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8128 if (CurrFrame->Arguments) {
8129 VD = CurrFrame->Arguments.getOrigParam(PVD);
8130 Frame =
8131 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8132 Version = CurrFrame->Arguments.Version;
8133 }
8134 } else {
8135 Frame = CurrFrame;
8136 Version = CurrFrame->getCurrentTemporaryVersion(VD);
8137 }
8138 }
8139 }
8140
8141 if (!VD->getType()->isReferenceType()) {
8142 if (Frame) {
8143 Result.set({VD, Frame->Index, Version});
8144 return true;
8145 }
8146 return Success(VD);
8147 }
8148
8149 if (!Info.getLangOpts().CPlusPlus11) {
8150 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8151 << VD << VD->getType();
8152 Info.Note(VD->getLocation(), diag::note_declared_at);
8153 }
8154
8155 APValue *V;
8156 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8157 return false;
8158 if (!V->hasValue()) {
8159 // FIXME: Is it possible for V to be indeterminate here? If so, we should
8160 // adjust the diagnostic to say that.
8161 if (!Info.checkingPotentialConstantExpression())
8162 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8163 return false;
8164 }
8165 return Success(*V, E);
8166 }
8167
VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr * E)8168 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8169 const MaterializeTemporaryExpr *E) {
8170 // Walk through the expression to find the materialized temporary itself.
8171 SmallVector<const Expr *, 2> CommaLHSs;
8172 SmallVector<SubobjectAdjustment, 2> Adjustments;
8173 const Expr *Inner =
8174 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8175
8176 // If we passed any comma operators, evaluate their LHSs.
8177 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8178 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8179 return false;
8180
8181 // A materialized temporary with static storage duration can appear within the
8182 // result of a constant expression evaluation, so we need to preserve its
8183 // value for use outside this evaluation.
8184 APValue *Value;
8185 if (E->getStorageDuration() == SD_Static) {
8186 // FIXME: What about SD_Thread?
8187 Value = E->getOrCreateValue(true);
8188 *Value = APValue();
8189 Result.set(E);
8190 } else {
8191 Value = &Info.CurrentCall->createTemporary(
8192 E, E->getType(),
8193 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8194 : ScopeKind::Block,
8195 Result);
8196 }
8197
8198 QualType Type = Inner->getType();
8199
8200 // Materialize the temporary itself.
8201 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8202 *Value = APValue();
8203 return false;
8204 }
8205
8206 // Adjust our lvalue to refer to the desired subobject.
8207 for (unsigned I = Adjustments.size(); I != 0; /**/) {
8208 --I;
8209 switch (Adjustments[I].Kind) {
8210 case SubobjectAdjustment::DerivedToBaseAdjustment:
8211 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8212 Type, Result))
8213 return false;
8214 Type = Adjustments[I].DerivedToBase.BasePath->getType();
8215 break;
8216
8217 case SubobjectAdjustment::FieldAdjustment:
8218 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8219 return false;
8220 Type = Adjustments[I].Field->getType();
8221 break;
8222
8223 case SubobjectAdjustment::MemberPointerAdjustment:
8224 if (!HandleMemberPointerAccess(this->Info, Type, Result,
8225 Adjustments[I].Ptr.RHS))
8226 return false;
8227 Type = Adjustments[I].Ptr.MPT->getPointeeType();
8228 break;
8229 }
8230 }
8231
8232 return true;
8233 }
8234
8235 bool
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)8236 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8237 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8238 "lvalue compound literal in c++?");
8239 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8240 // only see this when folding in C, so there's no standard to follow here.
8241 return Success(E);
8242 }
8243
VisitCXXTypeidExpr(const CXXTypeidExpr * E)8244 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8245 TypeInfoLValue TypeInfo;
8246
8247 if (!E->isPotentiallyEvaluated()) {
8248 if (E->isTypeOperand())
8249 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8250 else
8251 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8252 } else {
8253 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8254 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8255 << E->getExprOperand()->getType()
8256 << E->getExprOperand()->getSourceRange();
8257 }
8258
8259 if (!Visit(E->getExprOperand()))
8260 return false;
8261
8262 Optional<DynamicType> DynType =
8263 ComputeDynamicType(Info, E, Result, AK_TypeId);
8264 if (!DynType)
8265 return false;
8266
8267 TypeInfo =
8268 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8269 }
8270
8271 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8272 }
8273
VisitCXXUuidofExpr(const CXXUuidofExpr * E)8274 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8275 return Success(E->getGuidDecl());
8276 }
8277
VisitMemberExpr(const MemberExpr * E)8278 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8279 // Handle static data members.
8280 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8281 VisitIgnoredBaseExpression(E->getBase());
8282 return VisitVarDecl(E, VD);
8283 }
8284
8285 // Handle static member functions.
8286 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8287 if (MD->isStatic()) {
8288 VisitIgnoredBaseExpression(E->getBase());
8289 return Success(MD);
8290 }
8291 }
8292
8293 // Handle non-static data members.
8294 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8295 }
8296
VisitArraySubscriptExpr(const ArraySubscriptExpr * E)8297 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8298 // FIXME: Deal with vectors as array subscript bases.
8299 if (E->getBase()->getType()->isVectorType())
8300 return Error(E);
8301
8302 APSInt Index;
8303 bool Success = true;
8304
8305 // C++17's rules require us to evaluate the LHS first, regardless of which
8306 // side is the base.
8307 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8308 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8309 : !EvaluateInteger(SubExpr, Index, Info)) {
8310 if (!Info.noteFailure())
8311 return false;
8312 Success = false;
8313 }
8314 }
8315
8316 return Success &&
8317 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8318 }
8319
VisitUnaryDeref(const UnaryOperator * E)8320 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8321 return evaluatePointer(E->getSubExpr(), Result);
8322 }
8323
VisitUnaryReal(const UnaryOperator * E)8324 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8325 if (!Visit(E->getSubExpr()))
8326 return false;
8327 // __real is a no-op on scalar lvalues.
8328 if (E->getSubExpr()->getType()->isAnyComplexType())
8329 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8330 return true;
8331 }
8332
VisitUnaryImag(const UnaryOperator * E)8333 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8334 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8335 "lvalue __imag__ on scalar?");
8336 if (!Visit(E->getSubExpr()))
8337 return false;
8338 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8339 return true;
8340 }
8341
VisitUnaryPreIncDec(const UnaryOperator * UO)8342 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8343 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8344 return Error(UO);
8345
8346 if (!this->Visit(UO->getSubExpr()))
8347 return false;
8348
8349 return handleIncDec(
8350 this->Info, UO, Result, UO->getSubExpr()->getType(),
8351 UO->isIncrementOp(), nullptr);
8352 }
8353
VisitCompoundAssignOperator(const CompoundAssignOperator * CAO)8354 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8355 const CompoundAssignOperator *CAO) {
8356 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8357 return Error(CAO);
8358
8359 bool Success = true;
8360
8361 // C++17 onwards require that we evaluate the RHS first.
8362 APValue RHS;
8363 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8364 if (!Info.noteFailure())
8365 return false;
8366 Success = false;
8367 }
8368
8369 // The overall lvalue result is the result of evaluating the LHS.
8370 if (!this->Visit(CAO->getLHS()) || !Success)
8371 return false;
8372
8373 return handleCompoundAssignment(
8374 this->Info, CAO,
8375 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8376 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8377 }
8378
VisitBinAssign(const BinaryOperator * E)8379 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8380 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8381 return Error(E);
8382
8383 bool Success = true;
8384
8385 // C++17 onwards require that we evaluate the RHS first.
8386 APValue NewVal;
8387 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8388 if (!Info.noteFailure())
8389 return false;
8390 Success = false;
8391 }
8392
8393 if (!this->Visit(E->getLHS()) || !Success)
8394 return false;
8395
8396 if (Info.getLangOpts().CPlusPlus20 &&
8397 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8398 return false;
8399
8400 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8401 NewVal);
8402 }
8403
8404 //===----------------------------------------------------------------------===//
8405 // Pointer Evaluation
8406 //===----------------------------------------------------------------------===//
8407
8408 /// Attempts to compute the number of bytes available at the pointer
8409 /// returned by a function with the alloc_size attribute. Returns true if we
8410 /// were successful. Places an unsigned number into `Result`.
8411 ///
8412 /// This expects the given CallExpr to be a call to a function with an
8413 /// alloc_size attribute.
getBytesReturnedByAllocSizeCall(const ASTContext & Ctx,const CallExpr * Call,llvm::APInt & Result)8414 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8415 const CallExpr *Call,
8416 llvm::APInt &Result) {
8417 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8418
8419 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8420 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8421 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8422 if (Call->getNumArgs() <= SizeArgNo)
8423 return false;
8424
8425 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8426 Expr::EvalResult ExprResult;
8427 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8428 return false;
8429 Into = ExprResult.Val.getInt();
8430 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8431 return false;
8432 Into = Into.zextOrSelf(BitsInSizeT);
8433 return true;
8434 };
8435
8436 APSInt SizeOfElem;
8437 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8438 return false;
8439
8440 if (!AllocSize->getNumElemsParam().isValid()) {
8441 Result = std::move(SizeOfElem);
8442 return true;
8443 }
8444
8445 APSInt NumberOfElems;
8446 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8447 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8448 return false;
8449
8450 bool Overflow;
8451 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8452 if (Overflow)
8453 return false;
8454
8455 Result = std::move(BytesAvailable);
8456 return true;
8457 }
8458
8459 /// Convenience function. LVal's base must be a call to an alloc_size
8460 /// function.
getBytesReturnedByAllocSizeCall(const ASTContext & Ctx,const LValue & LVal,llvm::APInt & Result)8461 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8462 const LValue &LVal,
8463 llvm::APInt &Result) {
8464 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8465 "Can't get the size of a non alloc_size function");
8466 const auto *Base = LVal.getLValueBase().get<const Expr *>();
8467 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8468 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8469 }
8470
8471 /// Attempts to evaluate the given LValueBase as the result of a call to
8472 /// a function with the alloc_size attribute. If it was possible to do so, this
8473 /// function will return true, make Result's Base point to said function call,
8474 /// and mark Result's Base as invalid.
evaluateLValueAsAllocSize(EvalInfo & Info,APValue::LValueBase Base,LValue & Result)8475 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8476 LValue &Result) {
8477 if (Base.isNull())
8478 return false;
8479
8480 // Because we do no form of static analysis, we only support const variables.
8481 //
8482 // Additionally, we can't support parameters, nor can we support static
8483 // variables (in the latter case, use-before-assign isn't UB; in the former,
8484 // we have no clue what they'll be assigned to).
8485 const auto *VD =
8486 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8487 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8488 return false;
8489
8490 const Expr *Init = VD->getAnyInitializer();
8491 if (!Init)
8492 return false;
8493
8494 const Expr *E = Init->IgnoreParens();
8495 if (!tryUnwrapAllocSizeCall(E))
8496 return false;
8497
8498 // Store E instead of E unwrapped so that the type of the LValue's base is
8499 // what the user wanted.
8500 Result.setInvalid(E);
8501
8502 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8503 Result.addUnsizedArray(Info, E, Pointee);
8504 return true;
8505 }
8506
8507 namespace {
8508 class PointerExprEvaluator
8509 : public ExprEvaluatorBase<PointerExprEvaluator> {
8510 LValue &Result;
8511 bool InvalidBaseOK;
8512
Success(const Expr * E)8513 bool Success(const Expr *E) {
8514 Result.set(E);
8515 return true;
8516 }
8517
evaluateLValue(const Expr * E,LValue & Result)8518 bool evaluateLValue(const Expr *E, LValue &Result) {
8519 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8520 }
8521
evaluatePointer(const Expr * E,LValue & Result)8522 bool evaluatePointer(const Expr *E, LValue &Result) {
8523 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8524 }
8525
8526 bool visitNonBuiltinCallExpr(const CallExpr *E);
8527 public:
8528
PointerExprEvaluator(EvalInfo & info,LValue & Result,bool InvalidBaseOK)8529 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8530 : ExprEvaluatorBaseTy(info), Result(Result),
8531 InvalidBaseOK(InvalidBaseOK) {}
8532
Success(const APValue & V,const Expr * E)8533 bool Success(const APValue &V, const Expr *E) {
8534 Result.setFrom(Info.Ctx, V);
8535 return true;
8536 }
ZeroInitialization(const Expr * E)8537 bool ZeroInitialization(const Expr *E) {
8538 Result.setNull(Info.Ctx, E->getType());
8539 return true;
8540 }
8541
8542 bool VisitBinaryOperator(const BinaryOperator *E);
8543 bool VisitCastExpr(const CastExpr* E);
8544 bool VisitUnaryAddrOf(const UnaryOperator *E);
VisitObjCStringLiteral(const ObjCStringLiteral * E)8545 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8546 { return Success(E); }
VisitObjCBoxedExpr(const ObjCBoxedExpr * E)8547 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8548 if (E->isExpressibleAsConstantInitializer())
8549 return Success(E);
8550 if (Info.noteFailure())
8551 EvaluateIgnoredValue(Info, E->getSubExpr());
8552 return Error(E);
8553 }
VisitAddrLabelExpr(const AddrLabelExpr * E)8554 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8555 { return Success(E); }
8556 bool VisitCallExpr(const CallExpr *E);
8557 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
VisitBlockExpr(const BlockExpr * E)8558 bool VisitBlockExpr(const BlockExpr *E) {
8559 if (!E->getBlockDecl()->hasCaptures())
8560 return Success(E);
8561 return Error(E);
8562 }
VisitCXXThisExpr(const CXXThisExpr * E)8563 bool VisitCXXThisExpr(const CXXThisExpr *E) {
8564 // Can't look at 'this' when checking a potential constant expression.
8565 if (Info.checkingPotentialConstantExpression())
8566 return false;
8567 if (!Info.CurrentCall->This) {
8568 if (Info.getLangOpts().CPlusPlus11)
8569 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8570 else
8571 Info.FFDiag(E);
8572 return false;
8573 }
8574 Result = *Info.CurrentCall->This;
8575 // If we are inside a lambda's call operator, the 'this' expression refers
8576 // to the enclosing '*this' object (either by value or reference) which is
8577 // either copied into the closure object's field that represents the '*this'
8578 // or refers to '*this'.
8579 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8580 // Ensure we actually have captured 'this'. (an error will have
8581 // been previously reported if not).
8582 if (!Info.CurrentCall->LambdaThisCaptureField)
8583 return false;
8584
8585 // Update 'Result' to refer to the data member/field of the closure object
8586 // that represents the '*this' capture.
8587 if (!HandleLValueMember(Info, E, Result,
8588 Info.CurrentCall->LambdaThisCaptureField))
8589 return false;
8590 // If we captured '*this' by reference, replace the field with its referent.
8591 if (Info.CurrentCall->LambdaThisCaptureField->getType()
8592 ->isPointerType()) {
8593 APValue RVal;
8594 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8595 RVal))
8596 return false;
8597
8598 Result.setFrom(Info.Ctx, RVal);
8599 }
8600 }
8601 return true;
8602 }
8603
8604 bool VisitCXXNewExpr(const CXXNewExpr *E);
8605
VisitSourceLocExpr(const SourceLocExpr * E)8606 bool VisitSourceLocExpr(const SourceLocExpr *E) {
8607 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8608 APValue LValResult = E->EvaluateInContext(
8609 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8610 Result.setFrom(Info.Ctx, LValResult);
8611 return true;
8612 }
8613
8614 // FIXME: Missing: @protocol, @selector
8615 };
8616 } // end anonymous namespace
8617
EvaluatePointer(const Expr * E,LValue & Result,EvalInfo & Info,bool InvalidBaseOK)8618 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8619 bool InvalidBaseOK) {
8620 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8621 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8622 }
8623
VisitBinaryOperator(const BinaryOperator * E)8624 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8625 if (E->getOpcode() != BO_Add &&
8626 E->getOpcode() != BO_Sub)
8627 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8628
8629 const Expr *PExp = E->getLHS();
8630 const Expr *IExp = E->getRHS();
8631 if (IExp->getType()->isPointerType())
8632 std::swap(PExp, IExp);
8633
8634 bool EvalPtrOK = evaluatePointer(PExp, Result);
8635 if (!EvalPtrOK && !Info.noteFailure())
8636 return false;
8637
8638 llvm::APSInt Offset;
8639 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8640 return false;
8641
8642 if (E->getOpcode() == BO_Sub)
8643 negateAsSigned(Offset);
8644
8645 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8646 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8647 }
8648
VisitUnaryAddrOf(const UnaryOperator * E)8649 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8650 return evaluateLValue(E->getSubExpr(), Result);
8651 }
8652
VisitCastExpr(const CastExpr * E)8653 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8654 const Expr *SubExpr = E->getSubExpr();
8655
8656 switch (E->getCastKind()) {
8657 default:
8658 break;
8659 case CK_BitCast:
8660 case CK_CPointerToObjCPointerCast:
8661 case CK_BlockPointerToObjCPointerCast:
8662 case CK_AnyPointerToBlockPointerCast:
8663 case CK_AddressSpaceConversion:
8664 if (!Visit(SubExpr))
8665 return false;
8666 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8667 // permitted in constant expressions in C++11. Bitcasts from cv void* are
8668 // also static_casts, but we disallow them as a resolution to DR1312.
8669 if (!E->getType()->isVoidPointerType()) {
8670 if (!Result.InvalidBase && !Result.Designator.Invalid &&
8671 !Result.IsNullPtr &&
8672 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8673 E->getType()->getPointeeType()) &&
8674 Info.getStdAllocatorCaller("allocate")) {
8675 // Inside a call to std::allocator::allocate and friends, we permit
8676 // casting from void* back to cv1 T* for a pointer that points to a
8677 // cv2 T.
8678 } else {
8679 Result.Designator.setInvalid();
8680 if (SubExpr->getType()->isVoidPointerType())
8681 CCEDiag(E, diag::note_constexpr_invalid_cast)
8682 << 3 << SubExpr->getType();
8683 else
8684 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8685 }
8686 }
8687 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8688 ZeroInitialization(E);
8689 return true;
8690
8691 case CK_DerivedToBase:
8692 case CK_UncheckedDerivedToBase:
8693 if (!evaluatePointer(E->getSubExpr(), Result))
8694 return false;
8695 if (!Result.Base && Result.Offset.isZero())
8696 return true;
8697
8698 // Now figure out the necessary offset to add to the base LV to get from
8699 // the derived class to the base class.
8700 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8701 castAs<PointerType>()->getPointeeType(),
8702 Result);
8703
8704 case CK_BaseToDerived:
8705 if (!Visit(E->getSubExpr()))
8706 return false;
8707 if (!Result.Base && Result.Offset.isZero())
8708 return true;
8709 return HandleBaseToDerivedCast(Info, E, Result);
8710
8711 case CK_Dynamic:
8712 if (!Visit(E->getSubExpr()))
8713 return false;
8714 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8715
8716 case CK_NullToPointer:
8717 VisitIgnoredValue(E->getSubExpr());
8718 return ZeroInitialization(E);
8719
8720 case CK_IntegralToPointer: {
8721 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8722
8723 APValue Value;
8724 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8725 break;
8726
8727 if (Value.isInt()) {
8728 unsigned Size = Info.Ctx.getTypeSize(E->getType());
8729 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8730 Result.Base = (Expr*)nullptr;
8731 Result.InvalidBase = false;
8732 Result.Offset = CharUnits::fromQuantity(N);
8733 Result.Designator.setInvalid();
8734 Result.IsNullPtr = false;
8735 return true;
8736 } else {
8737 // Cast is of an lvalue, no need to change value.
8738 Result.setFrom(Info.Ctx, Value);
8739 return true;
8740 }
8741 }
8742
8743 case CK_ArrayToPointerDecay: {
8744 if (SubExpr->isGLValue()) {
8745 if (!evaluateLValue(SubExpr, Result))
8746 return false;
8747 } else {
8748 APValue &Value = Info.CurrentCall->createTemporary(
8749 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8750 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8751 return false;
8752 }
8753 // The result is a pointer to the first element of the array.
8754 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8755 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8756 Result.addArray(Info, E, CAT);
8757 else
8758 Result.addUnsizedArray(Info, E, AT->getElementType());
8759 return true;
8760 }
8761
8762 case CK_FunctionToPointerDecay:
8763 return evaluateLValue(SubExpr, Result);
8764
8765 case CK_LValueToRValue: {
8766 LValue LVal;
8767 if (!evaluateLValue(E->getSubExpr(), LVal))
8768 return false;
8769
8770 APValue RVal;
8771 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8772 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8773 LVal, RVal))
8774 return InvalidBaseOK &&
8775 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8776 return Success(RVal, E);
8777 }
8778 }
8779
8780 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8781 }
8782
GetAlignOfType(EvalInfo & Info,QualType T,UnaryExprOrTypeTrait ExprKind)8783 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8784 UnaryExprOrTypeTrait ExprKind) {
8785 // C++ [expr.alignof]p3:
8786 // When alignof is applied to a reference type, the result is the
8787 // alignment of the referenced type.
8788 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8789 T = Ref->getPointeeType();
8790
8791 if (T.getQualifiers().hasUnaligned())
8792 return CharUnits::One();
8793
8794 const bool AlignOfReturnsPreferred =
8795 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8796
8797 // __alignof is defined to return the preferred alignment.
8798 // Before 8, clang returned the preferred alignment for alignof and _Alignof
8799 // as well.
8800 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8801 return Info.Ctx.toCharUnitsFromBits(
8802 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8803 // alignof and _Alignof are defined to return the ABI alignment.
8804 else if (ExprKind == UETT_AlignOf)
8805 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8806 else
8807 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8808 }
8809
GetAlignOfExpr(EvalInfo & Info,const Expr * E,UnaryExprOrTypeTrait ExprKind)8810 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8811 UnaryExprOrTypeTrait ExprKind) {
8812 E = E->IgnoreParens();
8813
8814 // The kinds of expressions that we have special-case logic here for
8815 // should be kept up to date with the special checks for those
8816 // expressions in Sema.
8817
8818 // alignof decl is always accepted, even if it doesn't make sense: we default
8819 // to 1 in those cases.
8820 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8821 return Info.Ctx.getDeclAlign(DRE->getDecl(),
8822 /*RefAsPointee*/true);
8823
8824 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8825 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8826 /*RefAsPointee*/true);
8827
8828 return GetAlignOfType(Info, E->getType(), ExprKind);
8829 }
8830
getBaseAlignment(EvalInfo & Info,const LValue & Value)8831 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8832 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8833 return Info.Ctx.getDeclAlign(VD);
8834 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8835 return GetAlignOfExpr(Info, E, UETT_AlignOf);
8836 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8837 }
8838
8839 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8840 /// __builtin_is_aligned and __builtin_assume_aligned.
getAlignmentArgument(const Expr * E,QualType ForType,EvalInfo & Info,APSInt & Alignment)8841 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8842 EvalInfo &Info, APSInt &Alignment) {
8843 if (!EvaluateInteger(E, Alignment, Info))
8844 return false;
8845 if (Alignment < 0 || !Alignment.isPowerOf2()) {
8846 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8847 return false;
8848 }
8849 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8850 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8851 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8852 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8853 << MaxValue << ForType << Alignment;
8854 return false;
8855 }
8856 // Ensure both alignment and source value have the same bit width so that we
8857 // don't assert when computing the resulting value.
8858 APSInt ExtAlignment =
8859 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8860 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8861 "Alignment should not be changed by ext/trunc");
8862 Alignment = ExtAlignment;
8863 assert(Alignment.getBitWidth() == SrcWidth);
8864 return true;
8865 }
8866
8867 // To be clear: this happily visits unsupported builtins. Better name welcomed.
visitNonBuiltinCallExpr(const CallExpr * E)8868 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8869 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8870 return true;
8871
8872 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8873 return false;
8874
8875 Result.setInvalid(E);
8876 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8877 Result.addUnsizedArray(Info, E, PointeeTy);
8878 return true;
8879 }
8880
VisitCallExpr(const CallExpr * E)8881 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8882 if (IsStringLiteralCall(E))
8883 return Success(E);
8884
8885 if (unsigned BuiltinOp = E->getBuiltinCallee())
8886 return VisitBuiltinCallExpr(E, BuiltinOp);
8887
8888 return visitNonBuiltinCallExpr(E);
8889 }
8890
8891 // Determine if T is a character type for which we guarantee that
8892 // sizeof(T) == 1.
isOneByteCharacterType(QualType T)8893 static bool isOneByteCharacterType(QualType T) {
8894 return T->isCharType() || T->isChar8Type();
8895 }
8896
VisitBuiltinCallExpr(const CallExpr * E,unsigned BuiltinOp)8897 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8898 unsigned BuiltinOp) {
8899 switch (BuiltinOp) {
8900 case Builtin::BI__builtin_addressof:
8901 return evaluateLValue(E->getArg(0), Result);
8902 case Builtin::BI__builtin_assume_aligned: {
8903 // We need to be very careful here because: if the pointer does not have the
8904 // asserted alignment, then the behavior is undefined, and undefined
8905 // behavior is non-constant.
8906 if (!evaluatePointer(E->getArg(0), Result))
8907 return false;
8908
8909 LValue OffsetResult(Result);
8910 APSInt Alignment;
8911 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8912 Alignment))
8913 return false;
8914 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8915
8916 if (E->getNumArgs() > 2) {
8917 APSInt Offset;
8918 if (!EvaluateInteger(E->getArg(2), Offset, Info))
8919 return false;
8920
8921 int64_t AdditionalOffset = -Offset.getZExtValue();
8922 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8923 }
8924
8925 // If there is a base object, then it must have the correct alignment.
8926 if (OffsetResult.Base) {
8927 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
8928
8929 if (BaseAlignment < Align) {
8930 Result.Designator.setInvalid();
8931 // FIXME: Add support to Diagnostic for long / long long.
8932 CCEDiag(E->getArg(0),
8933 diag::note_constexpr_baa_insufficient_alignment) << 0
8934 << (unsigned)BaseAlignment.getQuantity()
8935 << (unsigned)Align.getQuantity();
8936 return false;
8937 }
8938 }
8939
8940 // The offset must also have the correct alignment.
8941 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
8942 Result.Designator.setInvalid();
8943
8944 (OffsetResult.Base
8945 ? CCEDiag(E->getArg(0),
8946 diag::note_constexpr_baa_insufficient_alignment) << 1
8947 : CCEDiag(E->getArg(0),
8948 diag::note_constexpr_baa_value_insufficient_alignment))
8949 << (int)OffsetResult.Offset.getQuantity()
8950 << (unsigned)Align.getQuantity();
8951 return false;
8952 }
8953
8954 return true;
8955 }
8956 case Builtin::BI__builtin_align_up:
8957 case Builtin::BI__builtin_align_down: {
8958 if (!evaluatePointer(E->getArg(0), Result))
8959 return false;
8960 APSInt Alignment;
8961 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8962 Alignment))
8963 return false;
8964 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
8965 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
8966 // For align_up/align_down, we can return the same value if the alignment
8967 // is known to be greater or equal to the requested value.
8968 if (PtrAlign.getQuantity() >= Alignment)
8969 return true;
8970
8971 // The alignment could be greater than the minimum at run-time, so we cannot
8972 // infer much about the resulting pointer value. One case is possible:
8973 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
8974 // can infer the correct index if the requested alignment is smaller than
8975 // the base alignment so we can perform the computation on the offset.
8976 if (BaseAlignment.getQuantity() >= Alignment) {
8977 assert(Alignment.getBitWidth() <= 64 &&
8978 "Cannot handle > 64-bit address-space");
8979 uint64_t Alignment64 = Alignment.getZExtValue();
8980 CharUnits NewOffset = CharUnits::fromQuantity(
8981 BuiltinOp == Builtin::BI__builtin_align_down
8982 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
8983 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
8984 Result.adjustOffset(NewOffset - Result.Offset);
8985 // TODO: diagnose out-of-bounds values/only allow for arrays?
8986 return true;
8987 }
8988 // Otherwise, we cannot constant-evaluate the result.
8989 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
8990 << Alignment;
8991 return false;
8992 }
8993 case Builtin::BI__builtin_operator_new:
8994 return HandleOperatorNewCall(Info, E, Result);
8995 case Builtin::BI__builtin_launder:
8996 return evaluatePointer(E->getArg(0), Result);
8997 case Builtin::BIstrchr:
8998 case Builtin::BIwcschr:
8999 case Builtin::BImemchr:
9000 case Builtin::BIwmemchr:
9001 if (Info.getLangOpts().CPlusPlus11)
9002 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9003 << /*isConstexpr*/0 << /*isConstructor*/0
9004 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9005 else
9006 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9007 LLVM_FALLTHROUGH;
9008 case Builtin::BI__builtin_strchr:
9009 case Builtin::BI__builtin_wcschr:
9010 case Builtin::BI__builtin_memchr:
9011 case Builtin::BI__builtin_char_memchr:
9012 case Builtin::BI__builtin_wmemchr: {
9013 if (!Visit(E->getArg(0)))
9014 return false;
9015 APSInt Desired;
9016 if (!EvaluateInteger(E->getArg(1), Desired, Info))
9017 return false;
9018 uint64_t MaxLength = uint64_t(-1);
9019 if (BuiltinOp != Builtin::BIstrchr &&
9020 BuiltinOp != Builtin::BIwcschr &&
9021 BuiltinOp != Builtin::BI__builtin_strchr &&
9022 BuiltinOp != Builtin::BI__builtin_wcschr) {
9023 APSInt N;
9024 if (!EvaluateInteger(E->getArg(2), N, Info))
9025 return false;
9026 MaxLength = N.getExtValue();
9027 }
9028 // We cannot find the value if there are no candidates to match against.
9029 if (MaxLength == 0u)
9030 return ZeroInitialization(E);
9031 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9032 Result.Designator.Invalid)
9033 return false;
9034 QualType CharTy = Result.Designator.getType(Info.Ctx);
9035 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9036 BuiltinOp == Builtin::BI__builtin_memchr;
9037 assert(IsRawByte ||
9038 Info.Ctx.hasSameUnqualifiedType(
9039 CharTy, E->getArg(0)->getType()->getPointeeType()));
9040 // Pointers to const void may point to objects of incomplete type.
9041 if (IsRawByte && CharTy->isIncompleteType()) {
9042 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9043 return false;
9044 }
9045 // Give up on byte-oriented matching against multibyte elements.
9046 // FIXME: We can compare the bytes in the correct order.
9047 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9048 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9049 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9050 << CharTy;
9051 return false;
9052 }
9053 // Figure out what value we're actually looking for (after converting to
9054 // the corresponding unsigned type if necessary).
9055 uint64_t DesiredVal;
9056 bool StopAtNull = false;
9057 switch (BuiltinOp) {
9058 case Builtin::BIstrchr:
9059 case Builtin::BI__builtin_strchr:
9060 // strchr compares directly to the passed integer, and therefore
9061 // always fails if given an int that is not a char.
9062 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9063 E->getArg(1)->getType(),
9064 Desired),
9065 Desired))
9066 return ZeroInitialization(E);
9067 StopAtNull = true;
9068 LLVM_FALLTHROUGH;
9069 case Builtin::BImemchr:
9070 case Builtin::BI__builtin_memchr:
9071 case Builtin::BI__builtin_char_memchr:
9072 // memchr compares by converting both sides to unsigned char. That's also
9073 // correct for strchr if we get this far (to cope with plain char being
9074 // unsigned in the strchr case).
9075 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9076 break;
9077
9078 case Builtin::BIwcschr:
9079 case Builtin::BI__builtin_wcschr:
9080 StopAtNull = true;
9081 LLVM_FALLTHROUGH;
9082 case Builtin::BIwmemchr:
9083 case Builtin::BI__builtin_wmemchr:
9084 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9085 DesiredVal = Desired.getZExtValue();
9086 break;
9087 }
9088
9089 for (; MaxLength; --MaxLength) {
9090 APValue Char;
9091 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9092 !Char.isInt())
9093 return false;
9094 if (Char.getInt().getZExtValue() == DesiredVal)
9095 return true;
9096 if (StopAtNull && !Char.getInt())
9097 break;
9098 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9099 return false;
9100 }
9101 // Not found: return nullptr.
9102 return ZeroInitialization(E);
9103 }
9104
9105 case Builtin::BImemcpy:
9106 case Builtin::BImemmove:
9107 case Builtin::BIwmemcpy:
9108 case Builtin::BIwmemmove:
9109 if (Info.getLangOpts().CPlusPlus11)
9110 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9111 << /*isConstexpr*/0 << /*isConstructor*/0
9112 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9113 else
9114 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9115 LLVM_FALLTHROUGH;
9116 case Builtin::BI__builtin_memcpy:
9117 case Builtin::BI__builtin_memmove:
9118 case Builtin::BI__builtin_wmemcpy:
9119 case Builtin::BI__builtin_wmemmove: {
9120 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9121 BuiltinOp == Builtin::BIwmemmove ||
9122 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9123 BuiltinOp == Builtin::BI__builtin_wmemmove;
9124 bool Move = BuiltinOp == Builtin::BImemmove ||
9125 BuiltinOp == Builtin::BIwmemmove ||
9126 BuiltinOp == Builtin::BI__builtin_memmove ||
9127 BuiltinOp == Builtin::BI__builtin_wmemmove;
9128
9129 // The result of mem* is the first argument.
9130 if (!Visit(E->getArg(0)))
9131 return false;
9132 LValue Dest = Result;
9133
9134 LValue Src;
9135 if (!EvaluatePointer(E->getArg(1), Src, Info))
9136 return false;
9137
9138 APSInt N;
9139 if (!EvaluateInteger(E->getArg(2), N, Info))
9140 return false;
9141 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9142
9143 // If the size is zero, we treat this as always being a valid no-op.
9144 // (Even if one of the src and dest pointers is null.)
9145 if (!N)
9146 return true;
9147
9148 // Otherwise, if either of the operands is null, we can't proceed. Don't
9149 // try to determine the type of the copied objects, because there aren't
9150 // any.
9151 if (!Src.Base || !Dest.Base) {
9152 APValue Val;
9153 (!Src.Base ? Src : Dest).moveInto(Val);
9154 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9155 << Move << WChar << !!Src.Base
9156 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9157 return false;
9158 }
9159 if (Src.Designator.Invalid || Dest.Designator.Invalid)
9160 return false;
9161
9162 // We require that Src and Dest are both pointers to arrays of
9163 // trivially-copyable type. (For the wide version, the designator will be
9164 // invalid if the designated object is not a wchar_t.)
9165 QualType T = Dest.Designator.getType(Info.Ctx);
9166 QualType SrcT = Src.Designator.getType(Info.Ctx);
9167 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9168 // FIXME: Consider using our bit_cast implementation to support this.
9169 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9170 return false;
9171 }
9172 if (T->isIncompleteType()) {
9173 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9174 return false;
9175 }
9176 if (!T.isTriviallyCopyableType(Info.Ctx)) {
9177 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9178 return false;
9179 }
9180
9181 // Figure out how many T's we're copying.
9182 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9183 if (!WChar) {
9184 uint64_t Remainder;
9185 llvm::APInt OrigN = N;
9186 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9187 if (Remainder) {
9188 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9189 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
9190 << (unsigned)TSize;
9191 return false;
9192 }
9193 }
9194
9195 // Check that the copying will remain within the arrays, just so that we
9196 // can give a more meaningful diagnostic. This implicitly also checks that
9197 // N fits into 64 bits.
9198 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9199 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9200 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9201 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9202 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9203 << N.toString(10, /*Signed*/false);
9204 return false;
9205 }
9206 uint64_t NElems = N.getZExtValue();
9207 uint64_t NBytes = NElems * TSize;
9208
9209 // Check for overlap.
9210 int Direction = 1;
9211 if (HasSameBase(Src, Dest)) {
9212 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9213 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9214 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9215 // Dest is inside the source region.
9216 if (!Move) {
9217 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9218 return false;
9219 }
9220 // For memmove and friends, copy backwards.
9221 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9222 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9223 return false;
9224 Direction = -1;
9225 } else if (!Move && SrcOffset >= DestOffset &&
9226 SrcOffset - DestOffset < NBytes) {
9227 // Src is inside the destination region for memcpy: invalid.
9228 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9229 return false;
9230 }
9231 }
9232
9233 while (true) {
9234 APValue Val;
9235 // FIXME: Set WantObjectRepresentation to true if we're copying a
9236 // char-like type?
9237 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9238 !handleAssignment(Info, E, Dest, T, Val))
9239 return false;
9240 // Do not iterate past the last element; if we're copying backwards, that
9241 // might take us off the start of the array.
9242 if (--NElems == 0)
9243 return true;
9244 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9245 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9246 return false;
9247 }
9248 }
9249
9250 default:
9251 break;
9252 }
9253
9254 return visitNonBuiltinCallExpr(E);
9255 }
9256
9257 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9258 APValue &Result, const InitListExpr *ILE,
9259 QualType AllocType);
9260 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9261 APValue &Result,
9262 const CXXConstructExpr *CCE,
9263 QualType AllocType);
9264
VisitCXXNewExpr(const CXXNewExpr * E)9265 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9266 if (!Info.getLangOpts().CPlusPlus20)
9267 Info.CCEDiag(E, diag::note_constexpr_new);
9268
9269 // We cannot speculatively evaluate a delete expression.
9270 if (Info.SpeculativeEvaluationDepth)
9271 return false;
9272
9273 FunctionDecl *OperatorNew = E->getOperatorNew();
9274
9275 bool IsNothrow = false;
9276 bool IsPlacement = false;
9277 if (OperatorNew->isReservedGlobalPlacementOperator() &&
9278 Info.CurrentCall->isStdFunction() && !E->isArray()) {
9279 // FIXME Support array placement new.
9280 assert(E->getNumPlacementArgs() == 1);
9281 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9282 return false;
9283 if (Result.Designator.Invalid)
9284 return false;
9285 IsPlacement = true;
9286 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9287 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9288 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9289 return false;
9290 } else if (E->getNumPlacementArgs()) {
9291 // The only new-placement list we support is of the form (std::nothrow).
9292 //
9293 // FIXME: There is no restriction on this, but it's not clear that any
9294 // other form makes any sense. We get here for cases such as:
9295 //
9296 // new (std::align_val_t{N}) X(int)
9297 //
9298 // (which should presumably be valid only if N is a multiple of
9299 // alignof(int), and in any case can't be deallocated unless N is
9300 // alignof(X) and X has new-extended alignment).
9301 if (E->getNumPlacementArgs() != 1 ||
9302 !E->getPlacementArg(0)->getType()->isNothrowT())
9303 return Error(E, diag::note_constexpr_new_placement);
9304
9305 LValue Nothrow;
9306 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9307 return false;
9308 IsNothrow = true;
9309 }
9310
9311 const Expr *Init = E->getInitializer();
9312 const InitListExpr *ResizedArrayILE = nullptr;
9313 const CXXConstructExpr *ResizedArrayCCE = nullptr;
9314 bool ValueInit = false;
9315
9316 QualType AllocType = E->getAllocatedType();
9317 if (Optional<const Expr*> ArraySize = E->getArraySize()) {
9318 const Expr *Stripped = *ArraySize;
9319 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9320 Stripped = ICE->getSubExpr())
9321 if (ICE->getCastKind() != CK_NoOp &&
9322 ICE->getCastKind() != CK_IntegralCast)
9323 break;
9324
9325 llvm::APSInt ArrayBound;
9326 if (!EvaluateInteger(Stripped, ArrayBound, Info))
9327 return false;
9328
9329 // C++ [expr.new]p9:
9330 // The expression is erroneous if:
9331 // -- [...] its value before converting to size_t [or] applying the
9332 // second standard conversion sequence is less than zero
9333 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9334 if (IsNothrow)
9335 return ZeroInitialization(E);
9336
9337 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9338 << ArrayBound << (*ArraySize)->getSourceRange();
9339 return false;
9340 }
9341
9342 // -- its value is such that the size of the allocated object would
9343 // exceed the implementation-defined limit
9344 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9345 ArrayBound) >
9346 ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9347 if (IsNothrow)
9348 return ZeroInitialization(E);
9349
9350 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9351 << ArrayBound << (*ArraySize)->getSourceRange();
9352 return false;
9353 }
9354
9355 // -- the new-initializer is a braced-init-list and the number of
9356 // array elements for which initializers are provided [...]
9357 // exceeds the number of elements to initialize
9358 if (!Init) {
9359 // No initialization is performed.
9360 } else if (isa<CXXScalarValueInitExpr>(Init) ||
9361 isa<ImplicitValueInitExpr>(Init)) {
9362 ValueInit = true;
9363 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9364 ResizedArrayCCE = CCE;
9365 } else {
9366 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9367 assert(CAT && "unexpected type for array initializer");
9368
9369 unsigned Bits =
9370 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9371 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9372 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9373 if (InitBound.ugt(AllocBound)) {
9374 if (IsNothrow)
9375 return ZeroInitialization(E);
9376
9377 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9378 << AllocBound.toString(10, /*Signed=*/false)
9379 << InitBound.toString(10, /*Signed=*/false)
9380 << (*ArraySize)->getSourceRange();
9381 return false;
9382 }
9383
9384 // If the sizes differ, we must have an initializer list, and we need
9385 // special handling for this case when we initialize.
9386 if (InitBound != AllocBound)
9387 ResizedArrayILE = cast<InitListExpr>(Init);
9388 }
9389
9390 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9391 ArrayType::Normal, 0);
9392 } else {
9393 assert(!AllocType->isArrayType() &&
9394 "array allocation with non-array new");
9395 }
9396
9397 APValue *Val;
9398 if (IsPlacement) {
9399 AccessKinds AK = AK_Construct;
9400 struct FindObjectHandler {
9401 EvalInfo &Info;
9402 const Expr *E;
9403 QualType AllocType;
9404 const AccessKinds AccessKind;
9405 APValue *Value;
9406
9407 typedef bool result_type;
9408 bool failed() { return false; }
9409 bool found(APValue &Subobj, QualType SubobjType) {
9410 // FIXME: Reject the cases where [basic.life]p8 would not permit the
9411 // old name of the object to be used to name the new object.
9412 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9413 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9414 SubobjType << AllocType;
9415 return false;
9416 }
9417 Value = &Subobj;
9418 return true;
9419 }
9420 bool found(APSInt &Value, QualType SubobjType) {
9421 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9422 return false;
9423 }
9424 bool found(APFloat &Value, QualType SubobjType) {
9425 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9426 return false;
9427 }
9428 } Handler = {Info, E, AllocType, AK, nullptr};
9429
9430 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9431 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9432 return false;
9433
9434 Val = Handler.Value;
9435
9436 // [basic.life]p1:
9437 // The lifetime of an object o of type T ends when [...] the storage
9438 // which the object occupies is [...] reused by an object that is not
9439 // nested within o (6.6.2).
9440 *Val = APValue();
9441 } else {
9442 // Perform the allocation and obtain a pointer to the resulting object.
9443 Val = Info.createHeapAlloc(E, AllocType, Result);
9444 if (!Val)
9445 return false;
9446 }
9447
9448 if (ValueInit) {
9449 ImplicitValueInitExpr VIE(AllocType);
9450 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9451 return false;
9452 } else if (ResizedArrayILE) {
9453 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9454 AllocType))
9455 return false;
9456 } else if (ResizedArrayCCE) {
9457 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9458 AllocType))
9459 return false;
9460 } else if (Init) {
9461 if (!EvaluateInPlace(*Val, Info, Result, Init))
9462 return false;
9463 } else if (!getDefaultInitValue(AllocType, *Val)) {
9464 return false;
9465 }
9466
9467 // Array new returns a pointer to the first element, not a pointer to the
9468 // array.
9469 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9470 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9471
9472 return true;
9473 }
9474 //===----------------------------------------------------------------------===//
9475 // Member Pointer Evaluation
9476 //===----------------------------------------------------------------------===//
9477
9478 namespace {
9479 class MemberPointerExprEvaluator
9480 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9481 MemberPtr &Result;
9482
Success(const ValueDecl * D)9483 bool Success(const ValueDecl *D) {
9484 Result = MemberPtr(D);
9485 return true;
9486 }
9487 public:
9488
MemberPointerExprEvaluator(EvalInfo & Info,MemberPtr & Result)9489 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9490 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9491
Success(const APValue & V,const Expr * E)9492 bool Success(const APValue &V, const Expr *E) {
9493 Result.setFrom(V);
9494 return true;
9495 }
ZeroInitialization(const Expr * E)9496 bool ZeroInitialization(const Expr *E) {
9497 return Success((const ValueDecl*)nullptr);
9498 }
9499
9500 bool VisitCastExpr(const CastExpr *E);
9501 bool VisitUnaryAddrOf(const UnaryOperator *E);
9502 };
9503 } // end anonymous namespace
9504
EvaluateMemberPointer(const Expr * E,MemberPtr & Result,EvalInfo & Info)9505 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9506 EvalInfo &Info) {
9507 assert(E->isRValue() && E->getType()->isMemberPointerType());
9508 return MemberPointerExprEvaluator(Info, Result).Visit(E);
9509 }
9510
VisitCastExpr(const CastExpr * E)9511 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9512 switch (E->getCastKind()) {
9513 default:
9514 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9515
9516 case CK_NullToMemberPointer:
9517 VisitIgnoredValue(E->getSubExpr());
9518 return ZeroInitialization(E);
9519
9520 case CK_BaseToDerivedMemberPointer: {
9521 if (!Visit(E->getSubExpr()))
9522 return false;
9523 if (E->path_empty())
9524 return true;
9525 // Base-to-derived member pointer casts store the path in derived-to-base
9526 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9527 // the wrong end of the derived->base arc, so stagger the path by one class.
9528 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9529 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9530 PathI != PathE; ++PathI) {
9531 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9532 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9533 if (!Result.castToDerived(Derived))
9534 return Error(E);
9535 }
9536 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9537 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9538 return Error(E);
9539 return true;
9540 }
9541
9542 case CK_DerivedToBaseMemberPointer:
9543 if (!Visit(E->getSubExpr()))
9544 return false;
9545 for (CastExpr::path_const_iterator PathI = E->path_begin(),
9546 PathE = E->path_end(); PathI != PathE; ++PathI) {
9547 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9548 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9549 if (!Result.castToBase(Base))
9550 return Error(E);
9551 }
9552 return true;
9553 }
9554 }
9555
VisitUnaryAddrOf(const UnaryOperator * E)9556 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9557 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9558 // member can be formed.
9559 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9560 }
9561
9562 //===----------------------------------------------------------------------===//
9563 // Record Evaluation
9564 //===----------------------------------------------------------------------===//
9565
9566 namespace {
9567 class RecordExprEvaluator
9568 : public ExprEvaluatorBase<RecordExprEvaluator> {
9569 const LValue &This;
9570 APValue &Result;
9571 public:
9572
RecordExprEvaluator(EvalInfo & info,const LValue & This,APValue & Result)9573 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9574 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9575
Success(const APValue & V,const Expr * E)9576 bool Success(const APValue &V, const Expr *E) {
9577 Result = V;
9578 return true;
9579 }
ZeroInitialization(const Expr * E)9580 bool ZeroInitialization(const Expr *E) {
9581 return ZeroInitialization(E, E->getType());
9582 }
9583 bool ZeroInitialization(const Expr *E, QualType T);
9584
VisitCallExpr(const CallExpr * E)9585 bool VisitCallExpr(const CallExpr *E) {
9586 return handleCallExpr(E, Result, &This);
9587 }
9588 bool VisitCastExpr(const CastExpr *E);
9589 bool VisitInitListExpr(const InitListExpr *E);
VisitCXXConstructExpr(const CXXConstructExpr * E)9590 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9591 return VisitCXXConstructExpr(E, E->getType());
9592 }
9593 bool VisitLambdaExpr(const LambdaExpr *E);
9594 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9595 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9596 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9597 bool VisitBinCmp(const BinaryOperator *E);
9598 };
9599 }
9600
9601 /// Perform zero-initialization on an object of non-union class type.
9602 /// C++11 [dcl.init]p5:
9603 /// To zero-initialize an object or reference of type T means:
9604 /// [...]
9605 /// -- if T is a (possibly cv-qualified) non-union class type,
9606 /// each non-static data member and each base-class subobject is
9607 /// zero-initialized
HandleClassZeroInitialization(EvalInfo & Info,const Expr * E,const RecordDecl * RD,const LValue & This,APValue & Result)9608 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9609 const RecordDecl *RD,
9610 const LValue &This, APValue &Result) {
9611 assert(!RD->isUnion() && "Expected non-union class type");
9612 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9613 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9614 std::distance(RD->field_begin(), RD->field_end()));
9615
9616 if (RD->isInvalidDecl()) return false;
9617 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9618
9619 if (CD) {
9620 unsigned Index = 0;
9621 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9622 End = CD->bases_end(); I != End; ++I, ++Index) {
9623 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9624 LValue Subobject = This;
9625 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9626 return false;
9627 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9628 Result.getStructBase(Index)))
9629 return false;
9630 }
9631 }
9632
9633 for (const auto *I : RD->fields()) {
9634 // -- if T is a reference type, no initialization is performed.
9635 if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9636 continue;
9637
9638 LValue Subobject = This;
9639 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9640 return false;
9641
9642 ImplicitValueInitExpr VIE(I->getType());
9643 if (!EvaluateInPlace(
9644 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9645 return false;
9646 }
9647
9648 return true;
9649 }
9650
ZeroInitialization(const Expr * E,QualType T)9651 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9652 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9653 if (RD->isInvalidDecl()) return false;
9654 if (RD->isUnion()) {
9655 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9656 // object's first non-static named data member is zero-initialized
9657 RecordDecl::field_iterator I = RD->field_begin();
9658 while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9659 ++I;
9660 if (I == RD->field_end()) {
9661 Result = APValue((const FieldDecl*)nullptr);
9662 return true;
9663 }
9664
9665 LValue Subobject = This;
9666 if (!HandleLValueMember(Info, E, Subobject, *I))
9667 return false;
9668 Result = APValue(*I);
9669 ImplicitValueInitExpr VIE(I->getType());
9670 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9671 }
9672
9673 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9674 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9675 return false;
9676 }
9677
9678 return HandleClassZeroInitialization(Info, E, RD, This, Result);
9679 }
9680
VisitCastExpr(const CastExpr * E)9681 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9682 switch (E->getCastKind()) {
9683 default:
9684 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9685
9686 case CK_ConstructorConversion:
9687 return Visit(E->getSubExpr());
9688
9689 case CK_DerivedToBase:
9690 case CK_UncheckedDerivedToBase: {
9691 APValue DerivedObject;
9692 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9693 return false;
9694 if (!DerivedObject.isStruct())
9695 return Error(E->getSubExpr());
9696
9697 // Derived-to-base rvalue conversion: just slice off the derived part.
9698 APValue *Value = &DerivedObject;
9699 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9700 for (CastExpr::path_const_iterator PathI = E->path_begin(),
9701 PathE = E->path_end(); PathI != PathE; ++PathI) {
9702 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9703 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9704 Value = &Value->getStructBase(getBaseIndex(RD, Base));
9705 RD = Base;
9706 }
9707 Result = *Value;
9708 return true;
9709 }
9710 }
9711 }
9712
VisitInitListExpr(const InitListExpr * E)9713 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9714 if (E->isTransparent())
9715 return Visit(E->getInit(0));
9716
9717 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9718 if (RD->isInvalidDecl()) return false;
9719 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9720 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9721
9722 EvalInfo::EvaluatingConstructorRAII EvalObj(
9723 Info,
9724 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9725 CXXRD && CXXRD->getNumBases());
9726
9727 if (RD->isUnion()) {
9728 const FieldDecl *Field = E->getInitializedFieldInUnion();
9729 Result = APValue(Field);
9730 if (!Field)
9731 return true;
9732
9733 // If the initializer list for a union does not contain any elements, the
9734 // first element of the union is value-initialized.
9735 // FIXME: The element should be initialized from an initializer list.
9736 // Is this difference ever observable for initializer lists which
9737 // we don't build?
9738 ImplicitValueInitExpr VIE(Field->getType());
9739 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9740
9741 LValue Subobject = This;
9742 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9743 return false;
9744
9745 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9746 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9747 isa<CXXDefaultInitExpr>(InitExpr));
9748
9749 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
9750 }
9751
9752 if (!Result.hasValue())
9753 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9754 std::distance(RD->field_begin(), RD->field_end()));
9755 unsigned ElementNo = 0;
9756 bool Success = true;
9757
9758 // Initialize base classes.
9759 if (CXXRD && CXXRD->getNumBases()) {
9760 for (const auto &Base : CXXRD->bases()) {
9761 assert(ElementNo < E->getNumInits() && "missing init for base class");
9762 const Expr *Init = E->getInit(ElementNo);
9763
9764 LValue Subobject = This;
9765 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9766 return false;
9767
9768 APValue &FieldVal = Result.getStructBase(ElementNo);
9769 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9770 if (!Info.noteFailure())
9771 return false;
9772 Success = false;
9773 }
9774 ++ElementNo;
9775 }
9776
9777 EvalObj.finishedConstructingBases();
9778 }
9779
9780 // Initialize members.
9781 for (const auto *Field : RD->fields()) {
9782 // Anonymous bit-fields are not considered members of the class for
9783 // purposes of aggregate initialization.
9784 if (Field->isUnnamedBitfield())
9785 continue;
9786
9787 LValue Subobject = This;
9788
9789 bool HaveInit = ElementNo < E->getNumInits();
9790
9791 // FIXME: Diagnostics here should point to the end of the initializer
9792 // list, not the start.
9793 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9794 Subobject, Field, &Layout))
9795 return false;
9796
9797 // Perform an implicit value-initialization for members beyond the end of
9798 // the initializer list.
9799 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9800 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9801
9802 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9803 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9804 isa<CXXDefaultInitExpr>(Init));
9805
9806 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9807 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9808 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9809 FieldVal, Field))) {
9810 if (!Info.noteFailure())
9811 return false;
9812 Success = false;
9813 }
9814 }
9815
9816 EvalObj.finishedConstructingFields();
9817
9818 return Success;
9819 }
9820
VisitCXXConstructExpr(const CXXConstructExpr * E,QualType T)9821 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9822 QualType T) {
9823 // Note that E's type is not necessarily the type of our class here; we might
9824 // be initializing an array element instead.
9825 const CXXConstructorDecl *FD = E->getConstructor();
9826 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9827
9828 bool ZeroInit = E->requiresZeroInitialization();
9829 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9830 // If we've already performed zero-initialization, we're already done.
9831 if (Result.hasValue())
9832 return true;
9833
9834 if (ZeroInit)
9835 return ZeroInitialization(E, T);
9836
9837 return getDefaultInitValue(T, Result);
9838 }
9839
9840 const FunctionDecl *Definition = nullptr;
9841 auto Body = FD->getBody(Definition);
9842
9843 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9844 return false;
9845
9846 // Avoid materializing a temporary for an elidable copy/move constructor.
9847 if (E->isElidable() && !ZeroInit)
9848 if (const MaterializeTemporaryExpr *ME
9849 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9850 return Visit(ME->getSubExpr());
9851
9852 if (ZeroInit && !ZeroInitialization(E, T))
9853 return false;
9854
9855 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9856 return HandleConstructorCall(E, This, Args,
9857 cast<CXXConstructorDecl>(Definition), Info,
9858 Result);
9859 }
9860
VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr * E)9861 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9862 const CXXInheritedCtorInitExpr *E) {
9863 if (!Info.CurrentCall) {
9864 assert(Info.checkingPotentialConstantExpression());
9865 return false;
9866 }
9867
9868 const CXXConstructorDecl *FD = E->getConstructor();
9869 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9870 return false;
9871
9872 const FunctionDecl *Definition = nullptr;
9873 auto Body = FD->getBody(Definition);
9874
9875 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9876 return false;
9877
9878 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9879 cast<CXXConstructorDecl>(Definition), Info,
9880 Result);
9881 }
9882
VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr * E)9883 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9884 const CXXStdInitializerListExpr *E) {
9885 const ConstantArrayType *ArrayType =
9886 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9887
9888 LValue Array;
9889 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9890 return false;
9891
9892 // Get a pointer to the first element of the array.
9893 Array.addArray(Info, E, ArrayType);
9894
9895 auto InvalidType = [&] {
9896 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
9897 << E->getType();
9898 return false;
9899 };
9900
9901 // FIXME: Perform the checks on the field types in SemaInit.
9902 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9903 RecordDecl::field_iterator Field = Record->field_begin();
9904 if (Field == Record->field_end())
9905 return InvalidType();
9906
9907 // Start pointer.
9908 if (!Field->getType()->isPointerType() ||
9909 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9910 ArrayType->getElementType()))
9911 return InvalidType();
9912
9913 // FIXME: What if the initializer_list type has base classes, etc?
9914 Result = APValue(APValue::UninitStruct(), 0, 2);
9915 Array.moveInto(Result.getStructField(0));
9916
9917 if (++Field == Record->field_end())
9918 return InvalidType();
9919
9920 if (Field->getType()->isPointerType() &&
9921 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9922 ArrayType->getElementType())) {
9923 // End pointer.
9924 if (!HandleLValueArrayAdjustment(Info, E, Array,
9925 ArrayType->getElementType(),
9926 ArrayType->getSize().getZExtValue()))
9927 return false;
9928 Array.moveInto(Result.getStructField(1));
9929 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9930 // Length.
9931 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9932 else
9933 return InvalidType();
9934
9935 if (++Field != Record->field_end())
9936 return InvalidType();
9937
9938 return true;
9939 }
9940
VisitLambdaExpr(const LambdaExpr * E)9941 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9942 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
9943 if (ClosureClass->isInvalidDecl())
9944 return false;
9945
9946 const size_t NumFields =
9947 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
9948
9949 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
9950 E->capture_init_end()) &&
9951 "The number of lambda capture initializers should equal the number of "
9952 "fields within the closure type");
9953
9954 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
9955 // Iterate through all the lambda's closure object's fields and initialize
9956 // them.
9957 auto *CaptureInitIt = E->capture_init_begin();
9958 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
9959 bool Success = true;
9960 for (const auto *Field : ClosureClass->fields()) {
9961 assert(CaptureInitIt != E->capture_init_end());
9962 // Get the initializer for this field
9963 Expr *const CurFieldInit = *CaptureInitIt++;
9964
9965 // If there is no initializer, either this is a VLA or an error has
9966 // occurred.
9967 if (!CurFieldInit)
9968 return Error(E);
9969
9970 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9971 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
9972 if (!Info.keepEvaluatingAfterFailure())
9973 return false;
9974 Success = false;
9975 }
9976 ++CaptureIt;
9977 }
9978 return Success;
9979 }
9980
EvaluateRecord(const Expr * E,const LValue & This,APValue & Result,EvalInfo & Info)9981 static bool EvaluateRecord(const Expr *E, const LValue &This,
9982 APValue &Result, EvalInfo &Info) {
9983 assert(E->isRValue() && E->getType()->isRecordType() &&
9984 "can't evaluate expression as a record rvalue");
9985 return RecordExprEvaluator(Info, This, Result).Visit(E);
9986 }
9987
9988 //===----------------------------------------------------------------------===//
9989 // Temporary Evaluation
9990 //
9991 // Temporaries are represented in the AST as rvalues, but generally behave like
9992 // lvalues. The full-object of which the temporary is a subobject is implicitly
9993 // materialized so that a reference can bind to it.
9994 //===----------------------------------------------------------------------===//
9995 namespace {
9996 class TemporaryExprEvaluator
9997 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
9998 public:
TemporaryExprEvaluator(EvalInfo & Info,LValue & Result)9999 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10000 LValueExprEvaluatorBaseTy(Info, Result, false) {}
10001
10002 /// Visit an expression which constructs the value of this temporary.
VisitConstructExpr(const Expr * E)10003 bool VisitConstructExpr(const Expr *E) {
10004 APValue &Value = Info.CurrentCall->createTemporary(
10005 E, E->getType(), ScopeKind::FullExpression, Result);
10006 return EvaluateInPlace(Value, Info, Result, E);
10007 }
10008
VisitCastExpr(const CastExpr * E)10009 bool VisitCastExpr(const CastExpr *E) {
10010 switch (E->getCastKind()) {
10011 default:
10012 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10013
10014 case CK_ConstructorConversion:
10015 return VisitConstructExpr(E->getSubExpr());
10016 }
10017 }
VisitInitListExpr(const InitListExpr * E)10018 bool VisitInitListExpr(const InitListExpr *E) {
10019 return VisitConstructExpr(E);
10020 }
VisitCXXConstructExpr(const CXXConstructExpr * E)10021 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10022 return VisitConstructExpr(E);
10023 }
VisitCallExpr(const CallExpr * E)10024 bool VisitCallExpr(const CallExpr *E) {
10025 return VisitConstructExpr(E);
10026 }
VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr * E)10027 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10028 return VisitConstructExpr(E);
10029 }
VisitLambdaExpr(const LambdaExpr * E)10030 bool VisitLambdaExpr(const LambdaExpr *E) {
10031 return VisitConstructExpr(E);
10032 }
10033 };
10034 } // end anonymous namespace
10035
10036 /// Evaluate an expression of record type as a temporary.
EvaluateTemporary(const Expr * E,LValue & Result,EvalInfo & Info)10037 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10038 assert(E->isRValue() && E->getType()->isRecordType());
10039 return TemporaryExprEvaluator(Info, Result).Visit(E);
10040 }
10041
10042 //===----------------------------------------------------------------------===//
10043 // Vector Evaluation
10044 //===----------------------------------------------------------------------===//
10045
10046 namespace {
10047 class VectorExprEvaluator
10048 : public ExprEvaluatorBase<VectorExprEvaluator> {
10049 APValue &Result;
10050 public:
10051
VectorExprEvaluator(EvalInfo & info,APValue & Result)10052 VectorExprEvaluator(EvalInfo &info, APValue &Result)
10053 : ExprEvaluatorBaseTy(info), Result(Result) {}
10054
Success(ArrayRef<APValue> V,const Expr * E)10055 bool Success(ArrayRef<APValue> V, const Expr *E) {
10056 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10057 // FIXME: remove this APValue copy.
10058 Result = APValue(V.data(), V.size());
10059 return true;
10060 }
Success(const APValue & V,const Expr * E)10061 bool Success(const APValue &V, const Expr *E) {
10062 assert(V.isVector());
10063 Result = V;
10064 return true;
10065 }
10066 bool ZeroInitialization(const Expr *E);
10067
VisitUnaryReal(const UnaryOperator * E)10068 bool VisitUnaryReal(const UnaryOperator *E)
10069 { return Visit(E->getSubExpr()); }
10070 bool VisitCastExpr(const CastExpr* E);
10071 bool VisitInitListExpr(const InitListExpr *E);
10072 bool VisitUnaryImag(const UnaryOperator *E);
10073 bool VisitBinaryOperator(const BinaryOperator *E);
10074 // FIXME: Missing: unary -, unary ~, conditional operator (for GNU
10075 // conditional select), shufflevector, ExtVectorElementExpr
10076 };
10077 } // end anonymous namespace
10078
EvaluateVector(const Expr * E,APValue & Result,EvalInfo & Info)10079 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10080 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
10081 return VectorExprEvaluator(Info, Result).Visit(E);
10082 }
10083
VisitCastExpr(const CastExpr * E)10084 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10085 const VectorType *VTy = E->getType()->castAs<VectorType>();
10086 unsigned NElts = VTy->getNumElements();
10087
10088 const Expr *SE = E->getSubExpr();
10089 QualType SETy = SE->getType();
10090
10091 switch (E->getCastKind()) {
10092 case CK_VectorSplat: {
10093 APValue Val = APValue();
10094 if (SETy->isIntegerType()) {
10095 APSInt IntResult;
10096 if (!EvaluateInteger(SE, IntResult, Info))
10097 return false;
10098 Val = APValue(std::move(IntResult));
10099 } else if (SETy->isRealFloatingType()) {
10100 APFloat FloatResult(0.0);
10101 if (!EvaluateFloat(SE, FloatResult, Info))
10102 return false;
10103 Val = APValue(std::move(FloatResult));
10104 } else {
10105 return Error(E);
10106 }
10107
10108 // Splat and create vector APValue.
10109 SmallVector<APValue, 4> Elts(NElts, Val);
10110 return Success(Elts, E);
10111 }
10112 case CK_BitCast: {
10113 // Evaluate the operand into an APInt we can extract from.
10114 llvm::APInt SValInt;
10115 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10116 return false;
10117 // Extract the elements
10118 QualType EltTy = VTy->getElementType();
10119 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10120 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10121 SmallVector<APValue, 4> Elts;
10122 if (EltTy->isRealFloatingType()) {
10123 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10124 unsigned FloatEltSize = EltSize;
10125 if (&Sem == &APFloat::x87DoubleExtended())
10126 FloatEltSize = 80;
10127 for (unsigned i = 0; i < NElts; i++) {
10128 llvm::APInt Elt;
10129 if (BigEndian)
10130 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
10131 else
10132 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
10133 Elts.push_back(APValue(APFloat(Sem, Elt)));
10134 }
10135 } else if (EltTy->isIntegerType()) {
10136 for (unsigned i = 0; i < NElts; i++) {
10137 llvm::APInt Elt;
10138 if (BigEndian)
10139 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10140 else
10141 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10142 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
10143 }
10144 } else {
10145 return Error(E);
10146 }
10147 return Success(Elts, E);
10148 }
10149 default:
10150 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10151 }
10152 }
10153
10154 bool
VisitInitListExpr(const InitListExpr * E)10155 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10156 const VectorType *VT = E->getType()->castAs<VectorType>();
10157 unsigned NumInits = E->getNumInits();
10158 unsigned NumElements = VT->getNumElements();
10159
10160 QualType EltTy = VT->getElementType();
10161 SmallVector<APValue, 4> Elements;
10162
10163 // The number of initializers can be less than the number of
10164 // vector elements. For OpenCL, this can be due to nested vector
10165 // initialization. For GCC compatibility, missing trailing elements
10166 // should be initialized with zeroes.
10167 unsigned CountInits = 0, CountElts = 0;
10168 while (CountElts < NumElements) {
10169 // Handle nested vector initialization.
10170 if (CountInits < NumInits
10171 && E->getInit(CountInits)->getType()->isVectorType()) {
10172 APValue v;
10173 if (!EvaluateVector(E->getInit(CountInits), v, Info))
10174 return Error(E);
10175 unsigned vlen = v.getVectorLength();
10176 for (unsigned j = 0; j < vlen; j++)
10177 Elements.push_back(v.getVectorElt(j));
10178 CountElts += vlen;
10179 } else if (EltTy->isIntegerType()) {
10180 llvm::APSInt sInt(32);
10181 if (CountInits < NumInits) {
10182 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10183 return false;
10184 } else // trailing integer zero.
10185 sInt = Info.Ctx.MakeIntValue(0, EltTy);
10186 Elements.push_back(APValue(sInt));
10187 CountElts++;
10188 } else {
10189 llvm::APFloat f(0.0);
10190 if (CountInits < NumInits) {
10191 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10192 return false;
10193 } else // trailing float zero.
10194 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10195 Elements.push_back(APValue(f));
10196 CountElts++;
10197 }
10198 CountInits++;
10199 }
10200 return Success(Elements, E);
10201 }
10202
10203 bool
ZeroInitialization(const Expr * E)10204 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10205 const auto *VT = E->getType()->castAs<VectorType>();
10206 QualType EltTy = VT->getElementType();
10207 APValue ZeroElement;
10208 if (EltTy->isIntegerType())
10209 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10210 else
10211 ZeroElement =
10212 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10213
10214 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10215 return Success(Elements, E);
10216 }
10217
VisitUnaryImag(const UnaryOperator * E)10218 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10219 VisitIgnoredValue(E->getSubExpr());
10220 return ZeroInitialization(E);
10221 }
10222
VisitBinaryOperator(const BinaryOperator * E)10223 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10224 BinaryOperatorKind Op = E->getOpcode();
10225 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10226 "Operation not supported on vector types");
10227
10228 if (Op == BO_Comma)
10229 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10230
10231 Expr *LHS = E->getLHS();
10232 Expr *RHS = E->getRHS();
10233
10234 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10235 "Must both be vector types");
10236 // Checking JUST the types are the same would be fine, except shifts don't
10237 // need to have their types be the same (since you always shift by an int).
10238 assert(LHS->getType()->getAs<VectorType>()->getNumElements() ==
10239 E->getType()->getAs<VectorType>()->getNumElements() &&
10240 RHS->getType()->getAs<VectorType>()->getNumElements() ==
10241 E->getType()->getAs<VectorType>()->getNumElements() &&
10242 "All operands must be the same size.");
10243
10244 APValue LHSValue;
10245 APValue RHSValue;
10246 bool LHSOK = Evaluate(LHSValue, Info, LHS);
10247 if (!LHSOK && !Info.noteFailure())
10248 return false;
10249 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10250 return false;
10251
10252 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10253 return false;
10254
10255 return Success(LHSValue, E);
10256 }
10257
10258 //===----------------------------------------------------------------------===//
10259 // Array Evaluation
10260 //===----------------------------------------------------------------------===//
10261
10262 namespace {
10263 class ArrayExprEvaluator
10264 : public ExprEvaluatorBase<ArrayExprEvaluator> {
10265 const LValue &This;
10266 APValue &Result;
10267 public:
10268
ArrayExprEvaluator(EvalInfo & Info,const LValue & This,APValue & Result)10269 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10270 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10271
Success(const APValue & V,const Expr * E)10272 bool Success(const APValue &V, const Expr *E) {
10273 assert(V.isArray() && "expected array");
10274 Result = V;
10275 return true;
10276 }
10277
ZeroInitialization(const Expr * E)10278 bool ZeroInitialization(const Expr *E) {
10279 const ConstantArrayType *CAT =
10280 Info.Ctx.getAsConstantArrayType(E->getType());
10281 if (!CAT) {
10282 if (E->getType()->isIncompleteArrayType()) {
10283 // We can be asked to zero-initialize a flexible array member; this
10284 // is represented as an ImplicitValueInitExpr of incomplete array
10285 // type. In this case, the array has zero elements.
10286 Result = APValue(APValue::UninitArray(), 0, 0);
10287 return true;
10288 }
10289 // FIXME: We could handle VLAs here.
10290 return Error(E);
10291 }
10292
10293 Result = APValue(APValue::UninitArray(), 0,
10294 CAT->getSize().getZExtValue());
10295 if (!Result.hasArrayFiller()) return true;
10296
10297 // Zero-initialize all elements.
10298 LValue Subobject = This;
10299 Subobject.addArray(Info, E, CAT);
10300 ImplicitValueInitExpr VIE(CAT->getElementType());
10301 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10302 }
10303
VisitCallExpr(const CallExpr * E)10304 bool VisitCallExpr(const CallExpr *E) {
10305 return handleCallExpr(E, Result, &This);
10306 }
10307 bool VisitInitListExpr(const InitListExpr *E,
10308 QualType AllocType = QualType());
10309 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10310 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10311 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10312 const LValue &Subobject,
10313 APValue *Value, QualType Type);
VisitStringLiteral(const StringLiteral * E,QualType AllocType=QualType ())10314 bool VisitStringLiteral(const StringLiteral *E,
10315 QualType AllocType = QualType()) {
10316 expandStringLiteral(Info, E, Result, AllocType);
10317 return true;
10318 }
10319 };
10320 } // end anonymous namespace
10321
EvaluateArray(const Expr * E,const LValue & This,APValue & Result,EvalInfo & Info)10322 static bool EvaluateArray(const Expr *E, const LValue &This,
10323 APValue &Result, EvalInfo &Info) {
10324 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
10325 return ArrayExprEvaluator(Info, This, Result).Visit(E);
10326 }
10327
EvaluateArrayNewInitList(EvalInfo & Info,LValue & This,APValue & Result,const InitListExpr * ILE,QualType AllocType)10328 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10329 APValue &Result, const InitListExpr *ILE,
10330 QualType AllocType) {
10331 assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
10332 "not an array rvalue");
10333 return ArrayExprEvaluator(Info, This, Result)
10334 .VisitInitListExpr(ILE, AllocType);
10335 }
10336
EvaluateArrayNewConstructExpr(EvalInfo & Info,LValue & This,APValue & Result,const CXXConstructExpr * CCE,QualType AllocType)10337 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10338 APValue &Result,
10339 const CXXConstructExpr *CCE,
10340 QualType AllocType) {
10341 assert(CCE->isRValue() && CCE->getType()->isArrayType() &&
10342 "not an array rvalue");
10343 return ArrayExprEvaluator(Info, This, Result)
10344 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10345 }
10346
10347 // Return true iff the given array filler may depend on the element index.
MaybeElementDependentArrayFiller(const Expr * FillerExpr)10348 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10349 // For now, just allow non-class value-initialization and initialization
10350 // lists comprised of them.
10351 if (isa<ImplicitValueInitExpr>(FillerExpr))
10352 return false;
10353 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10354 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10355 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10356 return true;
10357 }
10358 return false;
10359 }
10360 return true;
10361 }
10362
VisitInitListExpr(const InitListExpr * E,QualType AllocType)10363 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10364 QualType AllocType) {
10365 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10366 AllocType.isNull() ? E->getType() : AllocType);
10367 if (!CAT)
10368 return Error(E);
10369
10370 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10371 // an appropriately-typed string literal enclosed in braces.
10372 if (E->isStringLiteralInit()) {
10373 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
10374 // FIXME: Support ObjCEncodeExpr here once we support it in
10375 // ArrayExprEvaluator generally.
10376 if (!SL)
10377 return Error(E);
10378 return VisitStringLiteral(SL, AllocType);
10379 }
10380
10381 bool Success = true;
10382
10383 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10384 "zero-initialized array shouldn't have any initialized elts");
10385 APValue Filler;
10386 if (Result.isArray() && Result.hasArrayFiller())
10387 Filler = Result.getArrayFiller();
10388
10389 unsigned NumEltsToInit = E->getNumInits();
10390 unsigned NumElts = CAT->getSize().getZExtValue();
10391 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10392
10393 // If the initializer might depend on the array index, run it for each
10394 // array element.
10395 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10396 NumEltsToInit = NumElts;
10397
10398 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10399 << NumEltsToInit << ".\n");
10400
10401 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10402
10403 // If the array was previously zero-initialized, preserve the
10404 // zero-initialized values.
10405 if (Filler.hasValue()) {
10406 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10407 Result.getArrayInitializedElt(I) = Filler;
10408 if (Result.hasArrayFiller())
10409 Result.getArrayFiller() = Filler;
10410 }
10411
10412 LValue Subobject = This;
10413 Subobject.addArray(Info, E, CAT);
10414 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10415 const Expr *Init =
10416 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10417 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10418 Info, Subobject, Init) ||
10419 !HandleLValueArrayAdjustment(Info, Init, Subobject,
10420 CAT->getElementType(), 1)) {
10421 if (!Info.noteFailure())
10422 return false;
10423 Success = false;
10424 }
10425 }
10426
10427 if (!Result.hasArrayFiller())
10428 return Success;
10429
10430 // If we get here, we have a trivial filler, which we can just evaluate
10431 // once and splat over the rest of the array elements.
10432 assert(FillerExpr && "no array filler for incomplete init list");
10433 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10434 FillerExpr) && Success;
10435 }
10436
VisitArrayInitLoopExpr(const ArrayInitLoopExpr * E)10437 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10438 LValue CommonLV;
10439 if (E->getCommonExpr() &&
10440 !Evaluate(Info.CurrentCall->createTemporary(
10441 E->getCommonExpr(),
10442 getStorageType(Info.Ctx, E->getCommonExpr()),
10443 ScopeKind::FullExpression, CommonLV),
10444 Info, E->getCommonExpr()->getSourceExpr()))
10445 return false;
10446
10447 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10448
10449 uint64_t Elements = CAT->getSize().getZExtValue();
10450 Result = APValue(APValue::UninitArray(), Elements, Elements);
10451
10452 LValue Subobject = This;
10453 Subobject.addArray(Info, E, CAT);
10454
10455 bool Success = true;
10456 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10457 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10458 Info, Subobject, E->getSubExpr()) ||
10459 !HandleLValueArrayAdjustment(Info, E, Subobject,
10460 CAT->getElementType(), 1)) {
10461 if (!Info.noteFailure())
10462 return false;
10463 Success = false;
10464 }
10465 }
10466
10467 return Success;
10468 }
10469
VisitCXXConstructExpr(const CXXConstructExpr * E)10470 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10471 return VisitCXXConstructExpr(E, This, &Result, E->getType());
10472 }
10473
VisitCXXConstructExpr(const CXXConstructExpr * E,const LValue & Subobject,APValue * Value,QualType Type)10474 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10475 const LValue &Subobject,
10476 APValue *Value,
10477 QualType Type) {
10478 bool HadZeroInit = Value->hasValue();
10479
10480 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10481 unsigned N = CAT->getSize().getZExtValue();
10482
10483 // Preserve the array filler if we had prior zero-initialization.
10484 APValue Filler =
10485 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10486 : APValue();
10487
10488 *Value = APValue(APValue::UninitArray(), N, N);
10489
10490 if (HadZeroInit)
10491 for (unsigned I = 0; I != N; ++I)
10492 Value->getArrayInitializedElt(I) = Filler;
10493
10494 // Initialize the elements.
10495 LValue ArrayElt = Subobject;
10496 ArrayElt.addArray(Info, E, CAT);
10497 for (unsigned I = 0; I != N; ++I)
10498 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
10499 CAT->getElementType()) ||
10500 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10501 CAT->getElementType(), 1))
10502 return false;
10503
10504 return true;
10505 }
10506
10507 if (!Type->isRecordType())
10508 return Error(E);
10509
10510 return RecordExprEvaluator(Info, Subobject, *Value)
10511 .VisitCXXConstructExpr(E, Type);
10512 }
10513
10514 //===----------------------------------------------------------------------===//
10515 // Integer Evaluation
10516 //
10517 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10518 // types and back in constant folding. Integer values are thus represented
10519 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10520 //===----------------------------------------------------------------------===//
10521
10522 namespace {
10523 class IntExprEvaluator
10524 : public ExprEvaluatorBase<IntExprEvaluator> {
10525 APValue &Result;
10526 public:
IntExprEvaluator(EvalInfo & info,APValue & result)10527 IntExprEvaluator(EvalInfo &info, APValue &result)
10528 : ExprEvaluatorBaseTy(info), Result(result) {}
10529
Success(const llvm::APSInt & SI,const Expr * E,APValue & Result)10530 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10531 assert(E->getType()->isIntegralOrEnumerationType() &&
10532 "Invalid evaluation result.");
10533 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10534 "Invalid evaluation result.");
10535 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10536 "Invalid evaluation result.");
10537 Result = APValue(SI);
10538 return true;
10539 }
Success(const llvm::APSInt & SI,const Expr * E)10540 bool Success(const llvm::APSInt &SI, const Expr *E) {
10541 return Success(SI, E, Result);
10542 }
10543
Success(const llvm::APInt & I,const Expr * E,APValue & Result)10544 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10545 assert(E->getType()->isIntegralOrEnumerationType() &&
10546 "Invalid evaluation result.");
10547 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10548 "Invalid evaluation result.");
10549 Result = APValue(APSInt(I));
10550 Result.getInt().setIsUnsigned(
10551 E->getType()->isUnsignedIntegerOrEnumerationType());
10552 return true;
10553 }
Success(const llvm::APInt & I,const Expr * E)10554 bool Success(const llvm::APInt &I, const Expr *E) {
10555 return Success(I, E, Result);
10556 }
10557
Success(uint64_t Value,const Expr * E,APValue & Result)10558 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10559 assert(E->getType()->isIntegralOrEnumerationType() &&
10560 "Invalid evaluation result.");
10561 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10562 return true;
10563 }
Success(uint64_t Value,const Expr * E)10564 bool Success(uint64_t Value, const Expr *E) {
10565 return Success(Value, E, Result);
10566 }
10567
Success(CharUnits Size,const Expr * E)10568 bool Success(CharUnits Size, const Expr *E) {
10569 return Success(Size.getQuantity(), E);
10570 }
10571
Success(const APValue & V,const Expr * E)10572 bool Success(const APValue &V, const Expr *E) {
10573 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10574 Result = V;
10575 return true;
10576 }
10577 return Success(V.getInt(), E);
10578 }
10579
ZeroInitialization(const Expr * E)10580 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10581
10582 //===--------------------------------------------------------------------===//
10583 // Visitor Methods
10584 //===--------------------------------------------------------------------===//
10585
VisitIntegerLiteral(const IntegerLiteral * E)10586 bool VisitIntegerLiteral(const IntegerLiteral *E) {
10587 return Success(E->getValue(), E);
10588 }
VisitCharacterLiteral(const CharacterLiteral * E)10589 bool VisitCharacterLiteral(const CharacterLiteral *E) {
10590 return Success(E->getValue(), E);
10591 }
10592
10593 bool CheckReferencedDecl(const Expr *E, const Decl *D);
VisitDeclRefExpr(const DeclRefExpr * E)10594 bool VisitDeclRefExpr(const DeclRefExpr *E) {
10595 if (CheckReferencedDecl(E, E->getDecl()))
10596 return true;
10597
10598 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10599 }
VisitMemberExpr(const MemberExpr * E)10600 bool VisitMemberExpr(const MemberExpr *E) {
10601 if (CheckReferencedDecl(E, E->getMemberDecl())) {
10602 VisitIgnoredBaseExpression(E->getBase());
10603 return true;
10604 }
10605
10606 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10607 }
10608
10609 bool VisitCallExpr(const CallExpr *E);
10610 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10611 bool VisitBinaryOperator(const BinaryOperator *E);
10612 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10613 bool VisitUnaryOperator(const UnaryOperator *E);
10614
10615 bool VisitCastExpr(const CastExpr* E);
10616 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10617
VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr * E)10618 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10619 return Success(E->getValue(), E);
10620 }
10621
VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr * E)10622 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10623 return Success(E->getValue(), E);
10624 }
10625
VisitArrayInitIndexExpr(const ArrayInitIndexExpr * E)10626 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10627 if (Info.ArrayInitIndex == uint64_t(-1)) {
10628 // We were asked to evaluate this subexpression independent of the
10629 // enclosing ArrayInitLoopExpr. We can't do that.
10630 Info.FFDiag(E);
10631 return false;
10632 }
10633 return Success(Info.ArrayInitIndex, E);
10634 }
10635
10636 // Note, GNU defines __null as an integer, not a pointer.
VisitGNUNullExpr(const GNUNullExpr * E)10637 bool VisitGNUNullExpr(const GNUNullExpr *E) {
10638 return ZeroInitialization(E);
10639 }
10640
VisitTypeTraitExpr(const TypeTraitExpr * E)10641 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10642 return Success(E->getValue(), E);
10643 }
10644
VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr * E)10645 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10646 return Success(E->getValue(), E);
10647 }
10648
VisitExpressionTraitExpr(const ExpressionTraitExpr * E)10649 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10650 return Success(E->getValue(), E);
10651 }
10652
10653 bool VisitUnaryReal(const UnaryOperator *E);
10654 bool VisitUnaryImag(const UnaryOperator *E);
10655
10656 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10657 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10658 bool VisitSourceLocExpr(const SourceLocExpr *E);
10659 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10660 bool VisitRequiresExpr(const RequiresExpr *E);
10661 // FIXME: Missing: array subscript of vector, member of vector
10662 };
10663
10664 class FixedPointExprEvaluator
10665 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10666 APValue &Result;
10667
10668 public:
FixedPointExprEvaluator(EvalInfo & info,APValue & result)10669 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10670 : ExprEvaluatorBaseTy(info), Result(result) {}
10671
Success(const llvm::APInt & I,const Expr * E)10672 bool Success(const llvm::APInt &I, const Expr *E) {
10673 return Success(
10674 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10675 }
10676
Success(uint64_t Value,const Expr * E)10677 bool Success(uint64_t Value, const Expr *E) {
10678 return Success(
10679 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10680 }
10681
Success(const APValue & V,const Expr * E)10682 bool Success(const APValue &V, const Expr *E) {
10683 return Success(V.getFixedPoint(), E);
10684 }
10685
Success(const APFixedPoint & V,const Expr * E)10686 bool Success(const APFixedPoint &V, const Expr *E) {
10687 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10688 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10689 "Invalid evaluation result.");
10690 Result = APValue(V);
10691 return true;
10692 }
10693
10694 //===--------------------------------------------------------------------===//
10695 // Visitor Methods
10696 //===--------------------------------------------------------------------===//
10697
VisitFixedPointLiteral(const FixedPointLiteral * E)10698 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10699 return Success(E->getValue(), E);
10700 }
10701
10702 bool VisitCastExpr(const CastExpr *E);
10703 bool VisitUnaryOperator(const UnaryOperator *E);
10704 bool VisitBinaryOperator(const BinaryOperator *E);
10705 };
10706 } // end anonymous namespace
10707
10708 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10709 /// produce either the integer value or a pointer.
10710 ///
10711 /// GCC has a heinous extension which folds casts between pointer types and
10712 /// pointer-sized integral types. We support this by allowing the evaluation of
10713 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10714 /// Some simple arithmetic on such values is supported (they are treated much
10715 /// like char*).
EvaluateIntegerOrLValue(const Expr * E,APValue & Result,EvalInfo & Info)10716 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10717 EvalInfo &Info) {
10718 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
10719 return IntExprEvaluator(Info, Result).Visit(E);
10720 }
10721
EvaluateInteger(const Expr * E,APSInt & Result,EvalInfo & Info)10722 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10723 APValue Val;
10724 if (!EvaluateIntegerOrLValue(E, Val, Info))
10725 return false;
10726 if (!Val.isInt()) {
10727 // FIXME: It would be better to produce the diagnostic for casting
10728 // a pointer to an integer.
10729 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10730 return false;
10731 }
10732 Result = Val.getInt();
10733 return true;
10734 }
10735
VisitSourceLocExpr(const SourceLocExpr * E)10736 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10737 APValue Evaluated = E->EvaluateInContext(
10738 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10739 return Success(Evaluated, E);
10740 }
10741
EvaluateFixedPoint(const Expr * E,APFixedPoint & Result,EvalInfo & Info)10742 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10743 EvalInfo &Info) {
10744 if (E->getType()->isFixedPointType()) {
10745 APValue Val;
10746 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10747 return false;
10748 if (!Val.isFixedPoint())
10749 return false;
10750
10751 Result = Val.getFixedPoint();
10752 return true;
10753 }
10754 return false;
10755 }
10756
EvaluateFixedPointOrInteger(const Expr * E,APFixedPoint & Result,EvalInfo & Info)10757 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10758 EvalInfo &Info) {
10759 if (E->getType()->isIntegerType()) {
10760 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10761 APSInt Val;
10762 if (!EvaluateInteger(E, Val, Info))
10763 return false;
10764 Result = APFixedPoint(Val, FXSema);
10765 return true;
10766 } else if (E->getType()->isFixedPointType()) {
10767 return EvaluateFixedPoint(E, Result, Info);
10768 }
10769 return false;
10770 }
10771
10772 /// Check whether the given declaration can be directly converted to an integral
10773 /// rvalue. If not, no diagnostic is produced; there are other things we can
10774 /// try.
CheckReferencedDecl(const Expr * E,const Decl * D)10775 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10776 // Enums are integer constant exprs.
10777 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10778 // Check for signedness/width mismatches between E type and ECD value.
10779 bool SameSign = (ECD->getInitVal().isSigned()
10780 == E->getType()->isSignedIntegerOrEnumerationType());
10781 bool SameWidth = (ECD->getInitVal().getBitWidth()
10782 == Info.Ctx.getIntWidth(E->getType()));
10783 if (SameSign && SameWidth)
10784 return Success(ECD->getInitVal(), E);
10785 else {
10786 // Get rid of mismatch (otherwise Success assertions will fail)
10787 // by computing a new value matching the type of E.
10788 llvm::APSInt Val = ECD->getInitVal();
10789 if (!SameSign)
10790 Val.setIsSigned(!ECD->getInitVal().isSigned());
10791 if (!SameWidth)
10792 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10793 return Success(Val, E);
10794 }
10795 }
10796 return false;
10797 }
10798
10799 /// Values returned by __builtin_classify_type, chosen to match the values
10800 /// produced by GCC's builtin.
10801 enum class GCCTypeClass {
10802 None = -1,
10803 Void = 0,
10804 Integer = 1,
10805 // GCC reserves 2 for character types, but instead classifies them as
10806 // integers.
10807 Enum = 3,
10808 Bool = 4,
10809 Pointer = 5,
10810 // GCC reserves 6 for references, but appears to never use it (because
10811 // expressions never have reference type, presumably).
10812 PointerToDataMember = 7,
10813 RealFloat = 8,
10814 Complex = 9,
10815 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10816 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10817 // GCC claims to reserve 11 for pointers to member functions, but *actually*
10818 // uses 12 for that purpose, same as for a class or struct. Maybe it
10819 // internally implements a pointer to member as a struct? Who knows.
10820 PointerToMemberFunction = 12, // Not a bug, see above.
10821 ClassOrStruct = 12,
10822 Union = 13,
10823 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10824 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10825 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10826 // literals.
10827 };
10828
10829 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10830 /// as GCC.
10831 static GCCTypeClass
EvaluateBuiltinClassifyType(QualType T,const LangOptions & LangOpts)10832 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10833 assert(!T->isDependentType() && "unexpected dependent type");
10834
10835 QualType CanTy = T.getCanonicalType();
10836 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10837
10838 switch (CanTy->getTypeClass()) {
10839 #define TYPE(ID, BASE)
10840 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10841 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10842 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10843 #include "clang/AST/TypeNodes.inc"
10844 case Type::Auto:
10845 case Type::DeducedTemplateSpecialization:
10846 llvm_unreachable("unexpected non-canonical or dependent type");
10847
10848 case Type::Builtin:
10849 switch (BT->getKind()) {
10850 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10851 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10852 case BuiltinType::ID: return GCCTypeClass::Integer;
10853 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10854 case BuiltinType::ID: return GCCTypeClass::RealFloat;
10855 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10856 case BuiltinType::ID: break;
10857 #include "clang/AST/BuiltinTypes.def"
10858 case BuiltinType::Void:
10859 return GCCTypeClass::Void;
10860
10861 case BuiltinType::Bool:
10862 return GCCTypeClass::Bool;
10863
10864 case BuiltinType::Char_U:
10865 case BuiltinType::UChar:
10866 case BuiltinType::WChar_U:
10867 case BuiltinType::Char8:
10868 case BuiltinType::Char16:
10869 case BuiltinType::Char32:
10870 case BuiltinType::UShort:
10871 case BuiltinType::UInt:
10872 case BuiltinType::ULong:
10873 case BuiltinType::ULongLong:
10874 case BuiltinType::UInt128:
10875 return GCCTypeClass::Integer;
10876
10877 case BuiltinType::UShortAccum:
10878 case BuiltinType::UAccum:
10879 case BuiltinType::ULongAccum:
10880 case BuiltinType::UShortFract:
10881 case BuiltinType::UFract:
10882 case BuiltinType::ULongFract:
10883 case BuiltinType::SatUShortAccum:
10884 case BuiltinType::SatUAccum:
10885 case BuiltinType::SatULongAccum:
10886 case BuiltinType::SatUShortFract:
10887 case BuiltinType::SatUFract:
10888 case BuiltinType::SatULongFract:
10889 return GCCTypeClass::None;
10890
10891 case BuiltinType::NullPtr:
10892
10893 case BuiltinType::ObjCId:
10894 case BuiltinType::ObjCClass:
10895 case BuiltinType::ObjCSel:
10896 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10897 case BuiltinType::Id:
10898 #include "clang/Basic/OpenCLImageTypes.def"
10899 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10900 case BuiltinType::Id:
10901 #include "clang/Basic/OpenCLExtensionTypes.def"
10902 case BuiltinType::OCLSampler:
10903 case BuiltinType::OCLEvent:
10904 case BuiltinType::OCLClkEvent:
10905 case BuiltinType::OCLQueue:
10906 case BuiltinType::OCLReserveID:
10907 #define SVE_TYPE(Name, Id, SingletonId) \
10908 case BuiltinType::Id:
10909 #include "clang/Basic/AArch64SVEACLETypes.def"
10910 #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \
10911 case BuiltinType::Id:
10912 #include "clang/Basic/PPCTypes.def"
10913 return GCCTypeClass::None;
10914
10915 case BuiltinType::Dependent:
10916 llvm_unreachable("unexpected dependent type");
10917 };
10918 llvm_unreachable("unexpected placeholder type");
10919
10920 case Type::Enum:
10921 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
10922
10923 case Type::Pointer:
10924 case Type::ConstantArray:
10925 case Type::VariableArray:
10926 case Type::IncompleteArray:
10927 case Type::FunctionNoProto:
10928 case Type::FunctionProto:
10929 return GCCTypeClass::Pointer;
10930
10931 case Type::MemberPointer:
10932 return CanTy->isMemberDataPointerType()
10933 ? GCCTypeClass::PointerToDataMember
10934 : GCCTypeClass::PointerToMemberFunction;
10935
10936 case Type::Complex:
10937 return GCCTypeClass::Complex;
10938
10939 case Type::Record:
10940 return CanTy->isUnionType() ? GCCTypeClass::Union
10941 : GCCTypeClass::ClassOrStruct;
10942
10943 case Type::Atomic:
10944 // GCC classifies _Atomic T the same as T.
10945 return EvaluateBuiltinClassifyType(
10946 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
10947
10948 case Type::BlockPointer:
10949 case Type::Vector:
10950 case Type::ExtVector:
10951 case Type::ConstantMatrix:
10952 case Type::ObjCObject:
10953 case Type::ObjCInterface:
10954 case Type::ObjCObjectPointer:
10955 case Type::Pipe:
10956 case Type::ExtInt:
10957 // GCC classifies vectors as None. We follow its lead and classify all
10958 // other types that don't fit into the regular classification the same way.
10959 return GCCTypeClass::None;
10960
10961 case Type::LValueReference:
10962 case Type::RValueReference:
10963 llvm_unreachable("invalid type for expression");
10964 }
10965
10966 llvm_unreachable("unexpected type class");
10967 }
10968
10969 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10970 /// as GCC.
10971 static GCCTypeClass
EvaluateBuiltinClassifyType(const CallExpr * E,const LangOptions & LangOpts)10972 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
10973 // If no argument was supplied, default to None. This isn't
10974 // ideal, however it is what gcc does.
10975 if (E->getNumArgs() == 0)
10976 return GCCTypeClass::None;
10977
10978 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
10979 // being an ICE, but still folds it to a constant using the type of the first
10980 // argument.
10981 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
10982 }
10983
10984 /// EvaluateBuiltinConstantPForLValue - Determine the result of
10985 /// __builtin_constant_p when applied to the given pointer.
10986 ///
10987 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
10988 /// or it points to the first character of a string literal.
EvaluateBuiltinConstantPForLValue(const APValue & LV)10989 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
10990 APValue::LValueBase Base = LV.getLValueBase();
10991 if (Base.isNull()) {
10992 // A null base is acceptable.
10993 return true;
10994 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
10995 if (!isa<StringLiteral>(E))
10996 return false;
10997 return LV.getLValueOffset().isZero();
10998 } else if (Base.is<TypeInfoLValue>()) {
10999 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11000 // evaluate to true.
11001 return true;
11002 } else {
11003 // Any other base is not constant enough for GCC.
11004 return false;
11005 }
11006 }
11007
11008 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11009 /// GCC as we can manage.
EvaluateBuiltinConstantP(EvalInfo & Info,const Expr * Arg)11010 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11011 // This evaluation is not permitted to have side-effects, so evaluate it in
11012 // a speculative evaluation context.
11013 SpeculativeEvaluationRAII SpeculativeEval(Info);
11014
11015 // Constant-folding is always enabled for the operand of __builtin_constant_p
11016 // (even when the enclosing evaluation context otherwise requires a strict
11017 // language-specific constant expression).
11018 FoldConstant Fold(Info, true);
11019
11020 QualType ArgType = Arg->getType();
11021
11022 // __builtin_constant_p always has one operand. The rules which gcc follows
11023 // are not precisely documented, but are as follows:
11024 //
11025 // - If the operand is of integral, floating, complex or enumeration type,
11026 // and can be folded to a known value of that type, it returns 1.
11027 // - If the operand can be folded to a pointer to the first character
11028 // of a string literal (or such a pointer cast to an integral type)
11029 // or to a null pointer or an integer cast to a pointer, it returns 1.
11030 //
11031 // Otherwise, it returns 0.
11032 //
11033 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11034 // its support for this did not work prior to GCC 9 and is not yet well
11035 // understood.
11036 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11037 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11038 ArgType->isNullPtrType()) {
11039 APValue V;
11040 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11041 Fold.keepDiagnostics();
11042 return false;
11043 }
11044
11045 // For a pointer (possibly cast to integer), there are special rules.
11046 if (V.getKind() == APValue::LValue)
11047 return EvaluateBuiltinConstantPForLValue(V);
11048
11049 // Otherwise, any constant value is good enough.
11050 return V.hasValue();
11051 }
11052
11053 // Anything else isn't considered to be sufficiently constant.
11054 return false;
11055 }
11056
11057 /// Retrieves the "underlying object type" of the given expression,
11058 /// as used by __builtin_object_size.
getObjectType(APValue::LValueBase B)11059 static QualType getObjectType(APValue::LValueBase B) {
11060 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11061 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11062 return VD->getType();
11063 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11064 if (isa<CompoundLiteralExpr>(E))
11065 return E->getType();
11066 } else if (B.is<TypeInfoLValue>()) {
11067 return B.getTypeInfoType();
11068 } else if (B.is<DynamicAllocLValue>()) {
11069 return B.getDynamicAllocType();
11070 }
11071
11072 return QualType();
11073 }
11074
11075 /// A more selective version of E->IgnoreParenCasts for
11076 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11077 /// to change the type of E.
11078 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11079 ///
11080 /// Always returns an RValue with a pointer representation.
ignorePointerCastsAndParens(const Expr * E)11081 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11082 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
11083
11084 auto *NoParens = E->IgnoreParens();
11085 auto *Cast = dyn_cast<CastExpr>(NoParens);
11086 if (Cast == nullptr)
11087 return NoParens;
11088
11089 // We only conservatively allow a few kinds of casts, because this code is
11090 // inherently a simple solution that seeks to support the common case.
11091 auto CastKind = Cast->getCastKind();
11092 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11093 CastKind != CK_AddressSpaceConversion)
11094 return NoParens;
11095
11096 auto *SubExpr = Cast->getSubExpr();
11097 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
11098 return NoParens;
11099 return ignorePointerCastsAndParens(SubExpr);
11100 }
11101
11102 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11103 /// record layout. e.g.
11104 /// struct { struct { int a, b; } fst, snd; } obj;
11105 /// obj.fst // no
11106 /// obj.snd // yes
11107 /// obj.fst.a // no
11108 /// obj.fst.b // no
11109 /// obj.snd.a // no
11110 /// obj.snd.b // yes
11111 ///
11112 /// Please note: this function is specialized for how __builtin_object_size
11113 /// views "objects".
11114 ///
11115 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11116 /// correct result, it will always return true.
isDesignatorAtObjectEnd(const ASTContext & Ctx,const LValue & LVal)11117 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11118 assert(!LVal.Designator.Invalid);
11119
11120 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11121 const RecordDecl *Parent = FD->getParent();
11122 Invalid = Parent->isInvalidDecl();
11123 if (Invalid || Parent->isUnion())
11124 return true;
11125 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11126 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11127 };
11128
11129 auto &Base = LVal.getLValueBase();
11130 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11131 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11132 bool Invalid;
11133 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11134 return Invalid;
11135 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11136 for (auto *FD : IFD->chain()) {
11137 bool Invalid;
11138 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11139 return Invalid;
11140 }
11141 }
11142 }
11143
11144 unsigned I = 0;
11145 QualType BaseType = getType(Base);
11146 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11147 // If we don't know the array bound, conservatively assume we're looking at
11148 // the final array element.
11149 ++I;
11150 if (BaseType->isIncompleteArrayType())
11151 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11152 else
11153 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11154 }
11155
11156 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11157 const auto &Entry = LVal.Designator.Entries[I];
11158 if (BaseType->isArrayType()) {
11159 // Because __builtin_object_size treats arrays as objects, we can ignore
11160 // the index iff this is the last array in the Designator.
11161 if (I + 1 == E)
11162 return true;
11163 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11164 uint64_t Index = Entry.getAsArrayIndex();
11165 if (Index + 1 != CAT->getSize())
11166 return false;
11167 BaseType = CAT->getElementType();
11168 } else if (BaseType->isAnyComplexType()) {
11169 const auto *CT = BaseType->castAs<ComplexType>();
11170 uint64_t Index = Entry.getAsArrayIndex();
11171 if (Index != 1)
11172 return false;
11173 BaseType = CT->getElementType();
11174 } else if (auto *FD = getAsField(Entry)) {
11175 bool Invalid;
11176 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11177 return Invalid;
11178 BaseType = FD->getType();
11179 } else {
11180 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11181 return false;
11182 }
11183 }
11184 return true;
11185 }
11186
11187 /// Tests to see if the LValue has a user-specified designator (that isn't
11188 /// necessarily valid). Note that this always returns 'true' if the LValue has
11189 /// an unsized array as its first designator entry, because there's currently no
11190 /// way to tell if the user typed *foo or foo[0].
refersToCompleteObject(const LValue & LVal)11191 static bool refersToCompleteObject(const LValue &LVal) {
11192 if (LVal.Designator.Invalid)
11193 return false;
11194
11195 if (!LVal.Designator.Entries.empty())
11196 return LVal.Designator.isMostDerivedAnUnsizedArray();
11197
11198 if (!LVal.InvalidBase)
11199 return true;
11200
11201 // If `E` is a MemberExpr, then the first part of the designator is hiding in
11202 // the LValueBase.
11203 const auto *E = LVal.Base.dyn_cast<const Expr *>();
11204 return !E || !isa<MemberExpr>(E);
11205 }
11206
11207 /// Attempts to detect a user writing into a piece of memory that's impossible
11208 /// to figure out the size of by just using types.
isUserWritingOffTheEnd(const ASTContext & Ctx,const LValue & LVal)11209 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11210 const SubobjectDesignator &Designator = LVal.Designator;
11211 // Notes:
11212 // - Users can only write off of the end when we have an invalid base. Invalid
11213 // bases imply we don't know where the memory came from.
11214 // - We used to be a bit more aggressive here; we'd only be conservative if
11215 // the array at the end was flexible, or if it had 0 or 1 elements. This
11216 // broke some common standard library extensions (PR30346), but was
11217 // otherwise seemingly fine. It may be useful to reintroduce this behavior
11218 // with some sort of list. OTOH, it seems that GCC is always
11219 // conservative with the last element in structs (if it's an array), so our
11220 // current behavior is more compatible than an explicit list approach would
11221 // be.
11222 return LVal.InvalidBase &&
11223 Designator.Entries.size() == Designator.MostDerivedPathLength &&
11224 Designator.MostDerivedIsArrayElement &&
11225 isDesignatorAtObjectEnd(Ctx, LVal);
11226 }
11227
11228 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11229 /// Fails if the conversion would cause loss of precision.
convertUnsignedAPIntToCharUnits(const llvm::APInt & Int,CharUnits & Result)11230 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11231 CharUnits &Result) {
11232 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11233 if (Int.ugt(CharUnitsMax))
11234 return false;
11235 Result = CharUnits::fromQuantity(Int.getZExtValue());
11236 return true;
11237 }
11238
11239 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11240 /// determine how many bytes exist from the beginning of the object to either
11241 /// the end of the current subobject, or the end of the object itself, depending
11242 /// on what the LValue looks like + the value of Type.
11243 ///
11244 /// If this returns false, the value of Result is undefined.
determineEndOffset(EvalInfo & Info,SourceLocation ExprLoc,unsigned Type,const LValue & LVal,CharUnits & EndOffset)11245 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11246 unsigned Type, const LValue &LVal,
11247 CharUnits &EndOffset) {
11248 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11249
11250 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11251 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11252 return false;
11253 return HandleSizeof(Info, ExprLoc, Ty, Result);
11254 };
11255
11256 // We want to evaluate the size of the entire object. This is a valid fallback
11257 // for when Type=1 and the designator is invalid, because we're asked for an
11258 // upper-bound.
11259 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11260 // Type=3 wants a lower bound, so we can't fall back to this.
11261 if (Type == 3 && !DetermineForCompleteObject)
11262 return false;
11263
11264 llvm::APInt APEndOffset;
11265 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11266 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11267 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11268
11269 if (LVal.InvalidBase)
11270 return false;
11271
11272 QualType BaseTy = getObjectType(LVal.getLValueBase());
11273 return CheckedHandleSizeof(BaseTy, EndOffset);
11274 }
11275
11276 // We want to evaluate the size of a subobject.
11277 const SubobjectDesignator &Designator = LVal.Designator;
11278
11279 // The following is a moderately common idiom in C:
11280 //
11281 // struct Foo { int a; char c[1]; };
11282 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11283 // strcpy(&F->c[0], Bar);
11284 //
11285 // In order to not break too much legacy code, we need to support it.
11286 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11287 // If we can resolve this to an alloc_size call, we can hand that back,
11288 // because we know for certain how many bytes there are to write to.
11289 llvm::APInt APEndOffset;
11290 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11291 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11292 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11293
11294 // If we cannot determine the size of the initial allocation, then we can't
11295 // given an accurate upper-bound. However, we are still able to give
11296 // conservative lower-bounds for Type=3.
11297 if (Type == 1)
11298 return false;
11299 }
11300
11301 CharUnits BytesPerElem;
11302 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11303 return false;
11304
11305 // According to the GCC documentation, we want the size of the subobject
11306 // denoted by the pointer. But that's not quite right -- what we actually
11307 // want is the size of the immediately-enclosing array, if there is one.
11308 int64_t ElemsRemaining;
11309 if (Designator.MostDerivedIsArrayElement &&
11310 Designator.Entries.size() == Designator.MostDerivedPathLength) {
11311 uint64_t ArraySize = Designator.getMostDerivedArraySize();
11312 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11313 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11314 } else {
11315 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11316 }
11317
11318 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11319 return true;
11320 }
11321
11322 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11323 /// returns true and stores the result in @p Size.
11324 ///
11325 /// If @p WasError is non-null, this will report whether the failure to evaluate
11326 /// is to be treated as an Error in IntExprEvaluator.
tryEvaluateBuiltinObjectSize(const Expr * E,unsigned Type,EvalInfo & Info,uint64_t & Size)11327 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11328 EvalInfo &Info, uint64_t &Size) {
11329 // Determine the denoted object.
11330 LValue LVal;
11331 {
11332 // The operand of __builtin_object_size is never evaluated for side-effects.
11333 // If there are any, but we can determine the pointed-to object anyway, then
11334 // ignore the side-effects.
11335 SpeculativeEvaluationRAII SpeculativeEval(Info);
11336 IgnoreSideEffectsRAII Fold(Info);
11337
11338 if (E->isGLValue()) {
11339 // It's possible for us to be given GLValues if we're called via
11340 // Expr::tryEvaluateObjectSize.
11341 APValue RVal;
11342 if (!EvaluateAsRValue(Info, E, RVal))
11343 return false;
11344 LVal.setFrom(Info.Ctx, RVal);
11345 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11346 /*InvalidBaseOK=*/true))
11347 return false;
11348 }
11349
11350 // If we point to before the start of the object, there are no accessible
11351 // bytes.
11352 if (LVal.getLValueOffset().isNegative()) {
11353 Size = 0;
11354 return true;
11355 }
11356
11357 CharUnits EndOffset;
11358 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11359 return false;
11360
11361 // If we've fallen outside of the end offset, just pretend there's nothing to
11362 // write to/read from.
11363 if (EndOffset <= LVal.getLValueOffset())
11364 Size = 0;
11365 else
11366 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11367 return true;
11368 }
11369
VisitCallExpr(const CallExpr * E)11370 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11371 if (unsigned BuiltinOp = E->getBuiltinCallee())
11372 return VisitBuiltinCallExpr(E, BuiltinOp);
11373
11374 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11375 }
11376
getBuiltinAlignArguments(const CallExpr * E,EvalInfo & Info,APValue & Val,APSInt & Alignment)11377 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11378 APValue &Val, APSInt &Alignment) {
11379 QualType SrcTy = E->getArg(0)->getType();
11380 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11381 return false;
11382 // Even though we are evaluating integer expressions we could get a pointer
11383 // argument for the __builtin_is_aligned() case.
11384 if (SrcTy->isPointerType()) {
11385 LValue Ptr;
11386 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11387 return false;
11388 Ptr.moveInto(Val);
11389 } else if (!SrcTy->isIntegralOrEnumerationType()) {
11390 Info.FFDiag(E->getArg(0));
11391 return false;
11392 } else {
11393 APSInt SrcInt;
11394 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11395 return false;
11396 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11397 "Bit widths must be the same");
11398 Val = APValue(SrcInt);
11399 }
11400 assert(Val.hasValue());
11401 return true;
11402 }
11403
VisitBuiltinCallExpr(const CallExpr * E,unsigned BuiltinOp)11404 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11405 unsigned BuiltinOp) {
11406 switch (BuiltinOp) {
11407 default:
11408 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11409
11410 case Builtin::BI__builtin_dynamic_object_size:
11411 case Builtin::BI__builtin_object_size: {
11412 // The type was checked when we built the expression.
11413 unsigned Type =
11414 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11415 assert(Type <= 3 && "unexpected type");
11416
11417 uint64_t Size;
11418 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11419 return Success(Size, E);
11420
11421 if (E->getArg(0)->HasSideEffects(Info.Ctx))
11422 return Success((Type & 2) ? 0 : -1, E);
11423
11424 // Expression had no side effects, but we couldn't statically determine the
11425 // size of the referenced object.
11426 switch (Info.EvalMode) {
11427 case EvalInfo::EM_ConstantExpression:
11428 case EvalInfo::EM_ConstantFold:
11429 case EvalInfo::EM_IgnoreSideEffects:
11430 // Leave it to IR generation.
11431 return Error(E);
11432 case EvalInfo::EM_ConstantExpressionUnevaluated:
11433 // Reduce it to a constant now.
11434 return Success((Type & 2) ? 0 : -1, E);
11435 }
11436
11437 llvm_unreachable("unexpected EvalMode");
11438 }
11439
11440 case Builtin::BI__builtin_os_log_format_buffer_size: {
11441 analyze_os_log::OSLogBufferLayout Layout;
11442 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11443 return Success(Layout.size().getQuantity(), E);
11444 }
11445
11446 case Builtin::BI__builtin_is_aligned: {
11447 APValue Src;
11448 APSInt Alignment;
11449 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11450 return false;
11451 if (Src.isLValue()) {
11452 // If we evaluated a pointer, check the minimum known alignment.
11453 LValue Ptr;
11454 Ptr.setFrom(Info.Ctx, Src);
11455 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11456 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11457 // We can return true if the known alignment at the computed offset is
11458 // greater than the requested alignment.
11459 assert(PtrAlign.isPowerOfTwo());
11460 assert(Alignment.isPowerOf2());
11461 if (PtrAlign.getQuantity() >= Alignment)
11462 return Success(1, E);
11463 // If the alignment is not known to be sufficient, some cases could still
11464 // be aligned at run time. However, if the requested alignment is less or
11465 // equal to the base alignment and the offset is not aligned, we know that
11466 // the run-time value can never be aligned.
11467 if (BaseAlignment.getQuantity() >= Alignment &&
11468 PtrAlign.getQuantity() < Alignment)
11469 return Success(0, E);
11470 // Otherwise we can't infer whether the value is sufficiently aligned.
11471 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11472 // in cases where we can't fully evaluate the pointer.
11473 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11474 << Alignment;
11475 return false;
11476 }
11477 assert(Src.isInt());
11478 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11479 }
11480 case Builtin::BI__builtin_align_up: {
11481 APValue Src;
11482 APSInt Alignment;
11483 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11484 return false;
11485 if (!Src.isInt())
11486 return Error(E);
11487 APSInt AlignedVal =
11488 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11489 Src.getInt().isUnsigned());
11490 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11491 return Success(AlignedVal, E);
11492 }
11493 case Builtin::BI__builtin_align_down: {
11494 APValue Src;
11495 APSInt Alignment;
11496 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11497 return false;
11498 if (!Src.isInt())
11499 return Error(E);
11500 APSInt AlignedVal =
11501 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11502 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11503 return Success(AlignedVal, E);
11504 }
11505
11506 case Builtin::BI__builtin_bitreverse8:
11507 case Builtin::BI__builtin_bitreverse16:
11508 case Builtin::BI__builtin_bitreverse32:
11509 case Builtin::BI__builtin_bitreverse64: {
11510 APSInt Val;
11511 if (!EvaluateInteger(E->getArg(0), Val, Info))
11512 return false;
11513
11514 return Success(Val.reverseBits(), E);
11515 }
11516
11517 case Builtin::BI__builtin_bswap16:
11518 case Builtin::BI__builtin_bswap32:
11519 case Builtin::BI__builtin_bswap64: {
11520 APSInt Val;
11521 if (!EvaluateInteger(E->getArg(0), Val, Info))
11522 return false;
11523
11524 return Success(Val.byteSwap(), E);
11525 }
11526
11527 case Builtin::BI__builtin_classify_type:
11528 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11529
11530 case Builtin::BI__builtin_clrsb:
11531 case Builtin::BI__builtin_clrsbl:
11532 case Builtin::BI__builtin_clrsbll: {
11533 APSInt Val;
11534 if (!EvaluateInteger(E->getArg(0), Val, Info))
11535 return false;
11536
11537 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11538 }
11539
11540 case Builtin::BI__builtin_clz:
11541 case Builtin::BI__builtin_clzl:
11542 case Builtin::BI__builtin_clzll:
11543 case Builtin::BI__builtin_clzs: {
11544 APSInt Val;
11545 if (!EvaluateInteger(E->getArg(0), Val, Info))
11546 return false;
11547 if (!Val)
11548 return Error(E);
11549
11550 return Success(Val.countLeadingZeros(), E);
11551 }
11552
11553 case Builtin::BI__builtin_constant_p: {
11554 const Expr *Arg = E->getArg(0);
11555 if (EvaluateBuiltinConstantP(Info, Arg))
11556 return Success(true, E);
11557 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11558 // Outside a constant context, eagerly evaluate to false in the presence
11559 // of side-effects in order to avoid -Wunsequenced false-positives in
11560 // a branch on __builtin_constant_p(expr).
11561 return Success(false, E);
11562 }
11563 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11564 return false;
11565 }
11566
11567 case Builtin::BI__builtin_is_constant_evaluated: {
11568 const auto *Callee = Info.CurrentCall->getCallee();
11569 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11570 (Info.CallStackDepth == 1 ||
11571 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11572 Callee->getIdentifier() &&
11573 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11574 // FIXME: Find a better way to avoid duplicated diagnostics.
11575 if (Info.EvalStatus.Diag)
11576 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11577 : Info.CurrentCall->CallLoc,
11578 diag::warn_is_constant_evaluated_always_true_constexpr)
11579 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11580 : "std::is_constant_evaluated");
11581 }
11582
11583 return Success(Info.InConstantContext, E);
11584 }
11585
11586 case Builtin::BI__builtin_ctz:
11587 case Builtin::BI__builtin_ctzl:
11588 case Builtin::BI__builtin_ctzll:
11589 case Builtin::BI__builtin_ctzs: {
11590 APSInt Val;
11591 if (!EvaluateInteger(E->getArg(0), Val, Info))
11592 return false;
11593 if (!Val)
11594 return Error(E);
11595
11596 return Success(Val.countTrailingZeros(), E);
11597 }
11598
11599 case Builtin::BI__builtin_eh_return_data_regno: {
11600 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11601 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11602 return Success(Operand, E);
11603 }
11604
11605 case Builtin::BI__builtin_expect:
11606 case Builtin::BI__builtin_expect_with_probability:
11607 return Visit(E->getArg(0));
11608
11609 case Builtin::BI__builtin_ffs:
11610 case Builtin::BI__builtin_ffsl:
11611 case Builtin::BI__builtin_ffsll: {
11612 APSInt Val;
11613 if (!EvaluateInteger(E->getArg(0), Val, Info))
11614 return false;
11615
11616 unsigned N = Val.countTrailingZeros();
11617 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11618 }
11619
11620 case Builtin::BI__builtin_fpclassify: {
11621 APFloat Val(0.0);
11622 if (!EvaluateFloat(E->getArg(5), Val, Info))
11623 return false;
11624 unsigned Arg;
11625 switch (Val.getCategory()) {
11626 case APFloat::fcNaN: Arg = 0; break;
11627 case APFloat::fcInfinity: Arg = 1; break;
11628 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11629 case APFloat::fcZero: Arg = 4; break;
11630 }
11631 return Visit(E->getArg(Arg));
11632 }
11633
11634 case Builtin::BI__builtin_isinf_sign: {
11635 APFloat Val(0.0);
11636 return EvaluateFloat(E->getArg(0), Val, Info) &&
11637 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11638 }
11639
11640 case Builtin::BI__builtin_isinf: {
11641 APFloat Val(0.0);
11642 return EvaluateFloat(E->getArg(0), Val, Info) &&
11643 Success(Val.isInfinity() ? 1 : 0, E);
11644 }
11645
11646 case Builtin::BI__builtin_isfinite: {
11647 APFloat Val(0.0);
11648 return EvaluateFloat(E->getArg(0), Val, Info) &&
11649 Success(Val.isFinite() ? 1 : 0, E);
11650 }
11651
11652 case Builtin::BI__builtin_isnan: {
11653 APFloat Val(0.0);
11654 return EvaluateFloat(E->getArg(0), Val, Info) &&
11655 Success(Val.isNaN() ? 1 : 0, E);
11656 }
11657
11658 case Builtin::BI__builtin_isnormal: {
11659 APFloat Val(0.0);
11660 return EvaluateFloat(E->getArg(0), Val, Info) &&
11661 Success(Val.isNormal() ? 1 : 0, E);
11662 }
11663
11664 case Builtin::BI__builtin_parity:
11665 case Builtin::BI__builtin_parityl:
11666 case Builtin::BI__builtin_parityll: {
11667 APSInt Val;
11668 if (!EvaluateInteger(E->getArg(0), Val, Info))
11669 return false;
11670
11671 return Success(Val.countPopulation() % 2, E);
11672 }
11673
11674 case Builtin::BI__builtin_popcount:
11675 case Builtin::BI__builtin_popcountl:
11676 case Builtin::BI__builtin_popcountll: {
11677 APSInt Val;
11678 if (!EvaluateInteger(E->getArg(0), Val, Info))
11679 return false;
11680
11681 return Success(Val.countPopulation(), E);
11682 }
11683
11684 case Builtin::BI__builtin_rotateleft8:
11685 case Builtin::BI__builtin_rotateleft16:
11686 case Builtin::BI__builtin_rotateleft32:
11687 case Builtin::BI__builtin_rotateleft64:
11688 case Builtin::BI_rotl8: // Microsoft variants of rotate right
11689 case Builtin::BI_rotl16:
11690 case Builtin::BI_rotl:
11691 case Builtin::BI_lrotl:
11692 case Builtin::BI_rotl64: {
11693 APSInt Val, Amt;
11694 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11695 !EvaluateInteger(E->getArg(1), Amt, Info))
11696 return false;
11697
11698 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
11699 }
11700
11701 case Builtin::BI__builtin_rotateright8:
11702 case Builtin::BI__builtin_rotateright16:
11703 case Builtin::BI__builtin_rotateright32:
11704 case Builtin::BI__builtin_rotateright64:
11705 case Builtin::BI_rotr8: // Microsoft variants of rotate right
11706 case Builtin::BI_rotr16:
11707 case Builtin::BI_rotr:
11708 case Builtin::BI_lrotr:
11709 case Builtin::BI_rotr64: {
11710 APSInt Val, Amt;
11711 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11712 !EvaluateInteger(E->getArg(1), Amt, Info))
11713 return false;
11714
11715 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
11716 }
11717
11718 case Builtin::BIstrlen:
11719 case Builtin::BIwcslen:
11720 // A call to strlen is not a constant expression.
11721 if (Info.getLangOpts().CPlusPlus11)
11722 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11723 << /*isConstexpr*/0 << /*isConstructor*/0
11724 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11725 else
11726 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11727 LLVM_FALLTHROUGH;
11728 case Builtin::BI__builtin_strlen:
11729 case Builtin::BI__builtin_wcslen: {
11730 // As an extension, we support __builtin_strlen() as a constant expression,
11731 // and support folding strlen() to a constant.
11732 LValue String;
11733 if (!EvaluatePointer(E->getArg(0), String, Info))
11734 return false;
11735
11736 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
11737
11738 // Fast path: if it's a string literal, search the string value.
11739 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
11740 String.getLValueBase().dyn_cast<const Expr *>())) {
11741 // The string literal may have embedded null characters. Find the first
11742 // one and truncate there.
11743 StringRef Str = S->getBytes();
11744 int64_t Off = String.Offset.getQuantity();
11745 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
11746 S->getCharByteWidth() == 1 &&
11747 // FIXME: Add fast-path for wchar_t too.
11748 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
11749 Str = Str.substr(Off);
11750
11751 StringRef::size_type Pos = Str.find(0);
11752 if (Pos != StringRef::npos)
11753 Str = Str.substr(0, Pos);
11754
11755 return Success(Str.size(), E);
11756 }
11757
11758 // Fall through to slow path to issue appropriate diagnostic.
11759 }
11760
11761 // Slow path: scan the bytes of the string looking for the terminating 0.
11762 for (uint64_t Strlen = 0; /**/; ++Strlen) {
11763 APValue Char;
11764 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
11765 !Char.isInt())
11766 return false;
11767 if (!Char.getInt())
11768 return Success(Strlen, E);
11769 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
11770 return false;
11771 }
11772 }
11773
11774 case Builtin::BIstrcmp:
11775 case Builtin::BIwcscmp:
11776 case Builtin::BIstrncmp:
11777 case Builtin::BIwcsncmp:
11778 case Builtin::BImemcmp:
11779 case Builtin::BIbcmp:
11780 case Builtin::BIwmemcmp:
11781 // A call to strlen is not a constant expression.
11782 if (Info.getLangOpts().CPlusPlus11)
11783 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11784 << /*isConstexpr*/0 << /*isConstructor*/0
11785 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11786 else
11787 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11788 LLVM_FALLTHROUGH;
11789 case Builtin::BI__builtin_strcmp:
11790 case Builtin::BI__builtin_wcscmp:
11791 case Builtin::BI__builtin_strncmp:
11792 case Builtin::BI__builtin_wcsncmp:
11793 case Builtin::BI__builtin_memcmp:
11794 case Builtin::BI__builtin_bcmp:
11795 case Builtin::BI__builtin_wmemcmp: {
11796 LValue String1, String2;
11797 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11798 !EvaluatePointer(E->getArg(1), String2, Info))
11799 return false;
11800
11801 uint64_t MaxLength = uint64_t(-1);
11802 if (BuiltinOp != Builtin::BIstrcmp &&
11803 BuiltinOp != Builtin::BIwcscmp &&
11804 BuiltinOp != Builtin::BI__builtin_strcmp &&
11805 BuiltinOp != Builtin::BI__builtin_wcscmp) {
11806 APSInt N;
11807 if (!EvaluateInteger(E->getArg(2), N, Info))
11808 return false;
11809 MaxLength = N.getExtValue();
11810 }
11811
11812 // Empty substrings compare equal by definition.
11813 if (MaxLength == 0u)
11814 return Success(0, E);
11815
11816 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11817 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11818 String1.Designator.Invalid || String2.Designator.Invalid)
11819 return false;
11820
11821 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11822 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11823
11824 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11825 BuiltinOp == Builtin::BIbcmp ||
11826 BuiltinOp == Builtin::BI__builtin_memcmp ||
11827 BuiltinOp == Builtin::BI__builtin_bcmp;
11828
11829 assert(IsRawByte ||
11830 (Info.Ctx.hasSameUnqualifiedType(
11831 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11832 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11833
11834 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
11835 // 'char8_t', but no other types.
11836 if (IsRawByte &&
11837 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
11838 // FIXME: Consider using our bit_cast implementation to support this.
11839 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
11840 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
11841 << CharTy1 << CharTy2;
11842 return false;
11843 }
11844
11845 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11846 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11847 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11848 Char1.isInt() && Char2.isInt();
11849 };
11850 const auto &AdvanceElems = [&] {
11851 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11852 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11853 };
11854
11855 bool StopAtNull =
11856 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11857 BuiltinOp != Builtin::BIwmemcmp &&
11858 BuiltinOp != Builtin::BI__builtin_memcmp &&
11859 BuiltinOp != Builtin::BI__builtin_bcmp &&
11860 BuiltinOp != Builtin::BI__builtin_wmemcmp);
11861 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11862 BuiltinOp == Builtin::BIwcsncmp ||
11863 BuiltinOp == Builtin::BIwmemcmp ||
11864 BuiltinOp == Builtin::BI__builtin_wcscmp ||
11865 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11866 BuiltinOp == Builtin::BI__builtin_wmemcmp;
11867
11868 for (; MaxLength; --MaxLength) {
11869 APValue Char1, Char2;
11870 if (!ReadCurElems(Char1, Char2))
11871 return false;
11872 if (Char1.getInt().ne(Char2.getInt())) {
11873 if (IsWide) // wmemcmp compares with wchar_t signedness.
11874 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11875 // memcmp always compares unsigned chars.
11876 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11877 }
11878 if (StopAtNull && !Char1.getInt())
11879 return Success(0, E);
11880 assert(!(StopAtNull && !Char2.getInt()));
11881 if (!AdvanceElems())
11882 return false;
11883 }
11884 // We hit the strncmp / memcmp limit.
11885 return Success(0, E);
11886 }
11887
11888 case Builtin::BI__atomic_always_lock_free:
11889 case Builtin::BI__atomic_is_lock_free:
11890 case Builtin::BI__c11_atomic_is_lock_free: {
11891 APSInt SizeVal;
11892 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11893 return false;
11894
11895 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11896 // of two less than or equal to the maximum inline atomic width, we know it
11897 // is lock-free. If the size isn't a power of two, or greater than the
11898 // maximum alignment where we promote atomics, we know it is not lock-free
11899 // (at least not in the sense of atomic_is_lock_free). Otherwise,
11900 // the answer can only be determined at runtime; for example, 16-byte
11901 // atomics have lock-free implementations on some, but not all,
11902 // x86-64 processors.
11903
11904 // Check power-of-two.
11905 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11906 if (Size.isPowerOfTwo()) {
11907 // Check against inlining width.
11908 unsigned InlineWidthBits =
11909 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11910 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11911 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11912 Size == CharUnits::One() ||
11913 E->getArg(1)->isNullPointerConstant(Info.Ctx,
11914 Expr::NPC_NeverValueDependent))
11915 // OK, we will inline appropriately-aligned operations of this size,
11916 // and _Atomic(T) is appropriately-aligned.
11917 return Success(1, E);
11918
11919 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
11920 castAs<PointerType>()->getPointeeType();
11921 if (!PointeeType->isIncompleteType() &&
11922 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
11923 // OK, we will inline operations on this object.
11924 return Success(1, E);
11925 }
11926 }
11927 }
11928
11929 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
11930 Success(0, E) : Error(E);
11931 }
11932 case Builtin::BIomp_is_initial_device:
11933 // We can decide statically which value the runtime would return if called.
11934 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
11935 case Builtin::BI__builtin_add_overflow:
11936 case Builtin::BI__builtin_sub_overflow:
11937 case Builtin::BI__builtin_mul_overflow:
11938 case Builtin::BI__builtin_sadd_overflow:
11939 case Builtin::BI__builtin_uadd_overflow:
11940 case Builtin::BI__builtin_uaddl_overflow:
11941 case Builtin::BI__builtin_uaddll_overflow:
11942 case Builtin::BI__builtin_usub_overflow:
11943 case Builtin::BI__builtin_usubl_overflow:
11944 case Builtin::BI__builtin_usubll_overflow:
11945 case Builtin::BI__builtin_umul_overflow:
11946 case Builtin::BI__builtin_umull_overflow:
11947 case Builtin::BI__builtin_umulll_overflow:
11948 case Builtin::BI__builtin_saddl_overflow:
11949 case Builtin::BI__builtin_saddll_overflow:
11950 case Builtin::BI__builtin_ssub_overflow:
11951 case Builtin::BI__builtin_ssubl_overflow:
11952 case Builtin::BI__builtin_ssubll_overflow:
11953 case Builtin::BI__builtin_smul_overflow:
11954 case Builtin::BI__builtin_smull_overflow:
11955 case Builtin::BI__builtin_smulll_overflow: {
11956 LValue ResultLValue;
11957 APSInt LHS, RHS;
11958
11959 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
11960 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
11961 !EvaluateInteger(E->getArg(1), RHS, Info) ||
11962 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
11963 return false;
11964
11965 APSInt Result;
11966 bool DidOverflow = false;
11967
11968 // If the types don't have to match, enlarge all 3 to the largest of them.
11969 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11970 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11971 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11972 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
11973 ResultType->isSignedIntegerOrEnumerationType();
11974 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
11975 ResultType->isSignedIntegerOrEnumerationType();
11976 uint64_t LHSSize = LHS.getBitWidth();
11977 uint64_t RHSSize = RHS.getBitWidth();
11978 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
11979 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
11980
11981 // Add an additional bit if the signedness isn't uniformly agreed to. We
11982 // could do this ONLY if there is a signed and an unsigned that both have
11983 // MaxBits, but the code to check that is pretty nasty. The issue will be
11984 // caught in the shrink-to-result later anyway.
11985 if (IsSigned && !AllSigned)
11986 ++MaxBits;
11987
11988 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
11989 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
11990 Result = APSInt(MaxBits, !IsSigned);
11991 }
11992
11993 // Find largest int.
11994 switch (BuiltinOp) {
11995 default:
11996 llvm_unreachable("Invalid value for BuiltinOp");
11997 case Builtin::BI__builtin_add_overflow:
11998 case Builtin::BI__builtin_sadd_overflow:
11999 case Builtin::BI__builtin_saddl_overflow:
12000 case Builtin::BI__builtin_saddll_overflow:
12001 case Builtin::BI__builtin_uadd_overflow:
12002 case Builtin::BI__builtin_uaddl_overflow:
12003 case Builtin::BI__builtin_uaddll_overflow:
12004 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12005 : LHS.uadd_ov(RHS, DidOverflow);
12006 break;
12007 case Builtin::BI__builtin_sub_overflow:
12008 case Builtin::BI__builtin_ssub_overflow:
12009 case Builtin::BI__builtin_ssubl_overflow:
12010 case Builtin::BI__builtin_ssubll_overflow:
12011 case Builtin::BI__builtin_usub_overflow:
12012 case Builtin::BI__builtin_usubl_overflow:
12013 case Builtin::BI__builtin_usubll_overflow:
12014 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12015 : LHS.usub_ov(RHS, DidOverflow);
12016 break;
12017 case Builtin::BI__builtin_mul_overflow:
12018 case Builtin::BI__builtin_smul_overflow:
12019 case Builtin::BI__builtin_smull_overflow:
12020 case Builtin::BI__builtin_smulll_overflow:
12021 case Builtin::BI__builtin_umul_overflow:
12022 case Builtin::BI__builtin_umull_overflow:
12023 case Builtin::BI__builtin_umulll_overflow:
12024 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12025 : LHS.umul_ov(RHS, DidOverflow);
12026 break;
12027 }
12028
12029 // In the case where multiple sizes are allowed, truncate and see if
12030 // the values are the same.
12031 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12032 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12033 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12034 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12035 // since it will give us the behavior of a TruncOrSelf in the case where
12036 // its parameter <= its size. We previously set Result to be at least the
12037 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12038 // will work exactly like TruncOrSelf.
12039 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12040 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12041
12042 if (!APSInt::isSameValue(Temp, Result))
12043 DidOverflow = true;
12044 Result = Temp;
12045 }
12046
12047 APValue APV{Result};
12048 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12049 return false;
12050 return Success(DidOverflow, E);
12051 }
12052 }
12053 }
12054
12055 /// Determine whether this is a pointer past the end of the complete
12056 /// object referred to by the lvalue.
isOnePastTheEndOfCompleteObject(const ASTContext & Ctx,const LValue & LV)12057 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12058 const LValue &LV) {
12059 // A null pointer can be viewed as being "past the end" but we don't
12060 // choose to look at it that way here.
12061 if (!LV.getLValueBase())
12062 return false;
12063
12064 // If the designator is valid and refers to a subobject, we're not pointing
12065 // past the end.
12066 if (!LV.getLValueDesignator().Invalid &&
12067 !LV.getLValueDesignator().isOnePastTheEnd())
12068 return false;
12069
12070 // A pointer to an incomplete type might be past-the-end if the type's size is
12071 // zero. We cannot tell because the type is incomplete.
12072 QualType Ty = getType(LV.getLValueBase());
12073 if (Ty->isIncompleteType())
12074 return true;
12075
12076 // We're a past-the-end pointer if we point to the byte after the object,
12077 // no matter what our type or path is.
12078 auto Size = Ctx.getTypeSizeInChars(Ty);
12079 return LV.getLValueOffset() == Size;
12080 }
12081
12082 namespace {
12083
12084 /// Data recursive integer evaluator of certain binary operators.
12085 ///
12086 /// We use a data recursive algorithm for binary operators so that we are able
12087 /// to handle extreme cases of chained binary operators without causing stack
12088 /// overflow.
12089 class DataRecursiveIntBinOpEvaluator {
12090 struct EvalResult {
12091 APValue Val;
12092 bool Failed;
12093
EvalResult__anon4717f8732811::DataRecursiveIntBinOpEvaluator::EvalResult12094 EvalResult() : Failed(false) { }
12095
swap__anon4717f8732811::DataRecursiveIntBinOpEvaluator::EvalResult12096 void swap(EvalResult &RHS) {
12097 Val.swap(RHS.Val);
12098 Failed = RHS.Failed;
12099 RHS.Failed = false;
12100 }
12101 };
12102
12103 struct Job {
12104 const Expr *E;
12105 EvalResult LHSResult; // meaningful only for binary operator expression.
12106 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12107
12108 Job() = default;
12109 Job(Job &&) = default;
12110
startSpeculativeEval__anon4717f8732811::DataRecursiveIntBinOpEvaluator::Job12111 void startSpeculativeEval(EvalInfo &Info) {
12112 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12113 }
12114
12115 private:
12116 SpeculativeEvaluationRAII SpecEvalRAII;
12117 };
12118
12119 SmallVector<Job, 16> Queue;
12120
12121 IntExprEvaluator &IntEval;
12122 EvalInfo &Info;
12123 APValue &FinalResult;
12124
12125 public:
DataRecursiveIntBinOpEvaluator(IntExprEvaluator & IntEval,APValue & Result)12126 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12127 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12128
12129 /// True if \param E is a binary operator that we are going to handle
12130 /// data recursively.
12131 /// We handle binary operators that are comma, logical, or that have operands
12132 /// with integral or enumeration type.
shouldEnqueue(const BinaryOperator * E)12133 static bool shouldEnqueue(const BinaryOperator *E) {
12134 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12135 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
12136 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12137 E->getRHS()->getType()->isIntegralOrEnumerationType());
12138 }
12139
Traverse(const BinaryOperator * E)12140 bool Traverse(const BinaryOperator *E) {
12141 enqueue(E);
12142 EvalResult PrevResult;
12143 while (!Queue.empty())
12144 process(PrevResult);
12145
12146 if (PrevResult.Failed) return false;
12147
12148 FinalResult.swap(PrevResult.Val);
12149 return true;
12150 }
12151
12152 private:
Success(uint64_t Value,const Expr * E,APValue & Result)12153 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12154 return IntEval.Success(Value, E, Result);
12155 }
Success(const APSInt & Value,const Expr * E,APValue & Result)12156 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12157 return IntEval.Success(Value, E, Result);
12158 }
Error(const Expr * E)12159 bool Error(const Expr *E) {
12160 return IntEval.Error(E);
12161 }
Error(const Expr * E,diag::kind D)12162 bool Error(const Expr *E, diag::kind D) {
12163 return IntEval.Error(E, D);
12164 }
12165
CCEDiag(const Expr * E,diag::kind D)12166 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12167 return Info.CCEDiag(E, D);
12168 }
12169
12170 // Returns true if visiting the RHS is necessary, false otherwise.
12171 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12172 bool &SuppressRHSDiags);
12173
12174 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12175 const BinaryOperator *E, APValue &Result);
12176
EvaluateExpr(const Expr * E,EvalResult & Result)12177 void EvaluateExpr(const Expr *E, EvalResult &Result) {
12178 Result.Failed = !Evaluate(Result.Val, Info, E);
12179 if (Result.Failed)
12180 Result.Val = APValue();
12181 }
12182
12183 void process(EvalResult &Result);
12184
enqueue(const Expr * E)12185 void enqueue(const Expr *E) {
12186 E = E->IgnoreParens();
12187 Queue.resize(Queue.size()+1);
12188 Queue.back().E = E;
12189 Queue.back().Kind = Job::AnyExprKind;
12190 }
12191 };
12192
12193 }
12194
12195 bool DataRecursiveIntBinOpEvaluator::
VisitBinOpLHSOnly(EvalResult & LHSResult,const BinaryOperator * E,bool & SuppressRHSDiags)12196 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12197 bool &SuppressRHSDiags) {
12198 if (E->getOpcode() == BO_Comma) {
12199 // Ignore LHS but note if we could not evaluate it.
12200 if (LHSResult.Failed)
12201 return Info.noteSideEffect();
12202 return true;
12203 }
12204
12205 if (E->isLogicalOp()) {
12206 bool LHSAsBool;
12207 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12208 // We were able to evaluate the LHS, see if we can get away with not
12209 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12210 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12211 Success(LHSAsBool, E, LHSResult.Val);
12212 return false; // Ignore RHS
12213 }
12214 } else {
12215 LHSResult.Failed = true;
12216
12217 // Since we weren't able to evaluate the left hand side, it
12218 // might have had side effects.
12219 if (!Info.noteSideEffect())
12220 return false;
12221
12222 // We can't evaluate the LHS; however, sometimes the result
12223 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12224 // Don't ignore RHS and suppress diagnostics from this arm.
12225 SuppressRHSDiags = true;
12226 }
12227
12228 return true;
12229 }
12230
12231 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12232 E->getRHS()->getType()->isIntegralOrEnumerationType());
12233
12234 if (LHSResult.Failed && !Info.noteFailure())
12235 return false; // Ignore RHS;
12236
12237 return true;
12238 }
12239
addOrSubLValueAsInteger(APValue & LVal,const APSInt & Index,bool IsSub)12240 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12241 bool IsSub) {
12242 // Compute the new offset in the appropriate width, wrapping at 64 bits.
12243 // FIXME: When compiling for a 32-bit target, we should use 32-bit
12244 // offsets.
12245 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12246 CharUnits &Offset = LVal.getLValueOffset();
12247 uint64_t Offset64 = Offset.getQuantity();
12248 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12249 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12250 : Offset64 + Index64);
12251 }
12252
12253 bool DataRecursiveIntBinOpEvaluator::
VisitBinOp(const EvalResult & LHSResult,const EvalResult & RHSResult,const BinaryOperator * E,APValue & Result)12254 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12255 const BinaryOperator *E, APValue &Result) {
12256 if (E->getOpcode() == BO_Comma) {
12257 if (RHSResult.Failed)
12258 return false;
12259 Result = RHSResult.Val;
12260 return true;
12261 }
12262
12263 if (E->isLogicalOp()) {
12264 bool lhsResult, rhsResult;
12265 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12266 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12267
12268 if (LHSIsOK) {
12269 if (RHSIsOK) {
12270 if (E->getOpcode() == BO_LOr)
12271 return Success(lhsResult || rhsResult, E, Result);
12272 else
12273 return Success(lhsResult && rhsResult, E, Result);
12274 }
12275 } else {
12276 if (RHSIsOK) {
12277 // We can't evaluate the LHS; however, sometimes the result
12278 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12279 if (rhsResult == (E->getOpcode() == BO_LOr))
12280 return Success(rhsResult, E, Result);
12281 }
12282 }
12283
12284 return false;
12285 }
12286
12287 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12288 E->getRHS()->getType()->isIntegralOrEnumerationType());
12289
12290 if (LHSResult.Failed || RHSResult.Failed)
12291 return false;
12292
12293 const APValue &LHSVal = LHSResult.Val;
12294 const APValue &RHSVal = RHSResult.Val;
12295
12296 // Handle cases like (unsigned long)&a + 4.
12297 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12298 Result = LHSVal;
12299 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12300 return true;
12301 }
12302
12303 // Handle cases like 4 + (unsigned long)&a
12304 if (E->getOpcode() == BO_Add &&
12305 RHSVal.isLValue() && LHSVal.isInt()) {
12306 Result = RHSVal;
12307 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12308 return true;
12309 }
12310
12311 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12312 // Handle (intptr_t)&&A - (intptr_t)&&B.
12313 if (!LHSVal.getLValueOffset().isZero() ||
12314 !RHSVal.getLValueOffset().isZero())
12315 return false;
12316 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12317 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12318 if (!LHSExpr || !RHSExpr)
12319 return false;
12320 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12321 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12322 if (!LHSAddrExpr || !RHSAddrExpr)
12323 return false;
12324 // Make sure both labels come from the same function.
12325 if (LHSAddrExpr->getLabel()->getDeclContext() !=
12326 RHSAddrExpr->getLabel()->getDeclContext())
12327 return false;
12328 Result = APValue(LHSAddrExpr, RHSAddrExpr);
12329 return true;
12330 }
12331
12332 // All the remaining cases expect both operands to be an integer
12333 if (!LHSVal.isInt() || !RHSVal.isInt())
12334 return Error(E);
12335
12336 // Set up the width and signedness manually, in case it can't be deduced
12337 // from the operation we're performing.
12338 // FIXME: Don't do this in the cases where we can deduce it.
12339 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12340 E->getType()->isUnsignedIntegerOrEnumerationType());
12341 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12342 RHSVal.getInt(), Value))
12343 return false;
12344 return Success(Value, E, Result);
12345 }
12346
process(EvalResult & Result)12347 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12348 Job &job = Queue.back();
12349
12350 switch (job.Kind) {
12351 case Job::AnyExprKind: {
12352 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12353 if (shouldEnqueue(Bop)) {
12354 job.Kind = Job::BinOpKind;
12355 enqueue(Bop->getLHS());
12356 return;
12357 }
12358 }
12359
12360 EvaluateExpr(job.E, Result);
12361 Queue.pop_back();
12362 return;
12363 }
12364
12365 case Job::BinOpKind: {
12366 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12367 bool SuppressRHSDiags = false;
12368 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12369 Queue.pop_back();
12370 return;
12371 }
12372 if (SuppressRHSDiags)
12373 job.startSpeculativeEval(Info);
12374 job.LHSResult.swap(Result);
12375 job.Kind = Job::BinOpVisitedLHSKind;
12376 enqueue(Bop->getRHS());
12377 return;
12378 }
12379
12380 case Job::BinOpVisitedLHSKind: {
12381 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12382 EvalResult RHS;
12383 RHS.swap(Result);
12384 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12385 Queue.pop_back();
12386 return;
12387 }
12388 }
12389
12390 llvm_unreachable("Invalid Job::Kind!");
12391 }
12392
12393 namespace {
12394 /// Used when we determine that we should fail, but can keep evaluating prior to
12395 /// noting that we had a failure.
12396 class DelayedNoteFailureRAII {
12397 EvalInfo &Info;
12398 bool NoteFailure;
12399
12400 public:
DelayedNoteFailureRAII(EvalInfo & Info,bool NoteFailure=true)12401 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
12402 : Info(Info), NoteFailure(NoteFailure) {}
~DelayedNoteFailureRAII()12403 ~DelayedNoteFailureRAII() {
12404 if (NoteFailure) {
12405 bool ContinueAfterFailure = Info.noteFailure();
12406 (void)ContinueAfterFailure;
12407 assert(ContinueAfterFailure &&
12408 "Shouldn't have kept evaluating on failure.");
12409 }
12410 }
12411 };
12412
12413 enum class CmpResult {
12414 Unequal,
12415 Less,
12416 Equal,
12417 Greater,
12418 Unordered,
12419 };
12420 }
12421
12422 template <class SuccessCB, class AfterCB>
12423 static bool
EvaluateComparisonBinaryOperator(EvalInfo & Info,const BinaryOperator * E,SuccessCB && Success,AfterCB && DoAfter)12424 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12425 SuccessCB &&Success, AfterCB &&DoAfter) {
12426 assert(E->isComparisonOp() && "expected comparison operator");
12427 assert((E->getOpcode() == BO_Cmp ||
12428 E->getType()->isIntegralOrEnumerationType()) &&
12429 "unsupported binary expression evaluation");
12430 auto Error = [&](const Expr *E) {
12431 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12432 return false;
12433 };
12434
12435 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12436 bool IsEquality = E->isEqualityOp();
12437
12438 QualType LHSTy = E->getLHS()->getType();
12439 QualType RHSTy = E->getRHS()->getType();
12440
12441 if (LHSTy->isIntegralOrEnumerationType() &&
12442 RHSTy->isIntegralOrEnumerationType()) {
12443 APSInt LHS, RHS;
12444 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12445 if (!LHSOK && !Info.noteFailure())
12446 return false;
12447 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12448 return false;
12449 if (LHS < RHS)
12450 return Success(CmpResult::Less, E);
12451 if (LHS > RHS)
12452 return Success(CmpResult::Greater, E);
12453 return Success(CmpResult::Equal, E);
12454 }
12455
12456 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12457 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12458 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12459
12460 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12461 if (!LHSOK && !Info.noteFailure())
12462 return false;
12463 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12464 return false;
12465 if (LHSFX < RHSFX)
12466 return Success(CmpResult::Less, E);
12467 if (LHSFX > RHSFX)
12468 return Success(CmpResult::Greater, E);
12469 return Success(CmpResult::Equal, E);
12470 }
12471
12472 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12473 ComplexValue LHS, RHS;
12474 bool LHSOK;
12475 if (E->isAssignmentOp()) {
12476 LValue LV;
12477 EvaluateLValue(E->getLHS(), LV, Info);
12478 LHSOK = false;
12479 } else if (LHSTy->isRealFloatingType()) {
12480 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12481 if (LHSOK) {
12482 LHS.makeComplexFloat();
12483 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12484 }
12485 } else {
12486 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12487 }
12488 if (!LHSOK && !Info.noteFailure())
12489 return false;
12490
12491 if (E->getRHS()->getType()->isRealFloatingType()) {
12492 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12493 return false;
12494 RHS.makeComplexFloat();
12495 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12496 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12497 return false;
12498
12499 if (LHS.isComplexFloat()) {
12500 APFloat::cmpResult CR_r =
12501 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12502 APFloat::cmpResult CR_i =
12503 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12504 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12505 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12506 } else {
12507 assert(IsEquality && "invalid complex comparison");
12508 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12509 LHS.getComplexIntImag() == RHS.getComplexIntImag();
12510 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12511 }
12512 }
12513
12514 if (LHSTy->isRealFloatingType() &&
12515 RHSTy->isRealFloatingType()) {
12516 APFloat RHS(0.0), LHS(0.0);
12517
12518 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12519 if (!LHSOK && !Info.noteFailure())
12520 return false;
12521
12522 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12523 return false;
12524
12525 assert(E->isComparisonOp() && "Invalid binary operator!");
12526 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12527 if (!Info.InConstantContext &&
12528 APFloatCmpResult == APFloat::cmpUnordered &&
12529 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12530 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12531 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12532 return false;
12533 }
12534 auto GetCmpRes = [&]() {
12535 switch (APFloatCmpResult) {
12536 case APFloat::cmpEqual:
12537 return CmpResult::Equal;
12538 case APFloat::cmpLessThan:
12539 return CmpResult::Less;
12540 case APFloat::cmpGreaterThan:
12541 return CmpResult::Greater;
12542 case APFloat::cmpUnordered:
12543 return CmpResult::Unordered;
12544 }
12545 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12546 };
12547 return Success(GetCmpRes(), E);
12548 }
12549
12550 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12551 LValue LHSValue, RHSValue;
12552
12553 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12554 if (!LHSOK && !Info.noteFailure())
12555 return false;
12556
12557 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12558 return false;
12559
12560 // Reject differing bases from the normal codepath; we special-case
12561 // comparisons to null.
12562 if (!HasSameBase(LHSValue, RHSValue)) {
12563 // Inequalities and subtractions between unrelated pointers have
12564 // unspecified or undefined behavior.
12565 if (!IsEquality) {
12566 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12567 return false;
12568 }
12569 // A constant address may compare equal to the address of a symbol.
12570 // The one exception is that address of an object cannot compare equal
12571 // to a null pointer constant.
12572 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12573 (!RHSValue.Base && !RHSValue.Offset.isZero()))
12574 return Error(E);
12575 // It's implementation-defined whether distinct literals will have
12576 // distinct addresses. In clang, the result of such a comparison is
12577 // unspecified, so it is not a constant expression. However, we do know
12578 // that the address of a literal will be non-null.
12579 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12580 LHSValue.Base && RHSValue.Base)
12581 return Error(E);
12582 // We can't tell whether weak symbols will end up pointing to the same
12583 // object.
12584 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12585 return Error(E);
12586 // We can't compare the address of the start of one object with the
12587 // past-the-end address of another object, per C++ DR1652.
12588 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12589 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12590 (RHSValue.Base && RHSValue.Offset.isZero() &&
12591 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12592 return Error(E);
12593 // We can't tell whether an object is at the same address as another
12594 // zero sized object.
12595 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12596 (LHSValue.Base && isZeroSized(RHSValue)))
12597 return Error(E);
12598 return Success(CmpResult::Unequal, E);
12599 }
12600
12601 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12602 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12603
12604 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12605 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12606
12607 // C++11 [expr.rel]p3:
12608 // Pointers to void (after pointer conversions) can be compared, with a
12609 // result defined as follows: If both pointers represent the same
12610 // address or are both the null pointer value, the result is true if the
12611 // operator is <= or >= and false otherwise; otherwise the result is
12612 // unspecified.
12613 // We interpret this as applying to pointers to *cv* void.
12614 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12615 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12616
12617 // C++11 [expr.rel]p2:
12618 // - If two pointers point to non-static data members of the same object,
12619 // or to subobjects or array elements fo such members, recursively, the
12620 // pointer to the later declared member compares greater provided the
12621 // two members have the same access control and provided their class is
12622 // not a union.
12623 // [...]
12624 // - Otherwise pointer comparisons are unspecified.
12625 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12626 bool WasArrayIndex;
12627 unsigned Mismatch = FindDesignatorMismatch(
12628 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12629 // At the point where the designators diverge, the comparison has a
12630 // specified value if:
12631 // - we are comparing array indices
12632 // - we are comparing fields of a union, or fields with the same access
12633 // Otherwise, the result is unspecified and thus the comparison is not a
12634 // constant expression.
12635 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12636 Mismatch < RHSDesignator.Entries.size()) {
12637 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12638 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12639 if (!LF && !RF)
12640 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12641 else if (!LF)
12642 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12643 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12644 << RF->getParent() << RF;
12645 else if (!RF)
12646 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12647 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12648 << LF->getParent() << LF;
12649 else if (!LF->getParent()->isUnion() &&
12650 LF->getAccess() != RF->getAccess())
12651 Info.CCEDiag(E,
12652 diag::note_constexpr_pointer_comparison_differing_access)
12653 << LF << LF->getAccess() << RF << RF->getAccess()
12654 << LF->getParent();
12655 }
12656 }
12657
12658 // The comparison here must be unsigned, and performed with the same
12659 // width as the pointer.
12660 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12661 uint64_t CompareLHS = LHSOffset.getQuantity();
12662 uint64_t CompareRHS = RHSOffset.getQuantity();
12663 assert(PtrSize <= 64 && "Unexpected pointer width");
12664 uint64_t Mask = ~0ULL >> (64 - PtrSize);
12665 CompareLHS &= Mask;
12666 CompareRHS &= Mask;
12667
12668 // If there is a base and this is a relational operator, we can only
12669 // compare pointers within the object in question; otherwise, the result
12670 // depends on where the object is located in memory.
12671 if (!LHSValue.Base.isNull() && IsRelational) {
12672 QualType BaseTy = getType(LHSValue.Base);
12673 if (BaseTy->isIncompleteType())
12674 return Error(E);
12675 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12676 uint64_t OffsetLimit = Size.getQuantity();
12677 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12678 return Error(E);
12679 }
12680
12681 if (CompareLHS < CompareRHS)
12682 return Success(CmpResult::Less, E);
12683 if (CompareLHS > CompareRHS)
12684 return Success(CmpResult::Greater, E);
12685 return Success(CmpResult::Equal, E);
12686 }
12687
12688 if (LHSTy->isMemberPointerType()) {
12689 assert(IsEquality && "unexpected member pointer operation");
12690 assert(RHSTy->isMemberPointerType() && "invalid comparison");
12691
12692 MemberPtr LHSValue, RHSValue;
12693
12694 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12695 if (!LHSOK && !Info.noteFailure())
12696 return false;
12697
12698 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12699 return false;
12700
12701 // C++11 [expr.eq]p2:
12702 // If both operands are null, they compare equal. Otherwise if only one is
12703 // null, they compare unequal.
12704 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12705 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12706 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12707 }
12708
12709 // Otherwise if either is a pointer to a virtual member function, the
12710 // result is unspecified.
12711 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12712 if (MD->isVirtual())
12713 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12714 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12715 if (MD->isVirtual())
12716 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12717
12718 // Otherwise they compare equal if and only if they would refer to the
12719 // same member of the same most derived object or the same subobject if
12720 // they were dereferenced with a hypothetical object of the associated
12721 // class type.
12722 bool Equal = LHSValue == RHSValue;
12723 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12724 }
12725
12726 if (LHSTy->isNullPtrType()) {
12727 assert(E->isComparisonOp() && "unexpected nullptr operation");
12728 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12729 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12730 // are compared, the result is true of the operator is <=, >= or ==, and
12731 // false otherwise.
12732 return Success(CmpResult::Equal, E);
12733 }
12734
12735 return DoAfter();
12736 }
12737
VisitBinCmp(const BinaryOperator * E)12738 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12739 if (!CheckLiteralType(Info, E))
12740 return false;
12741
12742 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12743 ComparisonCategoryResult CCR;
12744 switch (CR) {
12745 case CmpResult::Unequal:
12746 llvm_unreachable("should never produce Unequal for three-way comparison");
12747 case CmpResult::Less:
12748 CCR = ComparisonCategoryResult::Less;
12749 break;
12750 case CmpResult::Equal:
12751 CCR = ComparisonCategoryResult::Equal;
12752 break;
12753 case CmpResult::Greater:
12754 CCR = ComparisonCategoryResult::Greater;
12755 break;
12756 case CmpResult::Unordered:
12757 CCR = ComparisonCategoryResult::Unordered;
12758 break;
12759 }
12760 // Evaluation succeeded. Lookup the information for the comparison category
12761 // type and fetch the VarDecl for the result.
12762 const ComparisonCategoryInfo &CmpInfo =
12763 Info.Ctx.CompCategories.getInfoForType(E->getType());
12764 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12765 // Check and evaluate the result as a constant expression.
12766 LValue LV;
12767 LV.set(VD);
12768 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12769 return false;
12770 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
12771 ConstantExprKind::Normal);
12772 };
12773 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12774 return ExprEvaluatorBaseTy::VisitBinCmp(E);
12775 });
12776 }
12777
VisitBinaryOperator(const BinaryOperator * E)12778 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12779 // We don't call noteFailure immediately because the assignment happens after
12780 // we evaluate LHS and RHS.
12781 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
12782 return Error(E);
12783
12784 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
12785 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12786 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12787
12788 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12789 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12790 "DataRecursiveIntBinOpEvaluator should have handled integral types");
12791
12792 if (E->isComparisonOp()) {
12793 // Evaluate builtin binary comparisons by evaluating them as three-way
12794 // comparisons and then translating the result.
12795 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12796 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12797 "should only produce Unequal for equality comparisons");
12798 bool IsEqual = CR == CmpResult::Equal,
12799 IsLess = CR == CmpResult::Less,
12800 IsGreater = CR == CmpResult::Greater;
12801 auto Op = E->getOpcode();
12802 switch (Op) {
12803 default:
12804 llvm_unreachable("unsupported binary operator");
12805 case BO_EQ:
12806 case BO_NE:
12807 return Success(IsEqual == (Op == BO_EQ), E);
12808 case BO_LT:
12809 return Success(IsLess, E);
12810 case BO_GT:
12811 return Success(IsGreater, E);
12812 case BO_LE:
12813 return Success(IsEqual || IsLess, E);
12814 case BO_GE:
12815 return Success(IsEqual || IsGreater, E);
12816 }
12817 };
12818 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12819 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12820 });
12821 }
12822
12823 QualType LHSTy = E->getLHS()->getType();
12824 QualType RHSTy = E->getRHS()->getType();
12825
12826 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12827 E->getOpcode() == BO_Sub) {
12828 LValue LHSValue, RHSValue;
12829
12830 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12831 if (!LHSOK && !Info.noteFailure())
12832 return false;
12833
12834 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12835 return false;
12836
12837 // Reject differing bases from the normal codepath; we special-case
12838 // comparisons to null.
12839 if (!HasSameBase(LHSValue, RHSValue)) {
12840 // Handle &&A - &&B.
12841 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12842 return Error(E);
12843 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12844 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12845 if (!LHSExpr || !RHSExpr)
12846 return Error(E);
12847 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12848 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12849 if (!LHSAddrExpr || !RHSAddrExpr)
12850 return Error(E);
12851 // Make sure both labels come from the same function.
12852 if (LHSAddrExpr->getLabel()->getDeclContext() !=
12853 RHSAddrExpr->getLabel()->getDeclContext())
12854 return Error(E);
12855 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12856 }
12857 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12858 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12859
12860 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12861 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12862
12863 // C++11 [expr.add]p6:
12864 // Unless both pointers point to elements of the same array object, or
12865 // one past the last element of the array object, the behavior is
12866 // undefined.
12867 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12868 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12869 RHSDesignator))
12870 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12871
12872 QualType Type = E->getLHS()->getType();
12873 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12874
12875 CharUnits ElementSize;
12876 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12877 return false;
12878
12879 // As an extension, a type may have zero size (empty struct or union in
12880 // C, array of zero length). Pointer subtraction in such cases has
12881 // undefined behavior, so is not constant.
12882 if (ElementSize.isZero()) {
12883 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12884 << ElementType;
12885 return false;
12886 }
12887
12888 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12889 // and produce incorrect results when it overflows. Such behavior
12890 // appears to be non-conforming, but is common, so perhaps we should
12891 // assume the standard intended for such cases to be undefined behavior
12892 // and check for them.
12893
12894 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12895 // overflow in the final conversion to ptrdiff_t.
12896 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12897 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12898 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12899 false);
12900 APSInt TrueResult = (LHS - RHS) / ElemSize;
12901 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12902
12903 if (Result.extend(65) != TrueResult &&
12904 !HandleOverflow(Info, E, TrueResult, E->getType()))
12905 return false;
12906 return Success(Result, E);
12907 }
12908
12909 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12910 }
12911
12912 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12913 /// a result as the expression's type.
VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr * E)12914 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12915 const UnaryExprOrTypeTraitExpr *E) {
12916 switch(E->getKind()) {
12917 case UETT_PreferredAlignOf:
12918 case UETT_AlignOf: {
12919 if (E->isArgumentType())
12920 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12921 E);
12922 else
12923 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12924 E);
12925 }
12926
12927 case UETT_VecStep: {
12928 QualType Ty = E->getTypeOfArgument();
12929
12930 if (Ty->isVectorType()) {
12931 unsigned n = Ty->castAs<VectorType>()->getNumElements();
12932
12933 // The vec_step built-in functions that take a 3-component
12934 // vector return 4. (OpenCL 1.1 spec 6.11.12)
12935 if (n == 3)
12936 n = 4;
12937
12938 return Success(n, E);
12939 } else
12940 return Success(1, E);
12941 }
12942
12943 case UETT_SizeOf: {
12944 QualType SrcTy = E->getTypeOfArgument();
12945 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
12946 // the result is the size of the referenced type."
12947 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
12948 SrcTy = Ref->getPointeeType();
12949
12950 CharUnits Sizeof;
12951 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
12952 return false;
12953 return Success(Sizeof, E);
12954 }
12955 case UETT_OpenMPRequiredSimdAlign:
12956 assert(E->isArgumentType());
12957 return Success(
12958 Info.Ctx.toCharUnitsFromBits(
12959 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
12960 .getQuantity(),
12961 E);
12962 }
12963
12964 llvm_unreachable("unknown expr/type trait");
12965 }
12966
VisitOffsetOfExpr(const OffsetOfExpr * OOE)12967 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
12968 CharUnits Result;
12969 unsigned n = OOE->getNumComponents();
12970 if (n == 0)
12971 return Error(OOE);
12972 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
12973 for (unsigned i = 0; i != n; ++i) {
12974 OffsetOfNode ON = OOE->getComponent(i);
12975 switch (ON.getKind()) {
12976 case OffsetOfNode::Array: {
12977 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
12978 APSInt IdxResult;
12979 if (!EvaluateInteger(Idx, IdxResult, Info))
12980 return false;
12981 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
12982 if (!AT)
12983 return Error(OOE);
12984 CurrentType = AT->getElementType();
12985 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
12986 Result += IdxResult.getSExtValue() * ElementSize;
12987 break;
12988 }
12989
12990 case OffsetOfNode::Field: {
12991 FieldDecl *MemberDecl = ON.getField();
12992 const RecordType *RT = CurrentType->getAs<RecordType>();
12993 if (!RT)
12994 return Error(OOE);
12995 RecordDecl *RD = RT->getDecl();
12996 if (RD->isInvalidDecl()) return false;
12997 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12998 unsigned i = MemberDecl->getFieldIndex();
12999 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13000 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13001 CurrentType = MemberDecl->getType().getNonReferenceType();
13002 break;
13003 }
13004
13005 case OffsetOfNode::Identifier:
13006 llvm_unreachable("dependent __builtin_offsetof");
13007
13008 case OffsetOfNode::Base: {
13009 CXXBaseSpecifier *BaseSpec = ON.getBase();
13010 if (BaseSpec->isVirtual())
13011 return Error(OOE);
13012
13013 // Find the layout of the class whose base we are looking into.
13014 const RecordType *RT = CurrentType->getAs<RecordType>();
13015 if (!RT)
13016 return Error(OOE);
13017 RecordDecl *RD = RT->getDecl();
13018 if (RD->isInvalidDecl()) return false;
13019 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13020
13021 // Find the base class itself.
13022 CurrentType = BaseSpec->getType();
13023 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13024 if (!BaseRT)
13025 return Error(OOE);
13026
13027 // Add the offset to the base.
13028 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13029 break;
13030 }
13031 }
13032 }
13033 return Success(Result, OOE);
13034 }
13035
VisitUnaryOperator(const UnaryOperator * E)13036 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13037 switch (E->getOpcode()) {
13038 default:
13039 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13040 // See C99 6.6p3.
13041 return Error(E);
13042 case UO_Extension:
13043 // FIXME: Should extension allow i-c-e extension expressions in its scope?
13044 // If so, we could clear the diagnostic ID.
13045 return Visit(E->getSubExpr());
13046 case UO_Plus:
13047 // The result is just the value.
13048 return Visit(E->getSubExpr());
13049 case UO_Minus: {
13050 if (!Visit(E->getSubExpr()))
13051 return false;
13052 if (!Result.isInt()) return Error(E);
13053 const APSInt &Value = Result.getInt();
13054 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13055 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13056 E->getType()))
13057 return false;
13058 return Success(-Value, E);
13059 }
13060 case UO_Not: {
13061 if (!Visit(E->getSubExpr()))
13062 return false;
13063 if (!Result.isInt()) return Error(E);
13064 return Success(~Result.getInt(), E);
13065 }
13066 case UO_LNot: {
13067 bool bres;
13068 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13069 return false;
13070 return Success(!bres, E);
13071 }
13072 }
13073 }
13074
13075 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13076 /// result type is integer.
VisitCastExpr(const CastExpr * E)13077 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13078 const Expr *SubExpr = E->getSubExpr();
13079 QualType DestType = E->getType();
13080 QualType SrcType = SubExpr->getType();
13081
13082 switch (E->getCastKind()) {
13083 case CK_BaseToDerived:
13084 case CK_DerivedToBase:
13085 case CK_UncheckedDerivedToBase:
13086 case CK_Dynamic:
13087 case CK_ToUnion:
13088 case CK_ArrayToPointerDecay:
13089 case CK_FunctionToPointerDecay:
13090 case CK_NullToPointer:
13091 case CK_NullToMemberPointer:
13092 case CK_BaseToDerivedMemberPointer:
13093 case CK_DerivedToBaseMemberPointer:
13094 case CK_ReinterpretMemberPointer:
13095 case CK_ConstructorConversion:
13096 case CK_IntegralToPointer:
13097 case CK_ToVoid:
13098 case CK_VectorSplat:
13099 case CK_IntegralToFloating:
13100 case CK_FloatingCast:
13101 case CK_CPointerToObjCPointerCast:
13102 case CK_BlockPointerToObjCPointerCast:
13103 case CK_AnyPointerToBlockPointerCast:
13104 case CK_ObjCObjectLValueCast:
13105 case CK_FloatingRealToComplex:
13106 case CK_FloatingComplexToReal:
13107 case CK_FloatingComplexCast:
13108 case CK_FloatingComplexToIntegralComplex:
13109 case CK_IntegralRealToComplex:
13110 case CK_IntegralComplexCast:
13111 case CK_IntegralComplexToFloatingComplex:
13112 case CK_BuiltinFnToFnPtr:
13113 case CK_ZeroToOCLOpaqueType:
13114 case CK_NonAtomicToAtomic:
13115 case CK_AddressSpaceConversion:
13116 case CK_IntToOCLSampler:
13117 case CK_FloatingToFixedPoint:
13118 case CK_FixedPointToFloating:
13119 case CK_FixedPointCast:
13120 case CK_IntegralToFixedPoint:
13121 llvm_unreachable("invalid cast kind for integral value");
13122
13123 case CK_BitCast:
13124 case CK_Dependent:
13125 case CK_LValueBitCast:
13126 case CK_ARCProduceObject:
13127 case CK_ARCConsumeObject:
13128 case CK_ARCReclaimReturnedObject:
13129 case CK_ARCExtendBlockObject:
13130 case CK_CopyAndAutoreleaseBlockObject:
13131 return Error(E);
13132
13133 case CK_UserDefinedConversion:
13134 case CK_LValueToRValue:
13135 case CK_AtomicToNonAtomic:
13136 case CK_NoOp:
13137 case CK_LValueToRValueBitCast:
13138 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13139
13140 case CK_MemberPointerToBoolean:
13141 case CK_PointerToBoolean:
13142 case CK_IntegralToBoolean:
13143 case CK_FloatingToBoolean:
13144 case CK_BooleanToSignedIntegral:
13145 case CK_FloatingComplexToBoolean:
13146 case CK_IntegralComplexToBoolean: {
13147 bool BoolResult;
13148 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13149 return false;
13150 uint64_t IntResult = BoolResult;
13151 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13152 IntResult = (uint64_t)-1;
13153 return Success(IntResult, E);
13154 }
13155
13156 case CK_FixedPointToIntegral: {
13157 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13158 if (!EvaluateFixedPoint(SubExpr, Src, Info))
13159 return false;
13160 bool Overflowed;
13161 llvm::APSInt Result = Src.convertToInt(
13162 Info.Ctx.getIntWidth(DestType),
13163 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13164 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13165 return false;
13166 return Success(Result, E);
13167 }
13168
13169 case CK_FixedPointToBoolean: {
13170 // Unsigned padding does not affect this.
13171 APValue Val;
13172 if (!Evaluate(Val, Info, SubExpr))
13173 return false;
13174 return Success(Val.getFixedPoint().getBoolValue(), E);
13175 }
13176
13177 case CK_IntegralCast: {
13178 if (!Visit(SubExpr))
13179 return false;
13180
13181 if (!Result.isInt()) {
13182 // Allow casts of address-of-label differences if they are no-ops
13183 // or narrowing. (The narrowing case isn't actually guaranteed to
13184 // be constant-evaluatable except in some narrow cases which are hard
13185 // to detect here. We let it through on the assumption the user knows
13186 // what they are doing.)
13187 if (Result.isAddrLabelDiff())
13188 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13189 // Only allow casts of lvalues if they are lossless.
13190 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13191 }
13192
13193 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13194 Result.getInt()), E);
13195 }
13196
13197 case CK_PointerToIntegral: {
13198 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13199
13200 LValue LV;
13201 if (!EvaluatePointer(SubExpr, LV, Info))
13202 return false;
13203
13204 if (LV.getLValueBase()) {
13205 // Only allow based lvalue casts if they are lossless.
13206 // FIXME: Allow a larger integer size than the pointer size, and allow
13207 // narrowing back down to pointer width in subsequent integral casts.
13208 // FIXME: Check integer type's active bits, not its type size.
13209 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13210 return Error(E);
13211
13212 LV.Designator.setInvalid();
13213 LV.moveInto(Result);
13214 return true;
13215 }
13216
13217 APSInt AsInt;
13218 APValue V;
13219 LV.moveInto(V);
13220 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13221 llvm_unreachable("Can't cast this!");
13222
13223 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13224 }
13225
13226 case CK_IntegralComplexToReal: {
13227 ComplexValue C;
13228 if (!EvaluateComplex(SubExpr, C, Info))
13229 return false;
13230 return Success(C.getComplexIntReal(), E);
13231 }
13232
13233 case CK_FloatingToIntegral: {
13234 APFloat F(0.0);
13235 if (!EvaluateFloat(SubExpr, F, Info))
13236 return false;
13237
13238 APSInt Value;
13239 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13240 return false;
13241 return Success(Value, E);
13242 }
13243 }
13244
13245 llvm_unreachable("unknown cast resulting in integral value");
13246 }
13247
VisitUnaryReal(const UnaryOperator * E)13248 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13249 if (E->getSubExpr()->getType()->isAnyComplexType()) {
13250 ComplexValue LV;
13251 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13252 return false;
13253 if (!LV.isComplexInt())
13254 return Error(E);
13255 return Success(LV.getComplexIntReal(), E);
13256 }
13257
13258 return Visit(E->getSubExpr());
13259 }
13260
VisitUnaryImag(const UnaryOperator * E)13261 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13262 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13263 ComplexValue LV;
13264 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13265 return false;
13266 if (!LV.isComplexInt())
13267 return Error(E);
13268 return Success(LV.getComplexIntImag(), E);
13269 }
13270
13271 VisitIgnoredValue(E->getSubExpr());
13272 return Success(0, E);
13273 }
13274
VisitSizeOfPackExpr(const SizeOfPackExpr * E)13275 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13276 return Success(E->getPackLength(), E);
13277 }
13278
VisitCXXNoexceptExpr(const CXXNoexceptExpr * E)13279 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13280 return Success(E->getValue(), E);
13281 }
13282
VisitConceptSpecializationExpr(const ConceptSpecializationExpr * E)13283 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13284 const ConceptSpecializationExpr *E) {
13285 return Success(E->isSatisfied(), E);
13286 }
13287
VisitRequiresExpr(const RequiresExpr * E)13288 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13289 return Success(E->isSatisfied(), E);
13290 }
13291
VisitUnaryOperator(const UnaryOperator * E)13292 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13293 switch (E->getOpcode()) {
13294 default:
13295 // Invalid unary operators
13296 return Error(E);
13297 case UO_Plus:
13298 // The result is just the value.
13299 return Visit(E->getSubExpr());
13300 case UO_Minus: {
13301 if (!Visit(E->getSubExpr())) return false;
13302 if (!Result.isFixedPoint())
13303 return Error(E);
13304 bool Overflowed;
13305 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13306 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13307 return false;
13308 return Success(Negated, E);
13309 }
13310 case UO_LNot: {
13311 bool bres;
13312 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13313 return false;
13314 return Success(!bres, E);
13315 }
13316 }
13317 }
13318
VisitCastExpr(const CastExpr * E)13319 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13320 const Expr *SubExpr = E->getSubExpr();
13321 QualType DestType = E->getType();
13322 assert(DestType->isFixedPointType() &&
13323 "Expected destination type to be a fixed point type");
13324 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13325
13326 switch (E->getCastKind()) {
13327 case CK_FixedPointCast: {
13328 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13329 if (!EvaluateFixedPoint(SubExpr, Src, Info))
13330 return false;
13331 bool Overflowed;
13332 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13333 if (Overflowed) {
13334 if (Info.checkingForUndefinedBehavior())
13335 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13336 diag::warn_fixedpoint_constant_overflow)
13337 << Result.toString() << E->getType();
13338 else if (!HandleOverflow(Info, E, Result, E->getType()))
13339 return false;
13340 }
13341 return Success(Result, E);
13342 }
13343 case CK_IntegralToFixedPoint: {
13344 APSInt Src;
13345 if (!EvaluateInteger(SubExpr, Src, Info))
13346 return false;
13347
13348 bool Overflowed;
13349 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13350 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13351
13352 if (Overflowed) {
13353 if (Info.checkingForUndefinedBehavior())
13354 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13355 diag::warn_fixedpoint_constant_overflow)
13356 << IntResult.toString() << E->getType();
13357 else if (!HandleOverflow(Info, E, IntResult, E->getType()))
13358 return false;
13359 }
13360
13361 return Success(IntResult, E);
13362 }
13363 case CK_FloatingToFixedPoint: {
13364 APFloat Src(0.0);
13365 if (!EvaluateFloat(SubExpr, Src, Info))
13366 return false;
13367
13368 bool Overflowed;
13369 APFixedPoint Result = APFixedPoint::getFromFloatValue(
13370 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13371
13372 if (Overflowed) {
13373 if (Info.checkingForUndefinedBehavior())
13374 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13375 diag::warn_fixedpoint_constant_overflow)
13376 << Result.toString() << E->getType();
13377 else if (!HandleOverflow(Info, E, Result, E->getType()))
13378 return false;
13379 }
13380
13381 return Success(Result, E);
13382 }
13383 case CK_NoOp:
13384 case CK_LValueToRValue:
13385 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13386 default:
13387 return Error(E);
13388 }
13389 }
13390
VisitBinaryOperator(const BinaryOperator * E)13391 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13392 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13393 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13394
13395 const Expr *LHS = E->getLHS();
13396 const Expr *RHS = E->getRHS();
13397 FixedPointSemantics ResultFXSema =
13398 Info.Ctx.getFixedPointSemantics(E->getType());
13399
13400 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13401 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13402 return false;
13403 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13404 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13405 return false;
13406
13407 bool OpOverflow = false, ConversionOverflow = false;
13408 APFixedPoint Result(LHSFX.getSemantics());
13409 switch (E->getOpcode()) {
13410 case BO_Add: {
13411 Result = LHSFX.add(RHSFX, &OpOverflow)
13412 .convert(ResultFXSema, &ConversionOverflow);
13413 break;
13414 }
13415 case BO_Sub: {
13416 Result = LHSFX.sub(RHSFX, &OpOverflow)
13417 .convert(ResultFXSema, &ConversionOverflow);
13418 break;
13419 }
13420 case BO_Mul: {
13421 Result = LHSFX.mul(RHSFX, &OpOverflow)
13422 .convert(ResultFXSema, &ConversionOverflow);
13423 break;
13424 }
13425 case BO_Div: {
13426 if (RHSFX.getValue() == 0) {
13427 Info.FFDiag(E, diag::note_expr_divide_by_zero);
13428 return false;
13429 }
13430 Result = LHSFX.div(RHSFX, &OpOverflow)
13431 .convert(ResultFXSema, &ConversionOverflow);
13432 break;
13433 }
13434 case BO_Shl:
13435 case BO_Shr: {
13436 FixedPointSemantics LHSSema = LHSFX.getSemantics();
13437 llvm::APSInt RHSVal = RHSFX.getValue();
13438
13439 unsigned ShiftBW =
13440 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13441 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13442 // Embedded-C 4.1.6.2.2:
13443 // The right operand must be nonnegative and less than the total number
13444 // of (nonpadding) bits of the fixed-point operand ...
13445 if (RHSVal.isNegative())
13446 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13447 else if (Amt != RHSVal)
13448 Info.CCEDiag(E, diag::note_constexpr_large_shift)
13449 << RHSVal << E->getType() << ShiftBW;
13450
13451 if (E->getOpcode() == BO_Shl)
13452 Result = LHSFX.shl(Amt, &OpOverflow);
13453 else
13454 Result = LHSFX.shr(Amt, &OpOverflow);
13455 break;
13456 }
13457 default:
13458 return false;
13459 }
13460 if (OpOverflow || ConversionOverflow) {
13461 if (Info.checkingForUndefinedBehavior())
13462 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13463 diag::warn_fixedpoint_constant_overflow)
13464 << Result.toString() << E->getType();
13465 else if (!HandleOverflow(Info, E, Result, E->getType()))
13466 return false;
13467 }
13468 return Success(Result, E);
13469 }
13470
13471 //===----------------------------------------------------------------------===//
13472 // Float Evaluation
13473 //===----------------------------------------------------------------------===//
13474
13475 namespace {
13476 class FloatExprEvaluator
13477 : public ExprEvaluatorBase<FloatExprEvaluator> {
13478 APFloat &Result;
13479 public:
FloatExprEvaluator(EvalInfo & info,APFloat & result)13480 FloatExprEvaluator(EvalInfo &info, APFloat &result)
13481 : ExprEvaluatorBaseTy(info), Result(result) {}
13482
Success(const APValue & V,const Expr * e)13483 bool Success(const APValue &V, const Expr *e) {
13484 Result = V.getFloat();
13485 return true;
13486 }
13487
ZeroInitialization(const Expr * E)13488 bool ZeroInitialization(const Expr *E) {
13489 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13490 return true;
13491 }
13492
13493 bool VisitCallExpr(const CallExpr *E);
13494
13495 bool VisitUnaryOperator(const UnaryOperator *E);
13496 bool VisitBinaryOperator(const BinaryOperator *E);
13497 bool VisitFloatingLiteral(const FloatingLiteral *E);
13498 bool VisitCastExpr(const CastExpr *E);
13499
13500 bool VisitUnaryReal(const UnaryOperator *E);
13501 bool VisitUnaryImag(const UnaryOperator *E);
13502
13503 // FIXME: Missing: array subscript of vector, member of vector
13504 };
13505 } // end anonymous namespace
13506
EvaluateFloat(const Expr * E,APFloat & Result,EvalInfo & Info)13507 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13508 assert(E->isRValue() && E->getType()->isRealFloatingType());
13509 return FloatExprEvaluator(Info, Result).Visit(E);
13510 }
13511
TryEvaluateBuiltinNaN(const ASTContext & Context,QualType ResultTy,const Expr * Arg,bool SNaN,llvm::APFloat & Result)13512 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13513 QualType ResultTy,
13514 const Expr *Arg,
13515 bool SNaN,
13516 llvm::APFloat &Result) {
13517 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13518 if (!S) return false;
13519
13520 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13521
13522 llvm::APInt fill;
13523
13524 // Treat empty strings as if they were zero.
13525 if (S->getString().empty())
13526 fill = llvm::APInt(32, 0);
13527 else if (S->getString().getAsInteger(0, fill))
13528 return false;
13529
13530 if (Context.getTargetInfo().isNan2008()) {
13531 if (SNaN)
13532 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13533 else
13534 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13535 } else {
13536 // Prior to IEEE 754-2008, architectures were allowed to choose whether
13537 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13538 // a different encoding to what became a standard in 2008, and for pre-
13539 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13540 // sNaN. This is now known as "legacy NaN" encoding.
13541 if (SNaN)
13542 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13543 else
13544 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13545 }
13546
13547 return true;
13548 }
13549
VisitCallExpr(const CallExpr * E)13550 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13551 switch (E->getBuiltinCallee()) {
13552 default:
13553 return ExprEvaluatorBaseTy::VisitCallExpr(E);
13554
13555 case Builtin::BI__builtin_huge_val:
13556 case Builtin::BI__builtin_huge_valf:
13557 case Builtin::BI__builtin_huge_vall:
13558 case Builtin::BI__builtin_huge_valf128:
13559 case Builtin::BI__builtin_inf:
13560 case Builtin::BI__builtin_inff:
13561 case Builtin::BI__builtin_infl:
13562 case Builtin::BI__builtin_inff128: {
13563 const llvm::fltSemantics &Sem =
13564 Info.Ctx.getFloatTypeSemantics(E->getType());
13565 Result = llvm::APFloat::getInf(Sem);
13566 return true;
13567 }
13568
13569 case Builtin::BI__builtin_nans:
13570 case Builtin::BI__builtin_nansf:
13571 case Builtin::BI__builtin_nansl:
13572 case Builtin::BI__builtin_nansf128:
13573 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13574 true, Result))
13575 return Error(E);
13576 return true;
13577
13578 case Builtin::BI__builtin_nan:
13579 case Builtin::BI__builtin_nanf:
13580 case Builtin::BI__builtin_nanl:
13581 case Builtin::BI__builtin_nanf128:
13582 // If this is __builtin_nan() turn this into a nan, otherwise we
13583 // can't constant fold it.
13584 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13585 false, Result))
13586 return Error(E);
13587 return true;
13588
13589 case Builtin::BI__builtin_fabs:
13590 case Builtin::BI__builtin_fabsf:
13591 case Builtin::BI__builtin_fabsl:
13592 case Builtin::BI__builtin_fabsf128:
13593 // The C standard says "fabs raises no floating-point exceptions,
13594 // even if x is a signaling NaN. The returned value is independent of
13595 // the current rounding direction mode." Therefore constant folding can
13596 // proceed without regard to the floating point settings.
13597 // Reference, WG14 N2478 F.10.4.3
13598 if (!EvaluateFloat(E->getArg(0), Result, Info))
13599 return false;
13600
13601 if (Result.isNegative())
13602 Result.changeSign();
13603 return true;
13604
13605 // FIXME: Builtin::BI__builtin_powi
13606 // FIXME: Builtin::BI__builtin_powif
13607 // FIXME: Builtin::BI__builtin_powil
13608
13609 case Builtin::BI__builtin_copysign:
13610 case Builtin::BI__builtin_copysignf:
13611 case Builtin::BI__builtin_copysignl:
13612 case Builtin::BI__builtin_copysignf128: {
13613 APFloat RHS(0.);
13614 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13615 !EvaluateFloat(E->getArg(1), RHS, Info))
13616 return false;
13617 Result.copySign(RHS);
13618 return true;
13619 }
13620 }
13621 }
13622
VisitUnaryReal(const UnaryOperator * E)13623 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13624 if (E->getSubExpr()->getType()->isAnyComplexType()) {
13625 ComplexValue CV;
13626 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13627 return false;
13628 Result = CV.FloatReal;
13629 return true;
13630 }
13631
13632 return Visit(E->getSubExpr());
13633 }
13634
VisitUnaryImag(const UnaryOperator * E)13635 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13636 if (E->getSubExpr()->getType()->isAnyComplexType()) {
13637 ComplexValue CV;
13638 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13639 return false;
13640 Result = CV.FloatImag;
13641 return true;
13642 }
13643
13644 VisitIgnoredValue(E->getSubExpr());
13645 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13646 Result = llvm::APFloat::getZero(Sem);
13647 return true;
13648 }
13649
VisitUnaryOperator(const UnaryOperator * E)13650 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13651 switch (E->getOpcode()) {
13652 default: return Error(E);
13653 case UO_Plus:
13654 return EvaluateFloat(E->getSubExpr(), Result, Info);
13655 case UO_Minus:
13656 // In C standard, WG14 N2478 F.3 p4
13657 // "the unary - raises no floating point exceptions,
13658 // even if the operand is signalling."
13659 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13660 return false;
13661 Result.changeSign();
13662 return true;
13663 }
13664 }
13665
VisitBinaryOperator(const BinaryOperator * E)13666 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13667 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13668 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13669
13670 APFloat RHS(0.0);
13671 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13672 if (!LHSOK && !Info.noteFailure())
13673 return false;
13674 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13675 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13676 }
13677
VisitFloatingLiteral(const FloatingLiteral * E)13678 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13679 Result = E->getValue();
13680 return true;
13681 }
13682
VisitCastExpr(const CastExpr * E)13683 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13684 const Expr* SubExpr = E->getSubExpr();
13685
13686 switch (E->getCastKind()) {
13687 default:
13688 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13689
13690 case CK_IntegralToFloating: {
13691 APSInt IntResult;
13692 const FPOptions FPO = E->getFPFeaturesInEffect(
13693 Info.Ctx.getLangOpts());
13694 return EvaluateInteger(SubExpr, IntResult, Info) &&
13695 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
13696 IntResult, E->getType(), Result);
13697 }
13698
13699 case CK_FixedPointToFloating: {
13700 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13701 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
13702 return false;
13703 Result =
13704 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
13705 return true;
13706 }
13707
13708 case CK_FloatingCast: {
13709 if (!Visit(SubExpr))
13710 return false;
13711 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13712 Result);
13713 }
13714
13715 case CK_FloatingComplexToReal: {
13716 ComplexValue V;
13717 if (!EvaluateComplex(SubExpr, V, Info))
13718 return false;
13719 Result = V.getComplexFloatReal();
13720 return true;
13721 }
13722 }
13723 }
13724
13725 //===----------------------------------------------------------------------===//
13726 // Complex Evaluation (for float and integer)
13727 //===----------------------------------------------------------------------===//
13728
13729 namespace {
13730 class ComplexExprEvaluator
13731 : public ExprEvaluatorBase<ComplexExprEvaluator> {
13732 ComplexValue &Result;
13733
13734 public:
ComplexExprEvaluator(EvalInfo & info,ComplexValue & Result)13735 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13736 : ExprEvaluatorBaseTy(info), Result(Result) {}
13737
Success(const APValue & V,const Expr * e)13738 bool Success(const APValue &V, const Expr *e) {
13739 Result.setFrom(V);
13740 return true;
13741 }
13742
13743 bool ZeroInitialization(const Expr *E);
13744
13745 //===--------------------------------------------------------------------===//
13746 // Visitor Methods
13747 //===--------------------------------------------------------------------===//
13748
13749 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13750 bool VisitCastExpr(const CastExpr *E);
13751 bool VisitBinaryOperator(const BinaryOperator *E);
13752 bool VisitUnaryOperator(const UnaryOperator *E);
13753 bool VisitInitListExpr(const InitListExpr *E);
13754 bool VisitCallExpr(const CallExpr *E);
13755 };
13756 } // end anonymous namespace
13757
EvaluateComplex(const Expr * E,ComplexValue & Result,EvalInfo & Info)13758 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13759 EvalInfo &Info) {
13760 assert(E->isRValue() && E->getType()->isAnyComplexType());
13761 return ComplexExprEvaluator(Info, Result).Visit(E);
13762 }
13763
ZeroInitialization(const Expr * E)13764 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13765 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13766 if (ElemTy->isRealFloatingType()) {
13767 Result.makeComplexFloat();
13768 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13769 Result.FloatReal = Zero;
13770 Result.FloatImag = Zero;
13771 } else {
13772 Result.makeComplexInt();
13773 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13774 Result.IntReal = Zero;
13775 Result.IntImag = Zero;
13776 }
13777 return true;
13778 }
13779
VisitImaginaryLiteral(const ImaginaryLiteral * E)13780 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13781 const Expr* SubExpr = E->getSubExpr();
13782
13783 if (SubExpr->getType()->isRealFloatingType()) {
13784 Result.makeComplexFloat();
13785 APFloat &Imag = Result.FloatImag;
13786 if (!EvaluateFloat(SubExpr, Imag, Info))
13787 return false;
13788
13789 Result.FloatReal = APFloat(Imag.getSemantics());
13790 return true;
13791 } else {
13792 assert(SubExpr->getType()->isIntegerType() &&
13793 "Unexpected imaginary literal.");
13794
13795 Result.makeComplexInt();
13796 APSInt &Imag = Result.IntImag;
13797 if (!EvaluateInteger(SubExpr, Imag, Info))
13798 return false;
13799
13800 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13801 return true;
13802 }
13803 }
13804
VisitCastExpr(const CastExpr * E)13805 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13806
13807 switch (E->getCastKind()) {
13808 case CK_BitCast:
13809 case CK_BaseToDerived:
13810 case CK_DerivedToBase:
13811 case CK_UncheckedDerivedToBase:
13812 case CK_Dynamic:
13813 case CK_ToUnion:
13814 case CK_ArrayToPointerDecay:
13815 case CK_FunctionToPointerDecay:
13816 case CK_NullToPointer:
13817 case CK_NullToMemberPointer:
13818 case CK_BaseToDerivedMemberPointer:
13819 case CK_DerivedToBaseMemberPointer:
13820 case CK_MemberPointerToBoolean:
13821 case CK_ReinterpretMemberPointer:
13822 case CK_ConstructorConversion:
13823 case CK_IntegralToPointer:
13824 case CK_PointerToIntegral:
13825 case CK_PointerToBoolean:
13826 case CK_ToVoid:
13827 case CK_VectorSplat:
13828 case CK_IntegralCast:
13829 case CK_BooleanToSignedIntegral:
13830 case CK_IntegralToBoolean:
13831 case CK_IntegralToFloating:
13832 case CK_FloatingToIntegral:
13833 case CK_FloatingToBoolean:
13834 case CK_FloatingCast:
13835 case CK_CPointerToObjCPointerCast:
13836 case CK_BlockPointerToObjCPointerCast:
13837 case CK_AnyPointerToBlockPointerCast:
13838 case CK_ObjCObjectLValueCast:
13839 case CK_FloatingComplexToReal:
13840 case CK_FloatingComplexToBoolean:
13841 case CK_IntegralComplexToReal:
13842 case CK_IntegralComplexToBoolean:
13843 case CK_ARCProduceObject:
13844 case CK_ARCConsumeObject:
13845 case CK_ARCReclaimReturnedObject:
13846 case CK_ARCExtendBlockObject:
13847 case CK_CopyAndAutoreleaseBlockObject:
13848 case CK_BuiltinFnToFnPtr:
13849 case CK_ZeroToOCLOpaqueType:
13850 case CK_NonAtomicToAtomic:
13851 case CK_AddressSpaceConversion:
13852 case CK_IntToOCLSampler:
13853 case CK_FloatingToFixedPoint:
13854 case CK_FixedPointToFloating:
13855 case CK_FixedPointCast:
13856 case CK_FixedPointToBoolean:
13857 case CK_FixedPointToIntegral:
13858 case CK_IntegralToFixedPoint:
13859 llvm_unreachable("invalid cast kind for complex value");
13860
13861 case CK_LValueToRValue:
13862 case CK_AtomicToNonAtomic:
13863 case CK_NoOp:
13864 case CK_LValueToRValueBitCast:
13865 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13866
13867 case CK_Dependent:
13868 case CK_LValueBitCast:
13869 case CK_UserDefinedConversion:
13870 return Error(E);
13871
13872 case CK_FloatingRealToComplex: {
13873 APFloat &Real = Result.FloatReal;
13874 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13875 return false;
13876
13877 Result.makeComplexFloat();
13878 Result.FloatImag = APFloat(Real.getSemantics());
13879 return true;
13880 }
13881
13882 case CK_FloatingComplexCast: {
13883 if (!Visit(E->getSubExpr()))
13884 return false;
13885
13886 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13887 QualType From
13888 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13889
13890 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13891 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13892 }
13893
13894 case CK_FloatingComplexToIntegralComplex: {
13895 if (!Visit(E->getSubExpr()))
13896 return false;
13897
13898 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13899 QualType From
13900 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13901 Result.makeComplexInt();
13902 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13903 To, Result.IntReal) &&
13904 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13905 To, Result.IntImag);
13906 }
13907
13908 case CK_IntegralRealToComplex: {
13909 APSInt &Real = Result.IntReal;
13910 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13911 return false;
13912
13913 Result.makeComplexInt();
13914 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13915 return true;
13916 }
13917
13918 case CK_IntegralComplexCast: {
13919 if (!Visit(E->getSubExpr()))
13920 return false;
13921
13922 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13923 QualType From
13924 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13925
13926 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
13927 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
13928 return true;
13929 }
13930
13931 case CK_IntegralComplexToFloatingComplex: {
13932 if (!Visit(E->getSubExpr()))
13933 return false;
13934
13935 const FPOptions FPO = E->getFPFeaturesInEffect(
13936 Info.Ctx.getLangOpts());
13937 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13938 QualType From
13939 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13940 Result.makeComplexFloat();
13941 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
13942 To, Result.FloatReal) &&
13943 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
13944 To, Result.FloatImag);
13945 }
13946 }
13947
13948 llvm_unreachable("unknown cast resulting in complex value");
13949 }
13950
VisitBinaryOperator(const BinaryOperator * E)13951 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13952 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13953 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13954
13955 // Track whether the LHS or RHS is real at the type system level. When this is
13956 // the case we can simplify our evaluation strategy.
13957 bool LHSReal = false, RHSReal = false;
13958
13959 bool LHSOK;
13960 if (E->getLHS()->getType()->isRealFloatingType()) {
13961 LHSReal = true;
13962 APFloat &Real = Result.FloatReal;
13963 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
13964 if (LHSOK) {
13965 Result.makeComplexFloat();
13966 Result.FloatImag = APFloat(Real.getSemantics());
13967 }
13968 } else {
13969 LHSOK = Visit(E->getLHS());
13970 }
13971 if (!LHSOK && !Info.noteFailure())
13972 return false;
13973
13974 ComplexValue RHS;
13975 if (E->getRHS()->getType()->isRealFloatingType()) {
13976 RHSReal = true;
13977 APFloat &Real = RHS.FloatReal;
13978 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
13979 return false;
13980 RHS.makeComplexFloat();
13981 RHS.FloatImag = APFloat(Real.getSemantics());
13982 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13983 return false;
13984
13985 assert(!(LHSReal && RHSReal) &&
13986 "Cannot have both operands of a complex operation be real.");
13987 switch (E->getOpcode()) {
13988 default: return Error(E);
13989 case BO_Add:
13990 if (Result.isComplexFloat()) {
13991 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
13992 APFloat::rmNearestTiesToEven);
13993 if (LHSReal)
13994 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13995 else if (!RHSReal)
13996 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
13997 APFloat::rmNearestTiesToEven);
13998 } else {
13999 Result.getComplexIntReal() += RHS.getComplexIntReal();
14000 Result.getComplexIntImag() += RHS.getComplexIntImag();
14001 }
14002 break;
14003 case BO_Sub:
14004 if (Result.isComplexFloat()) {
14005 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14006 APFloat::rmNearestTiesToEven);
14007 if (LHSReal) {
14008 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14009 Result.getComplexFloatImag().changeSign();
14010 } else if (!RHSReal) {
14011 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14012 APFloat::rmNearestTiesToEven);
14013 }
14014 } else {
14015 Result.getComplexIntReal() -= RHS.getComplexIntReal();
14016 Result.getComplexIntImag() -= RHS.getComplexIntImag();
14017 }
14018 break;
14019 case BO_Mul:
14020 if (Result.isComplexFloat()) {
14021 // This is an implementation of complex multiplication according to the
14022 // constraints laid out in C11 Annex G. The implementation uses the
14023 // following naming scheme:
14024 // (a + ib) * (c + id)
14025 ComplexValue LHS = Result;
14026 APFloat &A = LHS.getComplexFloatReal();
14027 APFloat &B = LHS.getComplexFloatImag();
14028 APFloat &C = RHS.getComplexFloatReal();
14029 APFloat &D = RHS.getComplexFloatImag();
14030 APFloat &ResR = Result.getComplexFloatReal();
14031 APFloat &ResI = Result.getComplexFloatImag();
14032 if (LHSReal) {
14033 assert(!RHSReal && "Cannot have two real operands for a complex op!");
14034 ResR = A * C;
14035 ResI = A * D;
14036 } else if (RHSReal) {
14037 ResR = C * A;
14038 ResI = C * B;
14039 } else {
14040 // In the fully general case, we need to handle NaNs and infinities
14041 // robustly.
14042 APFloat AC = A * C;
14043 APFloat BD = B * D;
14044 APFloat AD = A * D;
14045 APFloat BC = B * C;
14046 ResR = AC - BD;
14047 ResI = AD + BC;
14048 if (ResR.isNaN() && ResI.isNaN()) {
14049 bool Recalc = false;
14050 if (A.isInfinity() || B.isInfinity()) {
14051 A = APFloat::copySign(
14052 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14053 B = APFloat::copySign(
14054 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14055 if (C.isNaN())
14056 C = APFloat::copySign(APFloat(C.getSemantics()), C);
14057 if (D.isNaN())
14058 D = APFloat::copySign(APFloat(D.getSemantics()), D);
14059 Recalc = true;
14060 }
14061 if (C.isInfinity() || D.isInfinity()) {
14062 C = APFloat::copySign(
14063 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14064 D = APFloat::copySign(
14065 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14066 if (A.isNaN())
14067 A = APFloat::copySign(APFloat(A.getSemantics()), A);
14068 if (B.isNaN())
14069 B = APFloat::copySign(APFloat(B.getSemantics()), B);
14070 Recalc = true;
14071 }
14072 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14073 AD.isInfinity() || BC.isInfinity())) {
14074 if (A.isNaN())
14075 A = APFloat::copySign(APFloat(A.getSemantics()), A);
14076 if (B.isNaN())
14077 B = APFloat::copySign(APFloat(B.getSemantics()), B);
14078 if (C.isNaN())
14079 C = APFloat::copySign(APFloat(C.getSemantics()), C);
14080 if (D.isNaN())
14081 D = APFloat::copySign(APFloat(D.getSemantics()), D);
14082 Recalc = true;
14083 }
14084 if (Recalc) {
14085 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14086 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14087 }
14088 }
14089 }
14090 } else {
14091 ComplexValue LHS = Result;
14092 Result.getComplexIntReal() =
14093 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14094 LHS.getComplexIntImag() * RHS.getComplexIntImag());
14095 Result.getComplexIntImag() =
14096 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14097 LHS.getComplexIntImag() * RHS.getComplexIntReal());
14098 }
14099 break;
14100 case BO_Div:
14101 if (Result.isComplexFloat()) {
14102 // This is an implementation of complex division according to the
14103 // constraints laid out in C11 Annex G. The implementation uses the
14104 // following naming scheme:
14105 // (a + ib) / (c + id)
14106 ComplexValue LHS = Result;
14107 APFloat &A = LHS.getComplexFloatReal();
14108 APFloat &B = LHS.getComplexFloatImag();
14109 APFloat &C = RHS.getComplexFloatReal();
14110 APFloat &D = RHS.getComplexFloatImag();
14111 APFloat &ResR = Result.getComplexFloatReal();
14112 APFloat &ResI = Result.getComplexFloatImag();
14113 if (RHSReal) {
14114 ResR = A / C;
14115 ResI = B / C;
14116 } else {
14117 if (LHSReal) {
14118 // No real optimizations we can do here, stub out with zero.
14119 B = APFloat::getZero(A.getSemantics());
14120 }
14121 int DenomLogB = 0;
14122 APFloat MaxCD = maxnum(abs(C), abs(D));
14123 if (MaxCD.isFinite()) {
14124 DenomLogB = ilogb(MaxCD);
14125 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14126 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14127 }
14128 APFloat Denom = C * C + D * D;
14129 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14130 APFloat::rmNearestTiesToEven);
14131 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14132 APFloat::rmNearestTiesToEven);
14133 if (ResR.isNaN() && ResI.isNaN()) {
14134 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14135 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14136 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14137 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14138 D.isFinite()) {
14139 A = APFloat::copySign(
14140 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14141 B = APFloat::copySign(
14142 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14143 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14144 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14145 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14146 C = APFloat::copySign(
14147 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14148 D = APFloat::copySign(
14149 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14150 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14151 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14152 }
14153 }
14154 }
14155 } else {
14156 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14157 return Error(E, diag::note_expr_divide_by_zero);
14158
14159 ComplexValue LHS = Result;
14160 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14161 RHS.getComplexIntImag() * RHS.getComplexIntImag();
14162 Result.getComplexIntReal() =
14163 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14164 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14165 Result.getComplexIntImag() =
14166 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14167 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14168 }
14169 break;
14170 }
14171
14172 return true;
14173 }
14174
VisitUnaryOperator(const UnaryOperator * E)14175 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14176 // Get the operand value into 'Result'.
14177 if (!Visit(E->getSubExpr()))
14178 return false;
14179
14180 switch (E->getOpcode()) {
14181 default:
14182 return Error(E);
14183 case UO_Extension:
14184 return true;
14185 case UO_Plus:
14186 // The result is always just the subexpr.
14187 return true;
14188 case UO_Minus:
14189 if (Result.isComplexFloat()) {
14190 Result.getComplexFloatReal().changeSign();
14191 Result.getComplexFloatImag().changeSign();
14192 }
14193 else {
14194 Result.getComplexIntReal() = -Result.getComplexIntReal();
14195 Result.getComplexIntImag() = -Result.getComplexIntImag();
14196 }
14197 return true;
14198 case UO_Not:
14199 if (Result.isComplexFloat())
14200 Result.getComplexFloatImag().changeSign();
14201 else
14202 Result.getComplexIntImag() = -Result.getComplexIntImag();
14203 return true;
14204 }
14205 }
14206
VisitInitListExpr(const InitListExpr * E)14207 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14208 if (E->getNumInits() == 2) {
14209 if (E->getType()->isComplexType()) {
14210 Result.makeComplexFloat();
14211 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14212 return false;
14213 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14214 return false;
14215 } else {
14216 Result.makeComplexInt();
14217 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14218 return false;
14219 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14220 return false;
14221 }
14222 return true;
14223 }
14224 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14225 }
14226
VisitCallExpr(const CallExpr * E)14227 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14228 switch (E->getBuiltinCallee()) {
14229 case Builtin::BI__builtin_complex:
14230 Result.makeComplexFloat();
14231 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14232 return false;
14233 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14234 return false;
14235 return true;
14236
14237 default:
14238 break;
14239 }
14240
14241 return ExprEvaluatorBaseTy::VisitCallExpr(E);
14242 }
14243
14244 //===----------------------------------------------------------------------===//
14245 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14246 // implicit conversion.
14247 //===----------------------------------------------------------------------===//
14248
14249 namespace {
14250 class AtomicExprEvaluator :
14251 public ExprEvaluatorBase<AtomicExprEvaluator> {
14252 const LValue *This;
14253 APValue &Result;
14254 public:
AtomicExprEvaluator(EvalInfo & Info,const LValue * This,APValue & Result)14255 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14256 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14257
Success(const APValue & V,const Expr * E)14258 bool Success(const APValue &V, const Expr *E) {
14259 Result = V;
14260 return true;
14261 }
14262
ZeroInitialization(const Expr * E)14263 bool ZeroInitialization(const Expr *E) {
14264 ImplicitValueInitExpr VIE(
14265 E->getType()->castAs<AtomicType>()->getValueType());
14266 // For atomic-qualified class (and array) types in C++, initialize the
14267 // _Atomic-wrapped subobject directly, in-place.
14268 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14269 : Evaluate(Result, Info, &VIE);
14270 }
14271
VisitCastExpr(const CastExpr * E)14272 bool VisitCastExpr(const CastExpr *E) {
14273 switch (E->getCastKind()) {
14274 default:
14275 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14276 case CK_NonAtomicToAtomic:
14277 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14278 : Evaluate(Result, Info, E->getSubExpr());
14279 }
14280 }
14281 };
14282 } // end anonymous namespace
14283
EvaluateAtomic(const Expr * E,const LValue * This,APValue & Result,EvalInfo & Info)14284 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14285 EvalInfo &Info) {
14286 assert(E->isRValue() && E->getType()->isAtomicType());
14287 return AtomicExprEvaluator(Info, This, Result).Visit(E);
14288 }
14289
14290 //===----------------------------------------------------------------------===//
14291 // Void expression evaluation, primarily for a cast to void on the LHS of a
14292 // comma operator
14293 //===----------------------------------------------------------------------===//
14294
14295 namespace {
14296 class VoidExprEvaluator
14297 : public ExprEvaluatorBase<VoidExprEvaluator> {
14298 public:
VoidExprEvaluator(EvalInfo & Info)14299 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14300
Success(const APValue & V,const Expr * e)14301 bool Success(const APValue &V, const Expr *e) { return true; }
14302
ZeroInitialization(const Expr * E)14303 bool ZeroInitialization(const Expr *E) { return true; }
14304
VisitCastExpr(const CastExpr * E)14305 bool VisitCastExpr(const CastExpr *E) {
14306 switch (E->getCastKind()) {
14307 default:
14308 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14309 case CK_ToVoid:
14310 VisitIgnoredValue(E->getSubExpr());
14311 return true;
14312 }
14313 }
14314
VisitCallExpr(const CallExpr * E)14315 bool VisitCallExpr(const CallExpr *E) {
14316 switch (E->getBuiltinCallee()) {
14317 case Builtin::BI__assume:
14318 case Builtin::BI__builtin_assume:
14319 // The argument is not evaluated!
14320 return true;
14321
14322 case Builtin::BI__builtin_operator_delete:
14323 return HandleOperatorDeleteCall(Info, E);
14324
14325 default:
14326 break;
14327 }
14328
14329 return ExprEvaluatorBaseTy::VisitCallExpr(E);
14330 }
14331
14332 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14333 };
14334 } // end anonymous namespace
14335
VisitCXXDeleteExpr(const CXXDeleteExpr * E)14336 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14337 // We cannot speculatively evaluate a delete expression.
14338 if (Info.SpeculativeEvaluationDepth)
14339 return false;
14340
14341 FunctionDecl *OperatorDelete = E->getOperatorDelete();
14342 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14343 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14344 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14345 return false;
14346 }
14347
14348 const Expr *Arg = E->getArgument();
14349
14350 LValue Pointer;
14351 if (!EvaluatePointer(Arg, Pointer, Info))
14352 return false;
14353 if (Pointer.Designator.Invalid)
14354 return false;
14355
14356 // Deleting a null pointer has no effect.
14357 if (Pointer.isNullPointer()) {
14358 // This is the only case where we need to produce an extension warning:
14359 // the only other way we can succeed is if we find a dynamic allocation,
14360 // and we will have warned when we allocated it in that case.
14361 if (!Info.getLangOpts().CPlusPlus20)
14362 Info.CCEDiag(E, diag::note_constexpr_new);
14363 return true;
14364 }
14365
14366 Optional<DynAlloc *> Alloc = CheckDeleteKind(
14367 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14368 if (!Alloc)
14369 return false;
14370 QualType AllocType = Pointer.Base.getDynamicAllocType();
14371
14372 // For the non-array case, the designator must be empty if the static type
14373 // does not have a virtual destructor.
14374 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14375 !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14376 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14377 << Arg->getType()->getPointeeType() << AllocType;
14378 return false;
14379 }
14380
14381 // For a class type with a virtual destructor, the selected operator delete
14382 // is the one looked up when building the destructor.
14383 if (!E->isArrayForm() && !E->isGlobalDelete()) {
14384 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14385 if (VirtualDelete &&
14386 !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14387 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14388 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14389 return false;
14390 }
14391 }
14392
14393 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14394 (*Alloc)->Value, AllocType))
14395 return false;
14396
14397 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14398 // The element was already erased. This means the destructor call also
14399 // deleted the object.
14400 // FIXME: This probably results in undefined behavior before we get this
14401 // far, and should be diagnosed elsewhere first.
14402 Info.FFDiag(E, diag::note_constexpr_double_delete);
14403 return false;
14404 }
14405
14406 return true;
14407 }
14408
EvaluateVoid(const Expr * E,EvalInfo & Info)14409 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14410 assert(E->isRValue() && E->getType()->isVoidType());
14411 return VoidExprEvaluator(Info).Visit(E);
14412 }
14413
14414 //===----------------------------------------------------------------------===//
14415 // Top level Expr::EvaluateAsRValue method.
14416 //===----------------------------------------------------------------------===//
14417
Evaluate(APValue & Result,EvalInfo & Info,const Expr * E)14418 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14419 // In C, function designators are not lvalues, but we evaluate them as if they
14420 // are.
14421 QualType T = E->getType();
14422 if (E->isGLValue() || T->isFunctionType()) {
14423 LValue LV;
14424 if (!EvaluateLValue(E, LV, Info))
14425 return false;
14426 LV.moveInto(Result);
14427 } else if (T->isVectorType()) {
14428 if (!EvaluateVector(E, Result, Info))
14429 return false;
14430 } else if (T->isIntegralOrEnumerationType()) {
14431 if (!IntExprEvaluator(Info, Result).Visit(E))
14432 return false;
14433 } else if (T->hasPointerRepresentation()) {
14434 LValue LV;
14435 if (!EvaluatePointer(E, LV, Info))
14436 return false;
14437 LV.moveInto(Result);
14438 } else if (T->isRealFloatingType()) {
14439 llvm::APFloat F(0.0);
14440 if (!EvaluateFloat(E, F, Info))
14441 return false;
14442 Result = APValue(F);
14443 } else if (T->isAnyComplexType()) {
14444 ComplexValue C;
14445 if (!EvaluateComplex(E, C, Info))
14446 return false;
14447 C.moveInto(Result);
14448 } else if (T->isFixedPointType()) {
14449 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14450 } else if (T->isMemberPointerType()) {
14451 MemberPtr P;
14452 if (!EvaluateMemberPointer(E, P, Info))
14453 return false;
14454 P.moveInto(Result);
14455 return true;
14456 } else if (T->isArrayType()) {
14457 LValue LV;
14458 APValue &Value =
14459 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14460 if (!EvaluateArray(E, LV, Value, Info))
14461 return false;
14462 Result = Value;
14463 } else if (T->isRecordType()) {
14464 LValue LV;
14465 APValue &Value =
14466 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14467 if (!EvaluateRecord(E, LV, Value, Info))
14468 return false;
14469 Result = Value;
14470 } else if (T->isVoidType()) {
14471 if (!Info.getLangOpts().CPlusPlus11)
14472 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14473 << E->getType();
14474 if (!EvaluateVoid(E, Info))
14475 return false;
14476 } else if (T->isAtomicType()) {
14477 QualType Unqual = T.getAtomicUnqualifiedType();
14478 if (Unqual->isArrayType() || Unqual->isRecordType()) {
14479 LValue LV;
14480 APValue &Value = Info.CurrentCall->createTemporary(
14481 E, Unqual, ScopeKind::FullExpression, LV);
14482 if (!EvaluateAtomic(E, &LV, Value, Info))
14483 return false;
14484 } else {
14485 if (!EvaluateAtomic(E, nullptr, Result, Info))
14486 return false;
14487 }
14488 } else if (Info.getLangOpts().CPlusPlus11) {
14489 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14490 return false;
14491 } else {
14492 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14493 return false;
14494 }
14495
14496 return true;
14497 }
14498
14499 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14500 /// cases, the in-place evaluation is essential, since later initializers for
14501 /// an object can indirectly refer to subobjects which were initialized earlier.
EvaluateInPlace(APValue & Result,EvalInfo & Info,const LValue & This,const Expr * E,bool AllowNonLiteralTypes)14502 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14503 const Expr *E, bool AllowNonLiteralTypes) {
14504 assert(!E->isValueDependent());
14505
14506 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14507 return false;
14508
14509 if (E->isRValue()) {
14510 // Evaluate arrays and record types in-place, so that later initializers can
14511 // refer to earlier-initialized members of the object.
14512 QualType T = E->getType();
14513 if (T->isArrayType())
14514 return EvaluateArray(E, This, Result, Info);
14515 else if (T->isRecordType())
14516 return EvaluateRecord(E, This, Result, Info);
14517 else if (T->isAtomicType()) {
14518 QualType Unqual = T.getAtomicUnqualifiedType();
14519 if (Unqual->isArrayType() || Unqual->isRecordType())
14520 return EvaluateAtomic(E, &This, Result, Info);
14521 }
14522 }
14523
14524 // For any other type, in-place evaluation is unimportant.
14525 return Evaluate(Result, Info, E);
14526 }
14527
14528 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14529 /// lvalue-to-rvalue cast if it is an lvalue.
EvaluateAsRValue(EvalInfo & Info,const Expr * E,APValue & Result)14530 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14531 if (Info.EnableNewConstInterp) {
14532 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14533 return false;
14534 } else {
14535 if (E->getType().isNull())
14536 return false;
14537
14538 if (!CheckLiteralType(Info, E))
14539 return false;
14540
14541 if (!::Evaluate(Result, Info, E))
14542 return false;
14543
14544 if (E->isGLValue()) {
14545 LValue LV;
14546 LV.setFrom(Info.Ctx, Result);
14547 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14548 return false;
14549 }
14550 }
14551
14552 // Check this core constant expression is a constant expression.
14553 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14554 ConstantExprKind::Normal) &&
14555 CheckMemoryLeaks(Info);
14556 }
14557
FastEvaluateAsRValue(const Expr * Exp,Expr::EvalResult & Result,const ASTContext & Ctx,bool & IsConst)14558 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14559 const ASTContext &Ctx, bool &IsConst) {
14560 // Fast-path evaluations of integer literals, since we sometimes see files
14561 // containing vast quantities of these.
14562 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14563 Result.Val = APValue(APSInt(L->getValue(),
14564 L->getType()->isUnsignedIntegerType()));
14565 IsConst = true;
14566 return true;
14567 }
14568
14569 // This case should be rare, but we need to check it before we check on
14570 // the type below.
14571 if (Exp->getType().isNull()) {
14572 IsConst = false;
14573 return true;
14574 }
14575
14576 // FIXME: Evaluating values of large array and record types can cause
14577 // performance problems. Only do so in C++11 for now.
14578 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
14579 Exp->getType()->isRecordType()) &&
14580 !Ctx.getLangOpts().CPlusPlus11) {
14581 IsConst = false;
14582 return true;
14583 }
14584 return false;
14585 }
14586
hasUnacceptableSideEffect(Expr::EvalStatus & Result,Expr::SideEffectsKind SEK)14587 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14588 Expr::SideEffectsKind SEK) {
14589 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14590 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14591 }
14592
EvaluateAsRValue(const Expr * E,Expr::EvalResult & Result,const ASTContext & Ctx,EvalInfo & Info)14593 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14594 const ASTContext &Ctx, EvalInfo &Info) {
14595 bool IsConst;
14596 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14597 return IsConst;
14598
14599 return EvaluateAsRValue(Info, E, Result.Val);
14600 }
14601
EvaluateAsInt(const Expr * E,Expr::EvalResult & ExprResult,const ASTContext & Ctx,Expr::SideEffectsKind AllowSideEffects,EvalInfo & Info)14602 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14603 const ASTContext &Ctx,
14604 Expr::SideEffectsKind AllowSideEffects,
14605 EvalInfo &Info) {
14606 if (!E->getType()->isIntegralOrEnumerationType())
14607 return false;
14608
14609 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14610 !ExprResult.Val.isInt() ||
14611 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14612 return false;
14613
14614 return true;
14615 }
14616
EvaluateAsFixedPoint(const Expr * E,Expr::EvalResult & ExprResult,const ASTContext & Ctx,Expr::SideEffectsKind AllowSideEffects,EvalInfo & Info)14617 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14618 const ASTContext &Ctx,
14619 Expr::SideEffectsKind AllowSideEffects,
14620 EvalInfo &Info) {
14621 if (!E->getType()->isFixedPointType())
14622 return false;
14623
14624 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14625 return false;
14626
14627 if (!ExprResult.Val.isFixedPoint() ||
14628 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14629 return false;
14630
14631 return true;
14632 }
14633
14634 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14635 /// any crazy technique (that has nothing to do with language standards) that
14636 /// we want to. If this function returns true, it returns the folded constant
14637 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14638 /// will be applied to the result.
EvaluateAsRValue(EvalResult & Result,const ASTContext & Ctx,bool InConstantContext) const14639 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14640 bool InConstantContext) const {
14641 assert(!isValueDependent() &&
14642 "Expression evaluator can't be called on a dependent expression.");
14643 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14644 Info.InConstantContext = InConstantContext;
14645 return ::EvaluateAsRValue(this, Result, Ctx, Info);
14646 }
14647
EvaluateAsBooleanCondition(bool & Result,const ASTContext & Ctx,bool InConstantContext) const14648 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14649 bool InConstantContext) const {
14650 assert(!isValueDependent() &&
14651 "Expression evaluator can't be called on a dependent expression.");
14652 EvalResult Scratch;
14653 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14654 HandleConversionToBool(Scratch.Val, Result);
14655 }
14656
EvaluateAsInt(EvalResult & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const14657 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14658 SideEffectsKind AllowSideEffects,
14659 bool InConstantContext) const {
14660 assert(!isValueDependent() &&
14661 "Expression evaluator can't be called on a dependent expression.");
14662 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14663 Info.InConstantContext = InConstantContext;
14664 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14665 }
14666
EvaluateAsFixedPoint(EvalResult & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const14667 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14668 SideEffectsKind AllowSideEffects,
14669 bool InConstantContext) const {
14670 assert(!isValueDependent() &&
14671 "Expression evaluator can't be called on a dependent expression.");
14672 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14673 Info.InConstantContext = InConstantContext;
14674 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14675 }
14676
EvaluateAsFloat(APFloat & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const14677 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14678 SideEffectsKind AllowSideEffects,
14679 bool InConstantContext) const {
14680 assert(!isValueDependent() &&
14681 "Expression evaluator can't be called on a dependent expression.");
14682
14683 if (!getType()->isRealFloatingType())
14684 return false;
14685
14686 EvalResult ExprResult;
14687 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14688 !ExprResult.Val.isFloat() ||
14689 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14690 return false;
14691
14692 Result = ExprResult.Val.getFloat();
14693 return true;
14694 }
14695
EvaluateAsLValue(EvalResult & Result,const ASTContext & Ctx,bool InConstantContext) const14696 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14697 bool InConstantContext) const {
14698 assert(!isValueDependent() &&
14699 "Expression evaluator can't be called on a dependent expression.");
14700
14701 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14702 Info.InConstantContext = InConstantContext;
14703 LValue LV;
14704 CheckedTemporaries CheckedTemps;
14705 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14706 Result.HasSideEffects ||
14707 !CheckLValueConstantExpression(Info, getExprLoc(),
14708 Ctx.getLValueReferenceType(getType()), LV,
14709 ConstantExprKind::Normal, CheckedTemps))
14710 return false;
14711
14712 LV.moveInto(Result.Val);
14713 return true;
14714 }
14715
EvaluateDestruction(const ASTContext & Ctx,APValue::LValueBase Base,APValue DestroyedValue,QualType Type,SourceLocation Loc,Expr::EvalStatus & EStatus)14716 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
14717 APValue DestroyedValue, QualType Type,
14718 SourceLocation Loc, Expr::EvalStatus &EStatus) {
14719 EvalInfo Info(Ctx, EStatus, EvalInfo::EM_ConstantExpression);
14720 Info.setEvaluatingDecl(Base, DestroyedValue,
14721 EvalInfo::EvaluatingDeclKind::Dtor);
14722 Info.InConstantContext = true;
14723
14724 LValue LVal;
14725 LVal.set(Base);
14726
14727 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
14728 EStatus.HasSideEffects)
14729 return false;
14730
14731 if (!Info.discardCleanups())
14732 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14733
14734 return true;
14735 }
14736
EvaluateAsConstantExpr(EvalResult & Result,const ASTContext & Ctx,ConstantExprKind Kind) const14737 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
14738 ConstantExprKind Kind) const {
14739 assert(!isValueDependent() &&
14740 "Expression evaluator can't be called on a dependent expression.");
14741
14742 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14743 EvalInfo Info(Ctx, Result, EM);
14744 Info.InConstantContext = true;
14745
14746 // The type of the object we're initializing is 'const T' for a class NTTP.
14747 QualType T = getType();
14748 if (Kind == ConstantExprKind::ClassTemplateArgument)
14749 T.addConst();
14750
14751 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
14752 // represent the result of the evaluation. CheckConstantExpression ensures
14753 // this doesn't escape.
14754 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
14755 APValue::LValueBase Base(&BaseMTE);
14756
14757 Info.setEvaluatingDecl(Base, Result.Val);
14758 LValue LVal;
14759 LVal.set(Base);
14760
14761 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
14762 return false;
14763
14764 if (!Info.discardCleanups())
14765 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14766
14767 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14768 Result.Val, Kind))
14769 return false;
14770 if (!CheckMemoryLeaks(Info))
14771 return false;
14772
14773 // If this is a class template argument, it's required to have constant
14774 // destruction too.
14775 if (Kind == ConstantExprKind::ClassTemplateArgument &&
14776 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result) ||
14777 Result.HasSideEffects)) {
14778 // FIXME: Prefix a note to indicate that the problem is lack of constant
14779 // destruction.
14780 return false;
14781 }
14782
14783 return true;
14784 }
14785
EvaluateAsInitializer(APValue & Value,const ASTContext & Ctx,const VarDecl * VD,SmallVectorImpl<PartialDiagnosticAt> & Notes,bool IsConstantInitialization) const14786 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
14787 const VarDecl *VD,
14788 SmallVectorImpl<PartialDiagnosticAt> &Notes,
14789 bool IsConstantInitialization) const {
14790 assert(!isValueDependent() &&
14791 "Expression evaluator can't be called on a dependent expression.");
14792
14793 // FIXME: Evaluating initializers for large array and record types can cause
14794 // performance problems. Only do so in C++11 for now.
14795 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
14796 !Ctx.getLangOpts().CPlusPlus11)
14797 return false;
14798
14799 Expr::EvalStatus EStatus;
14800 EStatus.Diag = &Notes;
14801
14802 EvalInfo Info(Ctx, EStatus,
14803 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
14804 ? EvalInfo::EM_ConstantExpression
14805 : EvalInfo::EM_ConstantFold);
14806 Info.setEvaluatingDecl(VD, Value);
14807 Info.InConstantContext = IsConstantInitialization;
14808
14809 SourceLocation DeclLoc = VD->getLocation();
14810 QualType DeclTy = VD->getType();
14811
14812 if (Info.EnableNewConstInterp) {
14813 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
14814 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
14815 return false;
14816 } else {
14817 LValue LVal;
14818 LVal.set(VD);
14819
14820 if (!EvaluateInPlace(Value, Info, LVal, this,
14821 /*AllowNonLiteralTypes=*/true) ||
14822 EStatus.HasSideEffects)
14823 return false;
14824
14825 // At this point, any lifetime-extended temporaries are completely
14826 // initialized.
14827 Info.performLifetimeExtension();
14828
14829 if (!Info.discardCleanups())
14830 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14831 }
14832 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
14833 ConstantExprKind::Normal) &&
14834 CheckMemoryLeaks(Info);
14835 }
14836
evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> & Notes) const14837 bool VarDecl::evaluateDestruction(
14838 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14839 Expr::EvalStatus EStatus;
14840 EStatus.Diag = &Notes;
14841
14842 // Make a copy of the value for the destructor to mutate, if we know it.
14843 // Otherwise, treat the value as default-initialized; if the destructor works
14844 // anyway, then the destruction is constant (and must be essentially empty).
14845 APValue DestroyedValue;
14846 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
14847 DestroyedValue = *getEvaluatedValue();
14848 else if (!getDefaultInitValue(getType(), DestroyedValue))
14849 return false;
14850
14851 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
14852 getType(), getLocation(), EStatus) ||
14853 EStatus.HasSideEffects)
14854 return false;
14855
14856 ensureEvaluatedStmt()->HasConstantDestruction = true;
14857 return true;
14858 }
14859
14860 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14861 /// constant folded, but discard the result.
isEvaluatable(const ASTContext & Ctx,SideEffectsKind SEK) const14862 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14863 assert(!isValueDependent() &&
14864 "Expression evaluator can't be called on a dependent expression.");
14865
14866 EvalResult Result;
14867 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14868 !hasUnacceptableSideEffect(Result, SEK);
14869 }
14870
EvaluateKnownConstInt(const ASTContext & Ctx,SmallVectorImpl<PartialDiagnosticAt> * Diag) const14871 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14872 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14873 assert(!isValueDependent() &&
14874 "Expression evaluator can't be called on a dependent expression.");
14875
14876 EvalResult EVResult;
14877 EVResult.Diag = Diag;
14878 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14879 Info.InConstantContext = true;
14880
14881 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14882 (void)Result;
14883 assert(Result && "Could not evaluate expression");
14884 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14885
14886 return EVResult.Val.getInt();
14887 }
14888
EvaluateKnownConstIntCheckOverflow(const ASTContext & Ctx,SmallVectorImpl<PartialDiagnosticAt> * Diag) const14889 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14890 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14891 assert(!isValueDependent() &&
14892 "Expression evaluator can't be called on a dependent expression.");
14893
14894 EvalResult EVResult;
14895 EVResult.Diag = Diag;
14896 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14897 Info.InConstantContext = true;
14898 Info.CheckingForUndefinedBehavior = true;
14899
14900 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14901 (void)Result;
14902 assert(Result && "Could not evaluate expression");
14903 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14904
14905 return EVResult.Val.getInt();
14906 }
14907
EvaluateForOverflow(const ASTContext & Ctx) const14908 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
14909 assert(!isValueDependent() &&
14910 "Expression evaluator can't be called on a dependent expression.");
14911
14912 bool IsConst;
14913 EvalResult EVResult;
14914 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
14915 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14916 Info.CheckingForUndefinedBehavior = true;
14917 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
14918 }
14919 }
14920
isGlobalLValue() const14921 bool Expr::EvalResult::isGlobalLValue() const {
14922 assert(Val.isLValue());
14923 return IsGlobalLValue(Val.getLValueBase());
14924 }
14925
14926 /// isIntegerConstantExpr - this recursive routine will test if an expression is
14927 /// an integer constant expression.
14928
14929 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
14930 /// comma, etc
14931
14932 // CheckICE - This function does the fundamental ICE checking: the returned
14933 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
14934 // and a (possibly null) SourceLocation indicating the location of the problem.
14935 //
14936 // Note that to reduce code duplication, this helper does no evaluation
14937 // itself; the caller checks whether the expression is evaluatable, and
14938 // in the rare cases where CheckICE actually cares about the evaluated
14939 // value, it calls into Evaluate.
14940
14941 namespace {
14942
14943 enum ICEKind {
14944 /// This expression is an ICE.
14945 IK_ICE,
14946 /// This expression is not an ICE, but if it isn't evaluated, it's
14947 /// a legal subexpression for an ICE. This return value is used to handle
14948 /// the comma operator in C99 mode, and non-constant subexpressions.
14949 IK_ICEIfUnevaluated,
14950 /// This expression is not an ICE, and is not a legal subexpression for one.
14951 IK_NotICE
14952 };
14953
14954 struct ICEDiag {
14955 ICEKind Kind;
14956 SourceLocation Loc;
14957
ICEDiag__anon4717f8733511::ICEDiag14958 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
14959 };
14960
14961 }
14962
NoDiag()14963 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
14964
Worst(ICEDiag A,ICEDiag B)14965 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
14966
CheckEvalInICE(const Expr * E,const ASTContext & Ctx)14967 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
14968 Expr::EvalResult EVResult;
14969 Expr::EvalStatus Status;
14970 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14971
14972 Info.InConstantContext = true;
14973 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
14974 !EVResult.Val.isInt())
14975 return ICEDiag(IK_NotICE, E->getBeginLoc());
14976
14977 return NoDiag();
14978 }
14979
CheckICE(const Expr * E,const ASTContext & Ctx)14980 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
14981 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
14982 if (!E->getType()->isIntegralOrEnumerationType())
14983 return ICEDiag(IK_NotICE, E->getBeginLoc());
14984
14985 switch (E->getStmtClass()) {
14986 #define ABSTRACT_STMT(Node)
14987 #define STMT(Node, Base) case Expr::Node##Class:
14988 #define EXPR(Node, Base)
14989 #include "clang/AST/StmtNodes.inc"
14990 case Expr::PredefinedExprClass:
14991 case Expr::FloatingLiteralClass:
14992 case Expr::ImaginaryLiteralClass:
14993 case Expr::StringLiteralClass:
14994 case Expr::ArraySubscriptExprClass:
14995 case Expr::MatrixSubscriptExprClass:
14996 case Expr::OMPArraySectionExprClass:
14997 case Expr::OMPArrayShapingExprClass:
14998 case Expr::OMPIteratorExprClass:
14999 case Expr::MemberExprClass:
15000 case Expr::CompoundAssignOperatorClass:
15001 case Expr::CompoundLiteralExprClass:
15002 case Expr::ExtVectorElementExprClass:
15003 case Expr::DesignatedInitExprClass:
15004 case Expr::ArrayInitLoopExprClass:
15005 case Expr::ArrayInitIndexExprClass:
15006 case Expr::NoInitExprClass:
15007 case Expr::DesignatedInitUpdateExprClass:
15008 case Expr::ImplicitValueInitExprClass:
15009 case Expr::ParenListExprClass:
15010 case Expr::VAArgExprClass:
15011 case Expr::AddrLabelExprClass:
15012 case Expr::StmtExprClass:
15013 case Expr::CXXMemberCallExprClass:
15014 case Expr::CUDAKernelCallExprClass:
15015 case Expr::CXXAddrspaceCastExprClass:
15016 case Expr::CXXDynamicCastExprClass:
15017 case Expr::CXXTypeidExprClass:
15018 case Expr::CXXUuidofExprClass:
15019 case Expr::MSPropertyRefExprClass:
15020 case Expr::MSPropertySubscriptExprClass:
15021 case Expr::CXXNullPtrLiteralExprClass:
15022 case Expr::UserDefinedLiteralClass:
15023 case Expr::CXXThisExprClass:
15024 case Expr::CXXThrowExprClass:
15025 case Expr::CXXNewExprClass:
15026 case Expr::CXXDeleteExprClass:
15027 case Expr::CXXPseudoDestructorExprClass:
15028 case Expr::UnresolvedLookupExprClass:
15029 case Expr::TypoExprClass:
15030 case Expr::RecoveryExprClass:
15031 case Expr::DependentScopeDeclRefExprClass:
15032 case Expr::CXXConstructExprClass:
15033 case Expr::CXXInheritedCtorInitExprClass:
15034 case Expr::CXXStdInitializerListExprClass:
15035 case Expr::CXXBindTemporaryExprClass:
15036 case Expr::ExprWithCleanupsClass:
15037 case Expr::CXXTemporaryObjectExprClass:
15038 case Expr::CXXUnresolvedConstructExprClass:
15039 case Expr::CXXDependentScopeMemberExprClass:
15040 case Expr::UnresolvedMemberExprClass:
15041 case Expr::ObjCStringLiteralClass:
15042 case Expr::ObjCBoxedExprClass:
15043 case Expr::ObjCArrayLiteralClass:
15044 case Expr::ObjCDictionaryLiteralClass:
15045 case Expr::ObjCEncodeExprClass:
15046 case Expr::ObjCMessageExprClass:
15047 case Expr::ObjCSelectorExprClass:
15048 case Expr::ObjCProtocolExprClass:
15049 case Expr::ObjCIvarRefExprClass:
15050 case Expr::ObjCPropertyRefExprClass:
15051 case Expr::ObjCSubscriptRefExprClass:
15052 case Expr::ObjCIsaExprClass:
15053 case Expr::ObjCAvailabilityCheckExprClass:
15054 case Expr::ShuffleVectorExprClass:
15055 case Expr::ConvertVectorExprClass:
15056 case Expr::BlockExprClass:
15057 case Expr::NoStmtClass:
15058 case Expr::OpaqueValueExprClass:
15059 case Expr::PackExpansionExprClass:
15060 case Expr::SubstNonTypeTemplateParmPackExprClass:
15061 case Expr::FunctionParmPackExprClass:
15062 case Expr::AsTypeExprClass:
15063 case Expr::ObjCIndirectCopyRestoreExprClass:
15064 case Expr::MaterializeTemporaryExprClass:
15065 case Expr::PseudoObjectExprClass:
15066 case Expr::AtomicExprClass:
15067 case Expr::LambdaExprClass:
15068 case Expr::CXXFoldExprClass:
15069 case Expr::CoawaitExprClass:
15070 case Expr::DependentCoawaitExprClass:
15071 case Expr::CoyieldExprClass:
15072 return ICEDiag(IK_NotICE, E->getBeginLoc());
15073
15074 case Expr::InitListExprClass: {
15075 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15076 // form "T x = { a };" is equivalent to "T x = a;".
15077 // Unless we're initializing a reference, T is a scalar as it is known to be
15078 // of integral or enumeration type.
15079 if (E->isRValue())
15080 if (cast<InitListExpr>(E)->getNumInits() == 1)
15081 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15082 return ICEDiag(IK_NotICE, E->getBeginLoc());
15083 }
15084
15085 case Expr::SizeOfPackExprClass:
15086 case Expr::GNUNullExprClass:
15087 case Expr::SourceLocExprClass:
15088 return NoDiag();
15089
15090 case Expr::SubstNonTypeTemplateParmExprClass:
15091 return
15092 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15093
15094 case Expr::ConstantExprClass:
15095 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15096
15097 case Expr::ParenExprClass:
15098 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15099 case Expr::GenericSelectionExprClass:
15100 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15101 case Expr::IntegerLiteralClass:
15102 case Expr::FixedPointLiteralClass:
15103 case Expr::CharacterLiteralClass:
15104 case Expr::ObjCBoolLiteralExprClass:
15105 case Expr::CXXBoolLiteralExprClass:
15106 case Expr::CXXScalarValueInitExprClass:
15107 case Expr::TypeTraitExprClass:
15108 case Expr::ConceptSpecializationExprClass:
15109 case Expr::RequiresExprClass:
15110 case Expr::ArrayTypeTraitExprClass:
15111 case Expr::ExpressionTraitExprClass:
15112 case Expr::CXXNoexceptExprClass:
15113 return NoDiag();
15114 case Expr::CallExprClass:
15115 case Expr::CXXOperatorCallExprClass: {
15116 // C99 6.6/3 allows function calls within unevaluated subexpressions of
15117 // constant expressions, but they can never be ICEs because an ICE cannot
15118 // contain an operand of (pointer to) function type.
15119 const CallExpr *CE = cast<CallExpr>(E);
15120 if (CE->getBuiltinCallee())
15121 return CheckEvalInICE(E, Ctx);
15122 return ICEDiag(IK_NotICE, E->getBeginLoc());
15123 }
15124 case Expr::CXXRewrittenBinaryOperatorClass:
15125 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15126 Ctx);
15127 case Expr::DeclRefExprClass: {
15128 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15129 if (isa<EnumConstantDecl>(D))
15130 return NoDiag();
15131
15132 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15133 // integer variables in constant expressions:
15134 //
15135 // C++ 7.1.5.1p2
15136 // A variable of non-volatile const-qualified integral or enumeration
15137 // type initialized by an ICE can be used in ICEs.
15138 //
15139 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15140 // that mode, use of reference variables should not be allowed.
15141 const VarDecl *VD = dyn_cast<VarDecl>(D);
15142 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15143 !VD->getType()->isReferenceType())
15144 return NoDiag();
15145
15146 return ICEDiag(IK_NotICE, E->getBeginLoc());
15147 }
15148 case Expr::UnaryOperatorClass: {
15149 const UnaryOperator *Exp = cast<UnaryOperator>(E);
15150 switch (Exp->getOpcode()) {
15151 case UO_PostInc:
15152 case UO_PostDec:
15153 case UO_PreInc:
15154 case UO_PreDec:
15155 case UO_AddrOf:
15156 case UO_Deref:
15157 case UO_Coawait:
15158 // C99 6.6/3 allows increment and decrement within unevaluated
15159 // subexpressions of constant expressions, but they can never be ICEs
15160 // because an ICE cannot contain an lvalue operand.
15161 return ICEDiag(IK_NotICE, E->getBeginLoc());
15162 case UO_Extension:
15163 case UO_LNot:
15164 case UO_Plus:
15165 case UO_Minus:
15166 case UO_Not:
15167 case UO_Real:
15168 case UO_Imag:
15169 return CheckICE(Exp->getSubExpr(), Ctx);
15170 }
15171 llvm_unreachable("invalid unary operator class");
15172 }
15173 case Expr::OffsetOfExprClass: {
15174 // Note that per C99, offsetof must be an ICE. And AFAIK, using
15175 // EvaluateAsRValue matches the proposed gcc behavior for cases like
15176 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
15177 // compliance: we should warn earlier for offsetof expressions with
15178 // array subscripts that aren't ICEs, and if the array subscripts
15179 // are ICEs, the value of the offsetof must be an integer constant.
15180 return CheckEvalInICE(E, Ctx);
15181 }
15182 case Expr::UnaryExprOrTypeTraitExprClass: {
15183 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15184 if ((Exp->getKind() == UETT_SizeOf) &&
15185 Exp->getTypeOfArgument()->isVariableArrayType())
15186 return ICEDiag(IK_NotICE, E->getBeginLoc());
15187 return NoDiag();
15188 }
15189 case Expr::BinaryOperatorClass: {
15190 const BinaryOperator *Exp = cast<BinaryOperator>(E);
15191 switch (Exp->getOpcode()) {
15192 case BO_PtrMemD:
15193 case BO_PtrMemI:
15194 case BO_Assign:
15195 case BO_MulAssign:
15196 case BO_DivAssign:
15197 case BO_RemAssign:
15198 case BO_AddAssign:
15199 case BO_SubAssign:
15200 case BO_ShlAssign:
15201 case BO_ShrAssign:
15202 case BO_AndAssign:
15203 case BO_XorAssign:
15204 case BO_OrAssign:
15205 // C99 6.6/3 allows assignments within unevaluated subexpressions of
15206 // constant expressions, but they can never be ICEs because an ICE cannot
15207 // contain an lvalue operand.
15208 return ICEDiag(IK_NotICE, E->getBeginLoc());
15209
15210 case BO_Mul:
15211 case BO_Div:
15212 case BO_Rem:
15213 case BO_Add:
15214 case BO_Sub:
15215 case BO_Shl:
15216 case BO_Shr:
15217 case BO_LT:
15218 case BO_GT:
15219 case BO_LE:
15220 case BO_GE:
15221 case BO_EQ:
15222 case BO_NE:
15223 case BO_And:
15224 case BO_Xor:
15225 case BO_Or:
15226 case BO_Comma:
15227 case BO_Cmp: {
15228 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15229 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15230 if (Exp->getOpcode() == BO_Div ||
15231 Exp->getOpcode() == BO_Rem) {
15232 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15233 // we don't evaluate one.
15234 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15235 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15236 if (REval == 0)
15237 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15238 if (REval.isSigned() && REval.isAllOnesValue()) {
15239 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15240 if (LEval.isMinSignedValue())
15241 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15242 }
15243 }
15244 }
15245 if (Exp->getOpcode() == BO_Comma) {
15246 if (Ctx.getLangOpts().C99) {
15247 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15248 // if it isn't evaluated.
15249 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15250 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15251 } else {
15252 // In both C89 and C++, commas in ICEs are illegal.
15253 return ICEDiag(IK_NotICE, E->getBeginLoc());
15254 }
15255 }
15256 return Worst(LHSResult, RHSResult);
15257 }
15258 case BO_LAnd:
15259 case BO_LOr: {
15260 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15261 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15262 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15263 // Rare case where the RHS has a comma "side-effect"; we need
15264 // to actually check the condition to see whether the side
15265 // with the comma is evaluated.
15266 if ((Exp->getOpcode() == BO_LAnd) !=
15267 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15268 return RHSResult;
15269 return NoDiag();
15270 }
15271
15272 return Worst(LHSResult, RHSResult);
15273 }
15274 }
15275 llvm_unreachable("invalid binary operator kind");
15276 }
15277 case Expr::ImplicitCastExprClass:
15278 case Expr::CStyleCastExprClass:
15279 case Expr::CXXFunctionalCastExprClass:
15280 case Expr::CXXStaticCastExprClass:
15281 case Expr::CXXReinterpretCastExprClass:
15282 case Expr::CXXConstCastExprClass:
15283 case Expr::ObjCBridgedCastExprClass: {
15284 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15285 if (isa<ExplicitCastExpr>(E)) {
15286 if (const FloatingLiteral *FL
15287 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15288 unsigned DestWidth = Ctx.getIntWidth(E->getType());
15289 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15290 APSInt IgnoredVal(DestWidth, !DestSigned);
15291 bool Ignored;
15292 // If the value does not fit in the destination type, the behavior is
15293 // undefined, so we are not required to treat it as a constant
15294 // expression.
15295 if (FL->getValue().convertToInteger(IgnoredVal,
15296 llvm::APFloat::rmTowardZero,
15297 &Ignored) & APFloat::opInvalidOp)
15298 return ICEDiag(IK_NotICE, E->getBeginLoc());
15299 return NoDiag();
15300 }
15301 }
15302 switch (cast<CastExpr>(E)->getCastKind()) {
15303 case CK_LValueToRValue:
15304 case CK_AtomicToNonAtomic:
15305 case CK_NonAtomicToAtomic:
15306 case CK_NoOp:
15307 case CK_IntegralToBoolean:
15308 case CK_IntegralCast:
15309 return CheckICE(SubExpr, Ctx);
15310 default:
15311 return ICEDiag(IK_NotICE, E->getBeginLoc());
15312 }
15313 }
15314 case Expr::BinaryConditionalOperatorClass: {
15315 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15316 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15317 if (CommonResult.Kind == IK_NotICE) return CommonResult;
15318 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15319 if (FalseResult.Kind == IK_NotICE) return FalseResult;
15320 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15321 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15322 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15323 return FalseResult;
15324 }
15325 case Expr::ConditionalOperatorClass: {
15326 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15327 // If the condition (ignoring parens) is a __builtin_constant_p call,
15328 // then only the true side is actually considered in an integer constant
15329 // expression, and it is fully evaluated. This is an important GNU
15330 // extension. See GCC PR38377 for discussion.
15331 if (const CallExpr *CallCE
15332 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15333 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15334 return CheckEvalInICE(E, Ctx);
15335 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15336 if (CondResult.Kind == IK_NotICE)
15337 return CondResult;
15338
15339 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15340 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15341
15342 if (TrueResult.Kind == IK_NotICE)
15343 return TrueResult;
15344 if (FalseResult.Kind == IK_NotICE)
15345 return FalseResult;
15346 if (CondResult.Kind == IK_ICEIfUnevaluated)
15347 return CondResult;
15348 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15349 return NoDiag();
15350 // Rare case where the diagnostics depend on which side is evaluated
15351 // Note that if we get here, CondResult is 0, and at least one of
15352 // TrueResult and FalseResult is non-zero.
15353 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15354 return FalseResult;
15355 return TrueResult;
15356 }
15357 case Expr::CXXDefaultArgExprClass:
15358 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15359 case Expr::CXXDefaultInitExprClass:
15360 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15361 case Expr::ChooseExprClass: {
15362 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15363 }
15364 case Expr::BuiltinBitCastExprClass: {
15365 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15366 return ICEDiag(IK_NotICE, E->getBeginLoc());
15367 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15368 }
15369 }
15370
15371 llvm_unreachable("Invalid StmtClass!");
15372 }
15373
15374 /// Evaluate an expression as a C++11 integral constant expression.
EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext & Ctx,const Expr * E,llvm::APSInt * Value,SourceLocation * Loc)15375 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15376 const Expr *E,
15377 llvm::APSInt *Value,
15378 SourceLocation *Loc) {
15379 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15380 if (Loc) *Loc = E->getExprLoc();
15381 return false;
15382 }
15383
15384 APValue Result;
15385 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15386 return false;
15387
15388 if (!Result.isInt()) {
15389 if (Loc) *Loc = E->getExprLoc();
15390 return false;
15391 }
15392
15393 if (Value) *Value = Result.getInt();
15394 return true;
15395 }
15396
isIntegerConstantExpr(const ASTContext & Ctx,SourceLocation * Loc) const15397 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15398 SourceLocation *Loc) const {
15399 assert(!isValueDependent() &&
15400 "Expression evaluator can't be called on a dependent expression.");
15401
15402 if (Ctx.getLangOpts().CPlusPlus11)
15403 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15404
15405 ICEDiag D = CheckICE(this, Ctx);
15406 if (D.Kind != IK_ICE) {
15407 if (Loc) *Loc = D.Loc;
15408 return false;
15409 }
15410 return true;
15411 }
15412
getIntegerConstantExpr(const ASTContext & Ctx,SourceLocation * Loc,bool isEvaluated) const15413 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15414 SourceLocation *Loc,
15415 bool isEvaluated) const {
15416 assert(!isValueDependent() &&
15417 "Expression evaluator can't be called on a dependent expression.");
15418
15419 APSInt Value;
15420
15421 if (Ctx.getLangOpts().CPlusPlus11) {
15422 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15423 return Value;
15424 return None;
15425 }
15426
15427 if (!isIntegerConstantExpr(Ctx, Loc))
15428 return None;
15429
15430 // The only possible side-effects here are due to UB discovered in the
15431 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15432 // required to treat the expression as an ICE, so we produce the folded
15433 // value.
15434 EvalResult ExprResult;
15435 Expr::EvalStatus Status;
15436 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15437 Info.InConstantContext = true;
15438
15439 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15440 llvm_unreachable("ICE cannot be evaluated!");
15441
15442 return ExprResult.Val.getInt();
15443 }
15444
isCXX98IntegralConstantExpr(const ASTContext & Ctx) const15445 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15446 assert(!isValueDependent() &&
15447 "Expression evaluator can't be called on a dependent expression.");
15448
15449 return CheckICE(this, Ctx).Kind == IK_ICE;
15450 }
15451
isCXX11ConstantExpr(const ASTContext & Ctx,APValue * Result,SourceLocation * Loc) const15452 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15453 SourceLocation *Loc) const {
15454 assert(!isValueDependent() &&
15455 "Expression evaluator can't be called on a dependent expression.");
15456
15457 // We support this checking in C++98 mode in order to diagnose compatibility
15458 // issues.
15459 assert(Ctx.getLangOpts().CPlusPlus);
15460
15461 // Build evaluation settings.
15462 Expr::EvalStatus Status;
15463 SmallVector<PartialDiagnosticAt, 8> Diags;
15464 Status.Diag = &Diags;
15465 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15466
15467 APValue Scratch;
15468 bool IsConstExpr =
15469 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15470 // FIXME: We don't produce a diagnostic for this, but the callers that
15471 // call us on arbitrary full-expressions should generally not care.
15472 Info.discardCleanups() && !Status.HasSideEffects;
15473
15474 if (!Diags.empty()) {
15475 IsConstExpr = false;
15476 if (Loc) *Loc = Diags[0].first;
15477 } else if (!IsConstExpr) {
15478 // FIXME: This shouldn't happen.
15479 if (Loc) *Loc = getExprLoc();
15480 }
15481
15482 return IsConstExpr;
15483 }
15484
EvaluateWithSubstitution(APValue & Value,ASTContext & Ctx,const FunctionDecl * Callee,ArrayRef<const Expr * > Args,const Expr * This) const15485 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15486 const FunctionDecl *Callee,
15487 ArrayRef<const Expr*> Args,
15488 const Expr *This) const {
15489 assert(!isValueDependent() &&
15490 "Expression evaluator can't be called on a dependent expression.");
15491
15492 Expr::EvalStatus Status;
15493 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15494 Info.InConstantContext = true;
15495
15496 LValue ThisVal;
15497 const LValue *ThisPtr = nullptr;
15498 if (This) {
15499 #ifndef NDEBUG
15500 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15501 assert(MD && "Don't provide `this` for non-methods.");
15502 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15503 #endif
15504 if (!This->isValueDependent() &&
15505 EvaluateObjectArgument(Info, This, ThisVal) &&
15506 !Info.EvalStatus.HasSideEffects)
15507 ThisPtr = &ThisVal;
15508
15509 // Ignore any side-effects from a failed evaluation. This is safe because
15510 // they can't interfere with any other argument evaluation.
15511 Info.EvalStatus.HasSideEffects = false;
15512 }
15513
15514 CallRef Call = Info.CurrentCall->createCall(Callee);
15515 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15516 I != E; ++I) {
15517 unsigned Idx = I - Args.begin();
15518 if (Idx >= Callee->getNumParams())
15519 break;
15520 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15521 if ((*I)->isValueDependent() ||
15522 !EvaluateCallArg(PVD, *I, Call, Info) ||
15523 Info.EvalStatus.HasSideEffects) {
15524 // If evaluation fails, throw away the argument entirely.
15525 if (APValue *Slot = Info.getParamSlot(Call, PVD))
15526 *Slot = APValue();
15527 }
15528
15529 // Ignore any side-effects from a failed evaluation. This is safe because
15530 // they can't interfere with any other argument evaluation.
15531 Info.EvalStatus.HasSideEffects = false;
15532 }
15533
15534 // Parameter cleanups happen in the caller and are not part of this
15535 // evaluation.
15536 Info.discardCleanups();
15537 Info.EvalStatus.HasSideEffects = false;
15538
15539 // Build fake call to Callee.
15540 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15541 // FIXME: Missing ExprWithCleanups in enable_if conditions?
15542 FullExpressionRAII Scope(Info);
15543 return Evaluate(Value, Info, this) && Scope.destroy() &&
15544 !Info.EvalStatus.HasSideEffects;
15545 }
15546
isPotentialConstantExpr(const FunctionDecl * FD,SmallVectorImpl<PartialDiagnosticAt> & Diags)15547 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15548 SmallVectorImpl<
15549 PartialDiagnosticAt> &Diags) {
15550 // FIXME: It would be useful to check constexpr function templates, but at the
15551 // moment the constant expression evaluator cannot cope with the non-rigorous
15552 // ASTs which we build for dependent expressions.
15553 if (FD->isDependentContext())
15554 return true;
15555
15556 // Bail out if a constexpr constructor has an initializer that contains an
15557 // error. We deliberately don't produce a diagnostic, as we have produced a
15558 // relevant diagnostic when parsing the error initializer.
15559 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15560 for (const auto *InitExpr : Ctor->inits()) {
15561 if (InitExpr->getInit() && InitExpr->getInit()->containsErrors())
15562 return false;
15563 }
15564 }
15565 Expr::EvalStatus Status;
15566 Status.Diag = &Diags;
15567
15568 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15569 Info.InConstantContext = true;
15570 Info.CheckingPotentialConstantExpression = true;
15571
15572 // The constexpr VM attempts to compile all methods to bytecode here.
15573 if (Info.EnableNewConstInterp) {
15574 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15575 return Diags.empty();
15576 }
15577
15578 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15579 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15580
15581 // Fabricate an arbitrary expression on the stack and pretend that it
15582 // is a temporary being used as the 'this' pointer.
15583 LValue This;
15584 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15585 This.set({&VIE, Info.CurrentCall->Index});
15586
15587 ArrayRef<const Expr*> Args;
15588
15589 APValue Scratch;
15590 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15591 // Evaluate the call as a constant initializer, to allow the construction
15592 // of objects of non-literal types.
15593 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15594 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15595 } else {
15596 SourceLocation Loc = FD->getLocation();
15597 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15598 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15599 }
15600
15601 return Diags.empty();
15602 }
15603
isPotentialConstantExprUnevaluated(Expr * E,const FunctionDecl * FD,SmallVectorImpl<PartialDiagnosticAt> & Diags)15604 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15605 const FunctionDecl *FD,
15606 SmallVectorImpl<
15607 PartialDiagnosticAt> &Diags) {
15608 assert(!E->isValueDependent() &&
15609 "Expression evaluator can't be called on a dependent expression.");
15610
15611 Expr::EvalStatus Status;
15612 Status.Diag = &Diags;
15613
15614 EvalInfo Info(FD->getASTContext(), Status,
15615 EvalInfo::EM_ConstantExpressionUnevaluated);
15616 Info.InConstantContext = true;
15617 Info.CheckingPotentialConstantExpression = true;
15618
15619 // Fabricate a call stack frame to give the arguments a plausible cover story.
15620 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15621
15622 APValue ResultScratch;
15623 Evaluate(ResultScratch, Info, E);
15624 return Diags.empty();
15625 }
15626
tryEvaluateObjectSize(uint64_t & Result,ASTContext & Ctx,unsigned Type) const15627 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15628 unsigned Type) const {
15629 if (!getType()->isPointerType())
15630 return false;
15631
15632 Expr::EvalStatus Status;
15633 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15634 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15635 }
15636