xref: /openbsd/gnu/llvm/clang/lib/AST/ExprConstant.cpp (revision 12c85518)
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/SmallBitVector.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/SaveAndRestore.h"
58 #include "llvm/Support/TimeProfiler.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include <cstring>
61 #include <functional>
62 #include <optional>
63 
64 #define DEBUG_TYPE "exprconstant"
65 
66 using namespace clang;
67 using llvm::APFixedPoint;
68 using llvm::APInt;
69 using llvm::APSInt;
70 using llvm::APFloat;
71 using llvm::FixedPointSemantics;
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->isPRValue())
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     if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
112       return DirectCallee->getAttr<AllocSizeAttr>();
113     if (const Decl *IndirectCallee = CE->getCalleeDecl())
114       return IndirectCallee->getAttr<AllocSizeAttr>();
115     return nullptr;
116   }
117 
118   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119   /// This will look through a single cast.
120   ///
121   /// Returns null if we couldn't unwrap a function with alloc_size.
tryUnwrapAllocSizeCall(const Expr * E)122   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123     if (!E->getType()->isPointerType())
124       return nullptr;
125 
126     E = E->IgnoreParens();
127     // If we're doing a variable assignment from e.g. malloc(N), there will
128     // probably be a cast of some kind. In exotic cases, we might also see a
129     // top-level ExprWithCleanups. Ignore them either way.
130     if (const auto *FE = dyn_cast<FullExpr>(E))
131       E = FE->getSubExpr()->IgnoreParens();
132 
133     if (const auto *Cast = dyn_cast<CastExpr>(E))
134       E = Cast->getSubExpr()->IgnoreParens();
135 
136     if (const auto *CE = dyn_cast<CallExpr>(E))
137       return getAllocSizeAttr(CE) ? CE : nullptr;
138     return nullptr;
139   }
140 
141   /// Determines whether or not the given Base contains a call to a function
142   /// with the alloc_size attribute.
isBaseAnAllocSizeCall(APValue::LValueBase Base)143   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
144     const auto *E = Base.dyn_cast<const Expr *>();
145     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
146   }
147 
148   /// Determines whether the given kind of constant expression is only ever
149   /// used for name mangling. If so, it's permitted to reference things that we
150   /// can't generate code for (in particular, dllimported functions).
isForManglingOnly(ConstantExprKind Kind)151   static bool isForManglingOnly(ConstantExprKind Kind) {
152     switch (Kind) {
153     case ConstantExprKind::Normal:
154     case ConstantExprKind::ClassTemplateArgument:
155     case ConstantExprKind::ImmediateInvocation:
156       // Note that non-type template arguments of class type are emitted as
157       // template parameter objects.
158       return false;
159 
160     case ConstantExprKind::NonClassTemplateArgument:
161       return true;
162     }
163     llvm_unreachable("unknown ConstantExprKind");
164   }
165 
isTemplateArgument(ConstantExprKind Kind)166   static bool isTemplateArgument(ConstantExprKind Kind) {
167     switch (Kind) {
168     case ConstantExprKind::Normal:
169     case ConstantExprKind::ImmediateInvocation:
170       return false;
171 
172     case ConstantExprKind::ClassTemplateArgument:
173     case ConstantExprKind::NonClassTemplateArgument:
174       return true;
175     }
176     llvm_unreachable("unknown ConstantExprKind");
177   }
178 
179   /// The bound to claim that an array of unknown bound has.
180   /// The value in MostDerivedArraySize is undefined in this case. So, set it
181   /// to an arbitrary value that's likely to loudly break things if it's used.
182   static const uint64_t AssumedSizeForUnsizedArray =
183       std::numeric_limits<uint64_t>::max() / 2;
184 
185   /// Determines if an LValue with the given LValueBase will have an unsized
186   /// array in its designator.
187   /// Find the path length and type of the most-derived subobject in the given
188   /// path, and find the size of the containing array, if any.
189   static unsigned
findMostDerivedSubobject(ASTContext & Ctx,APValue::LValueBase Base,ArrayRef<APValue::LValuePathEntry> Path,uint64_t & ArraySize,QualType & Type,bool & IsArray,bool & FirstEntryIsUnsizedArray)190   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
191                            ArrayRef<APValue::LValuePathEntry> Path,
192                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
193                            bool &FirstEntryIsUnsizedArray) {
194     // This only accepts LValueBases from APValues, and APValues don't support
195     // arrays that lack size info.
196     assert(!isBaseAnAllocSizeCall(Base) &&
197            "Unsized arrays shouldn't appear here");
198     unsigned MostDerivedLength = 0;
199     Type = getType(Base);
200 
201     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
202       if (Type->isArrayType()) {
203         const ArrayType *AT = Ctx.getAsArrayType(Type);
204         Type = AT->getElementType();
205         MostDerivedLength = I + 1;
206         IsArray = true;
207 
208         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
209           ArraySize = CAT->getSize().getZExtValue();
210         } else {
211           assert(I == 0 && "unexpected unsized array designator");
212           FirstEntryIsUnsizedArray = true;
213           ArraySize = AssumedSizeForUnsizedArray;
214         }
215       } else if (Type->isAnyComplexType()) {
216         const ComplexType *CT = Type->castAs<ComplexType>();
217         Type = CT->getElementType();
218         ArraySize = 2;
219         MostDerivedLength = I + 1;
220         IsArray = true;
221       } else if (const FieldDecl *FD = getAsField(Path[I])) {
222         Type = FD->getType();
223         ArraySize = 0;
224         MostDerivedLength = I + 1;
225         IsArray = false;
226       } else {
227         // Path[I] describes a base class.
228         ArraySize = 0;
229         IsArray = false;
230       }
231     }
232     return MostDerivedLength;
233   }
234 
235   /// A path from a glvalue to a subobject of that glvalue.
236   struct SubobjectDesignator {
237     /// True if the subobject was named in a manner not supported by C++11. Such
238     /// lvalues can still be folded, but they are not core constant expressions
239     /// and we cannot perform lvalue-to-rvalue conversions on them.
240     unsigned Invalid : 1;
241 
242     /// Is this a pointer one past the end of an object?
243     unsigned IsOnePastTheEnd : 1;
244 
245     /// Indicator of whether the first entry is an unsized array.
246     unsigned FirstEntryIsAnUnsizedArray : 1;
247 
248     /// Indicator of whether the most-derived object is an array element.
249     unsigned MostDerivedIsArrayElement : 1;
250 
251     /// The length of the path to the most-derived object of which this is a
252     /// subobject.
253     unsigned MostDerivedPathLength : 28;
254 
255     /// The size of the array of which the most-derived object is an element.
256     /// This will always be 0 if the most-derived object is not an array
257     /// element. 0 is not an indicator of whether or not the most-derived object
258     /// is an array, however, because 0-length arrays are allowed.
259     ///
260     /// If the current array is an unsized array, the value of this is
261     /// undefined.
262     uint64_t MostDerivedArraySize;
263 
264     /// The type of the most derived object referred to by this address.
265     QualType MostDerivedType;
266 
267     typedef APValue::LValuePathEntry PathEntry;
268 
269     /// The entries on the path from the glvalue to the designated subobject.
270     SmallVector<PathEntry, 8> Entries;
271 
SubobjectDesignator__anond52d8a670111::SubobjectDesignator272     SubobjectDesignator() : Invalid(true) {}
273 
SubobjectDesignator__anond52d8a670111::SubobjectDesignator274     explicit SubobjectDesignator(QualType T)
275         : Invalid(false), IsOnePastTheEnd(false),
276           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
277           MostDerivedPathLength(0), MostDerivedArraySize(0),
278           MostDerivedType(T) {}
279 
SubobjectDesignator__anond52d8a670111::SubobjectDesignator280     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
281         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
282           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
283           MostDerivedPathLength(0), MostDerivedArraySize(0) {
284       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
285       if (!Invalid) {
286         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
287         ArrayRef<PathEntry> VEntries = V.getLValuePath();
288         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
289         if (V.getLValueBase()) {
290           bool IsArray = false;
291           bool FirstIsUnsizedArray = false;
292           MostDerivedPathLength = findMostDerivedSubobject(
293               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
294               MostDerivedType, IsArray, FirstIsUnsizedArray);
295           MostDerivedIsArrayElement = IsArray;
296           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
297         }
298       }
299     }
300 
truncate__anond52d8a670111::SubobjectDesignator301     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
302                   unsigned NewLength) {
303       if (Invalid)
304         return;
305 
306       assert(Base && "cannot truncate path for null pointer");
307       assert(NewLength <= Entries.size() && "not a truncation");
308 
309       if (NewLength == Entries.size())
310         return;
311       Entries.resize(NewLength);
312 
313       bool IsArray = false;
314       bool FirstIsUnsizedArray = false;
315       MostDerivedPathLength = findMostDerivedSubobject(
316           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
317           FirstIsUnsizedArray);
318       MostDerivedIsArrayElement = IsArray;
319       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
320     }
321 
setInvalid__anond52d8a670111::SubobjectDesignator322     void setInvalid() {
323       Invalid = true;
324       Entries.clear();
325     }
326 
327     /// Determine whether the most derived subobject is an array without a
328     /// known bound.
isMostDerivedAnUnsizedArray__anond52d8a670111::SubobjectDesignator329     bool isMostDerivedAnUnsizedArray() const {
330       assert(!Invalid && "Calling this makes no sense on invalid designators");
331       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
332     }
333 
334     /// Determine what the most derived array's size is. Results in an assertion
335     /// failure if the most derived array lacks a size.
getMostDerivedArraySize__anond52d8a670111::SubobjectDesignator336     uint64_t getMostDerivedArraySize() const {
337       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
338       return MostDerivedArraySize;
339     }
340 
341     /// Determine whether this is a one-past-the-end pointer.
isOnePastTheEnd__anond52d8a670111::SubobjectDesignator342     bool isOnePastTheEnd() const {
343       assert(!Invalid);
344       if (IsOnePastTheEnd)
345         return true;
346       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
347           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
348               MostDerivedArraySize)
349         return true;
350       return false;
351     }
352 
353     /// Get the range of valid index adjustments in the form
354     ///   {maximum value that can be subtracted from this pointer,
355     ///    maximum value that can be added to this pointer}
validIndexAdjustments__anond52d8a670111::SubobjectDesignator356     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
357       if (Invalid || isMostDerivedAnUnsizedArray())
358         return {0, 0};
359 
360       // [expr.add]p4: For the purposes of these operators, a pointer to a
361       // nonarray object behaves the same as a pointer to the first element of
362       // an array of length one with the type of the object as its element type.
363       bool IsArray = MostDerivedPathLength == Entries.size() &&
364                      MostDerivedIsArrayElement;
365       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
366                                     : (uint64_t)IsOnePastTheEnd;
367       uint64_t ArraySize =
368           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
369       return {ArrayIndex, ArraySize - ArrayIndex};
370     }
371 
372     /// Check that this refers to a valid subobject.
isValidSubobject__anond52d8a670111::SubobjectDesignator373     bool isValidSubobject() const {
374       if (Invalid)
375         return false;
376       return !isOnePastTheEnd();
377     }
378     /// Check that this refers to a valid subobject, and if not, produce a
379     /// relevant diagnostic and set the designator as invalid.
380     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
381 
382     /// Get the type of the designated object.
getType__anond52d8a670111::SubobjectDesignator383     QualType getType(ASTContext &Ctx) const {
384       assert(!Invalid && "invalid designator has no subobject type");
385       return MostDerivedPathLength == Entries.size()
386                  ? MostDerivedType
387                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
388     }
389 
390     /// Update this designator to refer to the first element within this array.
addArrayUnchecked__anond52d8a670111::SubobjectDesignator391     void addArrayUnchecked(const ConstantArrayType *CAT) {
392       Entries.push_back(PathEntry::ArrayIndex(0));
393 
394       // This is a most-derived object.
395       MostDerivedType = CAT->getElementType();
396       MostDerivedIsArrayElement = true;
397       MostDerivedArraySize = CAT->getSize().getZExtValue();
398       MostDerivedPathLength = Entries.size();
399     }
400     /// Update this designator to refer to the first element within the array of
401     /// elements of type T. This is an array of unknown size.
addUnsizedArrayUnchecked__anond52d8a670111::SubobjectDesignator402     void addUnsizedArrayUnchecked(QualType ElemTy) {
403       Entries.push_back(PathEntry::ArrayIndex(0));
404 
405       MostDerivedType = ElemTy;
406       MostDerivedIsArrayElement = true;
407       // The value in MostDerivedArraySize is undefined in this case. So, set it
408       // to an arbitrary value that's likely to loudly break things if it's
409       // used.
410       MostDerivedArraySize = AssumedSizeForUnsizedArray;
411       MostDerivedPathLength = Entries.size();
412     }
413     /// Update this designator to refer to the given base or member of this
414     /// object.
addDeclUnchecked__anond52d8a670111::SubobjectDesignator415     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
416       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
417 
418       // If this isn't a base class, it's a new most-derived object.
419       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
420         MostDerivedType = FD->getType();
421         MostDerivedIsArrayElement = false;
422         MostDerivedArraySize = 0;
423         MostDerivedPathLength = Entries.size();
424       }
425     }
426     /// Update this designator to refer to the given complex component.
addComplexUnchecked__anond52d8a670111::SubobjectDesignator427     void addComplexUnchecked(QualType EltTy, bool Imag) {
428       Entries.push_back(PathEntry::ArrayIndex(Imag));
429 
430       // This is technically a most-derived object, though in practice this
431       // is unlikely to matter.
432       MostDerivedType = EltTy;
433       MostDerivedIsArrayElement = true;
434       MostDerivedArraySize = 2;
435       MostDerivedPathLength = Entries.size();
436     }
437     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
438     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
439                                    const APSInt &N);
440     /// Add N to the address of this subobject.
adjustIndex__anond52d8a670111::SubobjectDesignator441     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
442       if (Invalid || !N) return;
443       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
444       if (isMostDerivedAnUnsizedArray()) {
445         diagnoseUnsizedArrayPointerArithmetic(Info, E);
446         // Can't verify -- trust that the user is doing the right thing (or if
447         // not, trust that the caller will catch the bad behavior).
448         // FIXME: Should we reject if this overflows, at least?
449         Entries.back() = PathEntry::ArrayIndex(
450             Entries.back().getAsArrayIndex() + TruncatedN);
451         return;
452       }
453 
454       // [expr.add]p4: For the purposes of these operators, a pointer to a
455       // nonarray object behaves the same as a pointer to the first element of
456       // an array of length one with the type of the object as its element type.
457       bool IsArray = MostDerivedPathLength == Entries.size() &&
458                      MostDerivedIsArrayElement;
459       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
460                                     : (uint64_t)IsOnePastTheEnd;
461       uint64_t ArraySize =
462           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
463 
464       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
465         // Calculate the actual index in a wide enough type, so we can include
466         // it in the note.
467         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
468         (llvm::APInt&)N += ArrayIndex;
469         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
470         diagnosePointerArithmetic(Info, E, N);
471         setInvalid();
472         return;
473       }
474 
475       ArrayIndex += TruncatedN;
476       assert(ArrayIndex <= ArraySize &&
477              "bounds check succeeded for out-of-bounds index");
478 
479       if (IsArray)
480         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
481       else
482         IsOnePastTheEnd = (ArrayIndex != 0);
483     }
484   };
485 
486   /// A scope at the end of which an object can need to be destroyed.
487   enum class ScopeKind {
488     Block,
489     FullExpression,
490     Call
491   };
492 
493   /// A reference to a particular call and its arguments.
494   struct CallRef {
CallRef__anond52d8a670111::CallRef495     CallRef() : OrigCallee(), CallIndex(0), Version() {}
CallRef__anond52d8a670111::CallRef496     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
497         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
498 
operator bool__anond52d8a670111::CallRef499     explicit operator bool() const { return OrigCallee; }
500 
501     /// Get the parameter that the caller initialized, corresponding to the
502     /// given parameter in the callee.
getOrigParam__anond52d8a670111::CallRef503     const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
504       return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
505                         : PVD;
506     }
507 
508     /// The callee at the point where the arguments were evaluated. This might
509     /// be different from the actual callee (a different redeclaration, or a
510     /// virtual override), but this function's parameters are the ones that
511     /// appear in the parameter map.
512     const FunctionDecl *OrigCallee;
513     /// The call index of the frame that holds the argument values.
514     unsigned CallIndex;
515     /// The version of the parameters corresponding to this call.
516     unsigned Version;
517   };
518 
519   /// A stack frame in the constexpr call stack.
520   class CallStackFrame : public interp::Frame {
521   public:
522     EvalInfo &Info;
523 
524     /// Parent - The caller of this stack frame.
525     CallStackFrame *Caller;
526 
527     /// Callee - The function which was called.
528     const FunctionDecl *Callee;
529 
530     /// This - The binding for the this pointer in this call, if any.
531     const LValue *This;
532 
533     /// Information on how to find the arguments to this call. Our arguments
534     /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
535     /// key and this value as the version.
536     CallRef Arguments;
537 
538     /// Source location information about the default argument or default
539     /// initializer expression we're evaluating, if any.
540     CurrentSourceLocExprScope CurSourceLocExprScope;
541 
542     // Note that we intentionally use std::map here so that references to
543     // values are stable.
544     typedef std::pair<const void *, unsigned> MapKeyTy;
545     typedef std::map<MapKeyTy, APValue> MapTy;
546     /// Temporaries - Temporary lvalues materialized within this stack frame.
547     MapTy Temporaries;
548 
549     /// CallLoc - The location of the call expression for this call.
550     SourceLocation CallLoc;
551 
552     /// Index - The call index of this call.
553     unsigned Index;
554 
555     /// The stack of integers for tracking version numbers for temporaries.
556     SmallVector<unsigned, 2> TempVersionStack = {1};
557     unsigned CurTempVersion = TempVersionStack.back();
558 
getTempVersion() const559     unsigned getTempVersion() const { return TempVersionStack.back(); }
560 
pushTempVersion()561     void pushTempVersion() {
562       TempVersionStack.push_back(++CurTempVersion);
563     }
564 
popTempVersion()565     void popTempVersion() {
566       TempVersionStack.pop_back();
567     }
568 
createCall(const FunctionDecl * Callee)569     CallRef createCall(const FunctionDecl *Callee) {
570       return {Callee, Index, ++CurTempVersion};
571     }
572 
573     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
574     // on the overall stack usage of deeply-recursing constexpr evaluations.
575     // (We should cache this map rather than recomputing it repeatedly.)
576     // But let's try this and see how it goes; we can look into caching the map
577     // as a later change.
578 
579     /// LambdaCaptureFields - Mapping from captured variables/this to
580     /// corresponding data members in the closure class.
581     llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
582     FieldDecl *LambdaThisCaptureField;
583 
584     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
585                    const FunctionDecl *Callee, const LValue *This,
586                    CallRef Arguments);
587     ~CallStackFrame();
588 
589     // Return the temporary for Key whose version number is Version.
getTemporary(const void * Key,unsigned Version)590     APValue *getTemporary(const void *Key, unsigned Version) {
591       MapKeyTy KV(Key, Version);
592       auto LB = Temporaries.lower_bound(KV);
593       if (LB != Temporaries.end() && LB->first == KV)
594         return &LB->second;
595       return nullptr;
596     }
597 
598     // Return the current temporary for Key in the map.
getCurrentTemporary(const void * Key)599     APValue *getCurrentTemporary(const void *Key) {
600       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
601       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
602         return &std::prev(UB)->second;
603       return nullptr;
604     }
605 
606     // Return the version number of the current temporary for Key.
getCurrentTemporaryVersion(const void * Key) const607     unsigned getCurrentTemporaryVersion(const void *Key) const {
608       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
609       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
610         return std::prev(UB)->first.second;
611       return 0;
612     }
613 
614     /// Allocate storage for an object of type T in this stack frame.
615     /// Populates LV with a handle to the created object. Key identifies
616     /// the temporary within the stack frame, and must not be reused without
617     /// bumping the temporary version number.
618     template<typename KeyT>
619     APValue &createTemporary(const KeyT *Key, QualType T,
620                              ScopeKind Scope, LValue &LV);
621 
622     /// Allocate storage for a parameter of a function call made in this frame.
623     APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
624 
625     void describe(llvm::raw_ostream &OS) override;
626 
getCaller() const627     Frame *getCaller() const override { return Caller; }
getCallLocation() const628     SourceLocation getCallLocation() const override { return CallLoc; }
getCallee() const629     const FunctionDecl *getCallee() const override { return Callee; }
630 
isStdFunction() const631     bool isStdFunction() const {
632       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
633         if (DC->isStdNamespace())
634           return true;
635       return false;
636     }
637 
638   private:
639     APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
640                          ScopeKind Scope);
641   };
642 
643   /// Temporarily override 'this'.
644   class ThisOverrideRAII {
645   public:
ThisOverrideRAII(CallStackFrame & Frame,const LValue * NewThis,bool Enable)646     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
647         : Frame(Frame), OldThis(Frame.This) {
648       if (Enable)
649         Frame.This = NewThis;
650     }
~ThisOverrideRAII()651     ~ThisOverrideRAII() {
652       Frame.This = OldThis;
653     }
654   private:
655     CallStackFrame &Frame;
656     const LValue *OldThis;
657   };
658 
659   // A shorthand time trace scope struct, prints source range, for example
660   // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
661   class ExprTimeTraceScope {
662   public:
ExprTimeTraceScope(const Expr * E,const ASTContext & Ctx,StringRef Name)663     ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
664         : TimeScope(Name, [E, &Ctx] {
665             return E->getSourceRange().printToString(Ctx.getSourceManager());
666           }) {}
667 
668   private:
669     llvm::TimeTraceScope TimeScope;
670   };
671 }
672 
673 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
674                               const LValue &This, QualType ThisType);
675 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
676                               APValue::LValueBase LVBase, APValue &Value,
677                               QualType T);
678 
679 namespace {
680   /// A cleanup, and a flag indicating whether it is lifetime-extended.
681   class Cleanup {
682     llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
683     APValue::LValueBase Base;
684     QualType T;
685 
686   public:
Cleanup(APValue * Val,APValue::LValueBase Base,QualType T,ScopeKind Scope)687     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
688             ScopeKind Scope)
689         : Value(Val, Scope), Base(Base), T(T) {}
690 
691     /// Determine whether this cleanup should be performed at the end of the
692     /// given kind of scope.
isDestroyedAtEndOf(ScopeKind K) const693     bool isDestroyedAtEndOf(ScopeKind K) const {
694       return (int)Value.getInt() >= (int)K;
695     }
endLifetime(EvalInfo & Info,bool RunDestructors)696     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
697       if (RunDestructors) {
698         SourceLocation Loc;
699         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
700           Loc = VD->getLocation();
701         else if (const Expr *E = Base.dyn_cast<const Expr*>())
702           Loc = E->getExprLoc();
703         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
704       }
705       *Value.getPointer() = APValue();
706       return true;
707     }
708 
hasSideEffect()709     bool hasSideEffect() {
710       return T.isDestructedType();
711     }
712   };
713 
714   /// A reference to an object whose construction we are currently evaluating.
715   struct ObjectUnderConstruction {
716     APValue::LValueBase Base;
717     ArrayRef<APValue::LValuePathEntry> Path;
operator ==(const ObjectUnderConstruction & LHS,const ObjectUnderConstruction & RHS)718     friend bool operator==(const ObjectUnderConstruction &LHS,
719                            const ObjectUnderConstruction &RHS) {
720       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
721     }
hash_value(const ObjectUnderConstruction & Obj)722     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
723       return llvm::hash_combine(Obj.Base, Obj.Path);
724     }
725   };
726   enum class ConstructionPhase {
727     None,
728     Bases,
729     AfterBases,
730     AfterFields,
731     Destroying,
732     DestroyingBases
733   };
734 }
735 
736 namespace llvm {
737 template<> struct DenseMapInfo<ObjectUnderConstruction> {
738   using Base = DenseMapInfo<APValue::LValueBase>;
getEmptyKeyllvm::DenseMapInfo739   static ObjectUnderConstruction getEmptyKey() {
740     return {Base::getEmptyKey(), {}}; }
getTombstoneKeyllvm::DenseMapInfo741   static ObjectUnderConstruction getTombstoneKey() {
742     return {Base::getTombstoneKey(), {}};
743   }
getHashValuellvm::DenseMapInfo744   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
745     return hash_value(Object);
746   }
isEqualllvm::DenseMapInfo747   static bool isEqual(const ObjectUnderConstruction &LHS,
748                       const ObjectUnderConstruction &RHS) {
749     return LHS == RHS;
750   }
751 };
752 }
753 
754 namespace {
755   /// A dynamically-allocated heap object.
756   struct DynAlloc {
757     /// The value of this heap-allocated object.
758     APValue Value;
759     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
760     /// or a CallExpr (the latter is for direct calls to operator new inside
761     /// std::allocator<T>::allocate).
762     const Expr *AllocExpr = nullptr;
763 
764     enum Kind {
765       New,
766       ArrayNew,
767       StdAllocator
768     };
769 
770     /// Get the kind of the allocation. This must match between allocation
771     /// and deallocation.
getKind__anond52d8a670411::DynAlloc772     Kind getKind() const {
773       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
774         return NE->isArray() ? ArrayNew : New;
775       assert(isa<CallExpr>(AllocExpr));
776       return StdAllocator;
777     }
778   };
779 
780   struct DynAllocOrder {
operator ()__anond52d8a670411::DynAllocOrder781     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
782       return L.getIndex() < R.getIndex();
783     }
784   };
785 
786   /// EvalInfo - This is a private struct used by the evaluator to capture
787   /// information about a subexpression as it is folded.  It retains information
788   /// about the AST context, but also maintains information about the folded
789   /// expression.
790   ///
791   /// If an expression could be evaluated, it is still possible it is not a C
792   /// "integer constant expression" or constant expression.  If not, this struct
793   /// captures information about how and why not.
794   ///
795   /// One bit of information passed *into* the request for constant folding
796   /// indicates whether the subexpression is "evaluated" or not according to C
797   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
798   /// evaluate the expression regardless of what the RHS is, but C only allows
799   /// certain things in certain situations.
800   class EvalInfo : public interp::State {
801   public:
802     ASTContext &Ctx;
803 
804     /// EvalStatus - Contains information about the evaluation.
805     Expr::EvalStatus &EvalStatus;
806 
807     /// CurrentCall - The top of the constexpr call stack.
808     CallStackFrame *CurrentCall;
809 
810     /// CallStackDepth - The number of calls in the call stack right now.
811     unsigned CallStackDepth;
812 
813     /// NextCallIndex - The next call index to assign.
814     unsigned NextCallIndex;
815 
816     /// StepsLeft - The remaining number of evaluation steps we're permitted
817     /// to perform. This is essentially a limit for the number of statements
818     /// we will evaluate.
819     unsigned StepsLeft;
820 
821     /// Enable the experimental new constant interpreter. If an expression is
822     /// not supported by the interpreter, an error is triggered.
823     bool EnableNewConstInterp;
824 
825     /// BottomFrame - The frame in which evaluation started. This must be
826     /// initialized after CurrentCall and CallStackDepth.
827     CallStackFrame BottomFrame;
828 
829     /// A stack of values whose lifetimes end at the end of some surrounding
830     /// evaluation frame.
831     llvm::SmallVector<Cleanup, 16> CleanupStack;
832 
833     /// EvaluatingDecl - This is the declaration whose initializer is being
834     /// evaluated, if any.
835     APValue::LValueBase EvaluatingDecl;
836 
837     enum class EvaluatingDeclKind {
838       None,
839       /// We're evaluating the construction of EvaluatingDecl.
840       Ctor,
841       /// We're evaluating the destruction of EvaluatingDecl.
842       Dtor,
843     };
844     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
845 
846     /// EvaluatingDeclValue - This is the value being constructed for the
847     /// declaration whose initializer is being evaluated, if any.
848     APValue *EvaluatingDeclValue;
849 
850     /// Set of objects that are currently being constructed.
851     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
852         ObjectsUnderConstruction;
853 
854     /// Current heap allocations, along with the location where each was
855     /// allocated. We use std::map here because we need stable addresses
856     /// for the stored APValues.
857     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
858 
859     /// The number of heap allocations performed so far in this evaluation.
860     unsigned NumHeapAllocs = 0;
861 
862     struct EvaluatingConstructorRAII {
863       EvalInfo &EI;
864       ObjectUnderConstruction Object;
865       bool DidInsert;
EvaluatingConstructorRAII__anond52d8a670411::EvalInfo::EvaluatingConstructorRAII866       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
867                                 bool HasBases)
868           : EI(EI), Object(Object) {
869         DidInsert =
870             EI.ObjectsUnderConstruction
871                 .insert({Object, HasBases ? ConstructionPhase::Bases
872                                           : ConstructionPhase::AfterBases})
873                 .second;
874       }
finishedConstructingBases__anond52d8a670411::EvalInfo::EvaluatingConstructorRAII875       void finishedConstructingBases() {
876         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
877       }
finishedConstructingFields__anond52d8a670411::EvalInfo::EvaluatingConstructorRAII878       void finishedConstructingFields() {
879         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
880       }
~EvaluatingConstructorRAII__anond52d8a670411::EvalInfo::EvaluatingConstructorRAII881       ~EvaluatingConstructorRAII() {
882         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
883       }
884     };
885 
886     struct EvaluatingDestructorRAII {
887       EvalInfo &EI;
888       ObjectUnderConstruction Object;
889       bool DidInsert;
EvaluatingDestructorRAII__anond52d8a670411::EvalInfo::EvaluatingDestructorRAII890       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
891           : EI(EI), Object(Object) {
892         DidInsert = EI.ObjectsUnderConstruction
893                         .insert({Object, ConstructionPhase::Destroying})
894                         .second;
895       }
startedDestroyingBases__anond52d8a670411::EvalInfo::EvaluatingDestructorRAII896       void startedDestroyingBases() {
897         EI.ObjectsUnderConstruction[Object] =
898             ConstructionPhase::DestroyingBases;
899       }
~EvaluatingDestructorRAII__anond52d8a670411::EvalInfo::EvaluatingDestructorRAII900       ~EvaluatingDestructorRAII() {
901         if (DidInsert)
902           EI.ObjectsUnderConstruction.erase(Object);
903       }
904     };
905 
906     ConstructionPhase
isEvaluatingCtorDtor(APValue::LValueBase Base,ArrayRef<APValue::LValuePathEntry> Path)907     isEvaluatingCtorDtor(APValue::LValueBase Base,
908                          ArrayRef<APValue::LValuePathEntry> Path) {
909       return ObjectsUnderConstruction.lookup({Base, Path});
910     }
911 
912     /// If we're currently speculatively evaluating, the outermost call stack
913     /// depth at which we can mutate state, otherwise 0.
914     unsigned SpeculativeEvaluationDepth = 0;
915 
916     /// The current array initialization index, if we're performing array
917     /// initialization.
918     uint64_t ArrayInitIndex = -1;
919 
920     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
921     /// notes attached to it will also be stored, otherwise they will not be.
922     bool HasActiveDiagnostic;
923 
924     /// Have we emitted a diagnostic explaining why we couldn't constant
925     /// fold (not just why it's not strictly a constant expression)?
926     bool HasFoldFailureDiagnostic;
927 
928     /// Whether we're checking that an expression is a potential constant
929     /// expression. If so, do not fail on constructs that could become constant
930     /// later on (such as a use of an undefined global).
931     bool CheckingPotentialConstantExpression = false;
932 
933     /// Whether we're checking for an expression that has undefined behavior.
934     /// If so, we will produce warnings if we encounter an operation that is
935     /// always undefined.
936     ///
937     /// Note that we still need to evaluate the expression normally when this
938     /// is set; this is used when evaluating ICEs in C.
939     bool CheckingForUndefinedBehavior = false;
940 
941     enum EvaluationMode {
942       /// Evaluate as a constant expression. Stop if we find that the expression
943       /// is not a constant expression.
944       EM_ConstantExpression,
945 
946       /// Evaluate as a constant expression. Stop if we find that the expression
947       /// is not a constant expression. Some expressions can be retried in the
948       /// optimizer if we don't constant fold them here, but in an unevaluated
949       /// context we try to fold them immediately since the optimizer never
950       /// gets a chance to look at it.
951       EM_ConstantExpressionUnevaluated,
952 
953       /// Fold the expression to a constant. Stop if we hit a side-effect that
954       /// we can't model.
955       EM_ConstantFold,
956 
957       /// Evaluate in any way we know how. Don't worry about side-effects that
958       /// can't be modeled.
959       EM_IgnoreSideEffects,
960     } EvalMode;
961 
962     /// Are we checking whether the expression is a potential constant
963     /// expression?
checkingPotentialConstantExpression() const964     bool checkingPotentialConstantExpression() const override  {
965       return CheckingPotentialConstantExpression;
966     }
967 
968     /// Are we checking an expression for overflow?
969     // FIXME: We should check for any kind of undefined or suspicious behavior
970     // in such constructs, not just overflow.
checkingForUndefinedBehavior() const971     bool checkingForUndefinedBehavior() const override {
972       return CheckingForUndefinedBehavior;
973     }
974 
EvalInfo(const ASTContext & C,Expr::EvalStatus & S,EvaluationMode Mode)975     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
976         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
977           CallStackDepth(0), NextCallIndex(1),
978           StepsLeft(C.getLangOpts().ConstexprStepLimit),
979           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
980           BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
981           EvaluatingDecl((const ValueDecl *)nullptr),
982           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
983           HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
984 
~EvalInfo()985     ~EvalInfo() {
986       discardCleanups();
987     }
988 
getCtx() const989     ASTContext &getCtx() const override { return Ctx; }
990 
setEvaluatingDecl(APValue::LValueBase Base,APValue & Value,EvaluatingDeclKind EDK=EvaluatingDeclKind::Ctor)991     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
992                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
993       EvaluatingDecl = Base;
994       IsEvaluatingDecl = EDK;
995       EvaluatingDeclValue = &Value;
996     }
997 
CheckCallLimit(SourceLocation Loc)998     bool CheckCallLimit(SourceLocation Loc) {
999       // Don't perform any constexpr calls (other than the call we're checking)
1000       // when checking a potential constant expression.
1001       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1002         return false;
1003       if (NextCallIndex == 0) {
1004         // NextCallIndex has wrapped around.
1005         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1006         return false;
1007       }
1008       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1009         return true;
1010       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1011         << getLangOpts().ConstexprCallDepth;
1012       return false;
1013     }
1014 
1015     std::pair<CallStackFrame *, unsigned>
getCallFrameAndDepth(unsigned CallIndex)1016     getCallFrameAndDepth(unsigned CallIndex) {
1017       assert(CallIndex && "no call index in getCallFrameAndDepth");
1018       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1019       // be null in this loop.
1020       unsigned Depth = CallStackDepth;
1021       CallStackFrame *Frame = CurrentCall;
1022       while (Frame->Index > CallIndex) {
1023         Frame = Frame->Caller;
1024         --Depth;
1025       }
1026       if (Frame->Index == CallIndex)
1027         return {Frame, Depth};
1028       return {nullptr, 0};
1029     }
1030 
nextStep(const Stmt * S)1031     bool nextStep(const Stmt *S) {
1032       if (!StepsLeft) {
1033         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1034         return false;
1035       }
1036       --StepsLeft;
1037       return true;
1038     }
1039 
1040     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1041 
lookupDynamicAlloc(DynamicAllocLValue DA)1042     std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1043       std::optional<DynAlloc *> Result;
1044       auto It = HeapAllocs.find(DA);
1045       if (It != HeapAllocs.end())
1046         Result = &It->second;
1047       return Result;
1048     }
1049 
1050     /// Get the allocated storage for the given parameter of the given call.
getParamSlot(CallRef Call,const ParmVarDecl * PVD)1051     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1052       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1053       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1054                    : nullptr;
1055     }
1056 
1057     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1058     struct StdAllocatorCaller {
1059       unsigned FrameIndex;
1060       QualType ElemType;
operator bool__anond52d8a670411::EvalInfo::StdAllocatorCaller1061       explicit operator bool() const { return FrameIndex != 0; };
1062     };
1063 
getStdAllocatorCaller(StringRef FnName) const1064     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1065       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1066            Call = Call->Caller) {
1067         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1068         if (!MD)
1069           continue;
1070         const IdentifierInfo *FnII = MD->getIdentifier();
1071         if (!FnII || !FnII->isStr(FnName))
1072           continue;
1073 
1074         const auto *CTSD =
1075             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1076         if (!CTSD)
1077           continue;
1078 
1079         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1080         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1081         if (CTSD->isInStdNamespace() && ClassII &&
1082             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1083             TAL[0].getKind() == TemplateArgument::Type)
1084           return {Call->Index, TAL[0].getAsType()};
1085       }
1086 
1087       return {};
1088     }
1089 
performLifetimeExtension()1090     void performLifetimeExtension() {
1091       // Disable the cleanups for lifetime-extended temporaries.
1092       llvm::erase_if(CleanupStack, [](Cleanup &C) {
1093         return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1094       });
1095     }
1096 
1097     /// Throw away any remaining cleanups at the end of evaluation. If any
1098     /// cleanups would have had a side-effect, note that as an unmodeled
1099     /// side-effect and return false. Otherwise, return true.
discardCleanups()1100     bool discardCleanups() {
1101       for (Cleanup &C : CleanupStack) {
1102         if (C.hasSideEffect() && !noteSideEffect()) {
1103           CleanupStack.clear();
1104           return false;
1105         }
1106       }
1107       CleanupStack.clear();
1108       return true;
1109     }
1110 
1111   private:
getCurrentFrame()1112     interp::Frame *getCurrentFrame() override { return CurrentCall; }
getBottomFrame() const1113     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1114 
hasActiveDiagnostic()1115     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
setActiveDiagnostic(bool Flag)1116     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1117 
setFoldFailureDiagnostic(bool Flag)1118     void setFoldFailureDiagnostic(bool Flag) override {
1119       HasFoldFailureDiagnostic = Flag;
1120     }
1121 
getEvalStatus() const1122     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1123 
1124     // If we have a prior diagnostic, it will be noting that the expression
1125     // isn't a constant expression. This diagnostic is more important,
1126     // unless we require this evaluation to produce a constant expression.
1127     //
1128     // FIXME: We might want to show both diagnostics to the user in
1129     // EM_ConstantFold mode.
hasPriorDiagnostic()1130     bool hasPriorDiagnostic() override {
1131       if (!EvalStatus.Diag->empty()) {
1132         switch (EvalMode) {
1133         case EM_ConstantFold:
1134         case EM_IgnoreSideEffects:
1135           if (!HasFoldFailureDiagnostic)
1136             break;
1137           // We've already failed to fold something. Keep that diagnostic.
1138           [[fallthrough]];
1139         case EM_ConstantExpression:
1140         case EM_ConstantExpressionUnevaluated:
1141           setActiveDiagnostic(false);
1142           return true;
1143         }
1144       }
1145       return false;
1146     }
1147 
getCallStackDepth()1148     unsigned getCallStackDepth() override { return CallStackDepth; }
1149 
1150   public:
1151     /// Should we continue evaluation after encountering a side-effect that we
1152     /// couldn't model?
keepEvaluatingAfterSideEffect()1153     bool keepEvaluatingAfterSideEffect() {
1154       switch (EvalMode) {
1155       case EM_IgnoreSideEffects:
1156         return true;
1157 
1158       case EM_ConstantExpression:
1159       case EM_ConstantExpressionUnevaluated:
1160       case EM_ConstantFold:
1161         // By default, assume any side effect might be valid in some other
1162         // evaluation of this expression from a different context.
1163         return checkingPotentialConstantExpression() ||
1164                checkingForUndefinedBehavior();
1165       }
1166       llvm_unreachable("Missed EvalMode case");
1167     }
1168 
1169     /// Note that we have had a side-effect, and determine whether we should
1170     /// keep evaluating.
noteSideEffect()1171     bool noteSideEffect() {
1172       EvalStatus.HasSideEffects = true;
1173       return keepEvaluatingAfterSideEffect();
1174     }
1175 
1176     /// Should we continue evaluation after encountering undefined behavior?
keepEvaluatingAfterUndefinedBehavior()1177     bool keepEvaluatingAfterUndefinedBehavior() {
1178       switch (EvalMode) {
1179       case EM_IgnoreSideEffects:
1180       case EM_ConstantFold:
1181         return true;
1182 
1183       case EM_ConstantExpression:
1184       case EM_ConstantExpressionUnevaluated:
1185         return checkingForUndefinedBehavior();
1186       }
1187       llvm_unreachable("Missed EvalMode case");
1188     }
1189 
1190     /// Note that we hit something that was technically undefined behavior, but
1191     /// that we can evaluate past it (such as signed overflow or floating-point
1192     /// division by zero.)
noteUndefinedBehavior()1193     bool noteUndefinedBehavior() override {
1194       EvalStatus.HasUndefinedBehavior = true;
1195       return keepEvaluatingAfterUndefinedBehavior();
1196     }
1197 
1198     /// Should we continue evaluation as much as possible after encountering a
1199     /// construct which can't be reduced to a value?
keepEvaluatingAfterFailure() const1200     bool keepEvaluatingAfterFailure() const override {
1201       if (!StepsLeft)
1202         return false;
1203 
1204       switch (EvalMode) {
1205       case EM_ConstantExpression:
1206       case EM_ConstantExpressionUnevaluated:
1207       case EM_ConstantFold:
1208       case EM_IgnoreSideEffects:
1209         return checkingPotentialConstantExpression() ||
1210                checkingForUndefinedBehavior();
1211       }
1212       llvm_unreachable("Missed EvalMode case");
1213     }
1214 
1215     /// Notes that we failed to evaluate an expression that other expressions
1216     /// directly depend on, and determine if we should keep evaluating. This
1217     /// should only be called if we actually intend to keep evaluating.
1218     ///
1219     /// Call noteSideEffect() instead if we may be able to ignore the value that
1220     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1221     ///
1222     /// (Foo(), 1)      // use noteSideEffect
1223     /// (Foo() || true) // use noteSideEffect
1224     /// Foo() + 1       // use noteFailure
noteFailure()1225     [[nodiscard]] bool noteFailure() {
1226       // Failure when evaluating some expression often means there is some
1227       // subexpression whose evaluation was skipped. Therefore, (because we
1228       // don't track whether we skipped an expression when unwinding after an
1229       // evaluation failure) every evaluation failure that bubbles up from a
1230       // subexpression implies that a side-effect has potentially happened. We
1231       // skip setting the HasSideEffects flag to true until we decide to
1232       // continue evaluating after that point, which happens here.
1233       bool KeepGoing = keepEvaluatingAfterFailure();
1234       EvalStatus.HasSideEffects |= KeepGoing;
1235       return KeepGoing;
1236     }
1237 
1238     class ArrayInitLoopIndex {
1239       EvalInfo &Info;
1240       uint64_t OuterIndex;
1241 
1242     public:
ArrayInitLoopIndex(EvalInfo & Info)1243       ArrayInitLoopIndex(EvalInfo &Info)
1244           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1245         Info.ArrayInitIndex = 0;
1246       }
~ArrayInitLoopIndex()1247       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1248 
operator uint64_t&()1249       operator uint64_t&() { return Info.ArrayInitIndex; }
1250     };
1251   };
1252 
1253   /// Object used to treat all foldable expressions as constant expressions.
1254   struct FoldConstant {
1255     EvalInfo &Info;
1256     bool Enabled;
1257     bool HadNoPriorDiags;
1258     EvalInfo::EvaluationMode OldMode;
1259 
FoldConstant__anond52d8a670411::FoldConstant1260     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1261       : Info(Info),
1262         Enabled(Enabled),
1263         HadNoPriorDiags(Info.EvalStatus.Diag &&
1264                         Info.EvalStatus.Diag->empty() &&
1265                         !Info.EvalStatus.HasSideEffects),
1266         OldMode(Info.EvalMode) {
1267       if (Enabled)
1268         Info.EvalMode = EvalInfo::EM_ConstantFold;
1269     }
keepDiagnostics__anond52d8a670411::FoldConstant1270     void keepDiagnostics() { Enabled = false; }
~FoldConstant__anond52d8a670411::FoldConstant1271     ~FoldConstant() {
1272       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1273           !Info.EvalStatus.HasSideEffects)
1274         Info.EvalStatus.Diag->clear();
1275       Info.EvalMode = OldMode;
1276     }
1277   };
1278 
1279   /// RAII object used to set the current evaluation mode to ignore
1280   /// side-effects.
1281   struct IgnoreSideEffectsRAII {
1282     EvalInfo &Info;
1283     EvalInfo::EvaluationMode OldMode;
IgnoreSideEffectsRAII__anond52d8a670411::IgnoreSideEffectsRAII1284     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1285         : Info(Info), OldMode(Info.EvalMode) {
1286       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1287     }
1288 
~IgnoreSideEffectsRAII__anond52d8a670411::IgnoreSideEffectsRAII1289     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1290   };
1291 
1292   /// RAII object used to optionally suppress diagnostics and side-effects from
1293   /// a speculative evaluation.
1294   class SpeculativeEvaluationRAII {
1295     EvalInfo *Info = nullptr;
1296     Expr::EvalStatus OldStatus;
1297     unsigned OldSpeculativeEvaluationDepth;
1298 
moveFromAndCancel(SpeculativeEvaluationRAII && Other)1299     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1300       Info = Other.Info;
1301       OldStatus = Other.OldStatus;
1302       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1303       Other.Info = nullptr;
1304     }
1305 
maybeRestoreState()1306     void maybeRestoreState() {
1307       if (!Info)
1308         return;
1309 
1310       Info->EvalStatus = OldStatus;
1311       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1312     }
1313 
1314   public:
1315     SpeculativeEvaluationRAII() = default;
1316 
SpeculativeEvaluationRAII(EvalInfo & Info,SmallVectorImpl<PartialDiagnosticAt> * NewDiag=nullptr)1317     SpeculativeEvaluationRAII(
1318         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1319         : Info(&Info), OldStatus(Info.EvalStatus),
1320           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1321       Info.EvalStatus.Diag = NewDiag;
1322       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1323     }
1324 
1325     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
SpeculativeEvaluationRAII(SpeculativeEvaluationRAII && Other)1326     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1327       moveFromAndCancel(std::move(Other));
1328     }
1329 
operator =(SpeculativeEvaluationRAII && Other)1330     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1331       maybeRestoreState();
1332       moveFromAndCancel(std::move(Other));
1333       return *this;
1334     }
1335 
~SpeculativeEvaluationRAII()1336     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1337   };
1338 
1339   /// RAII object wrapping a full-expression or block scope, and handling
1340   /// the ending of the lifetime of temporaries created within it.
1341   template<ScopeKind Kind>
1342   class ScopeRAII {
1343     EvalInfo &Info;
1344     unsigned OldStackSize;
1345   public:
ScopeRAII(EvalInfo & Info)1346     ScopeRAII(EvalInfo &Info)
1347         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1348       // Push a new temporary version. This is needed to distinguish between
1349       // temporaries created in different iterations of a loop.
1350       Info.CurrentCall->pushTempVersion();
1351     }
destroy(bool RunDestructors=true)1352     bool destroy(bool RunDestructors = true) {
1353       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1354       OldStackSize = -1U;
1355       return OK;
1356     }
~ScopeRAII()1357     ~ScopeRAII() {
1358       if (OldStackSize != -1U)
1359         destroy(false);
1360       // Body moved to a static method to encourage the compiler to inline away
1361       // instances of this class.
1362       Info.CurrentCall->popTempVersion();
1363     }
1364   private:
cleanup(EvalInfo & Info,bool RunDestructors,unsigned OldStackSize)1365     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1366                         unsigned OldStackSize) {
1367       assert(OldStackSize <= Info.CleanupStack.size() &&
1368              "running cleanups out of order?");
1369 
1370       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1371       // for a full-expression scope.
1372       bool Success = true;
1373       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1374         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1375           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1376             Success = false;
1377             break;
1378           }
1379         }
1380       }
1381 
1382       // Compact any retained cleanups.
1383       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1384       if (Kind != ScopeKind::Block)
1385         NewEnd =
1386             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1387               return C.isDestroyedAtEndOf(Kind);
1388             });
1389       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1390       return Success;
1391     }
1392   };
1393   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1394   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1395   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1396 }
1397 
checkSubobject(EvalInfo & Info,const Expr * E,CheckSubobjectKind CSK)1398 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1399                                          CheckSubobjectKind CSK) {
1400   if (Invalid)
1401     return false;
1402   if (isOnePastTheEnd()) {
1403     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1404       << CSK;
1405     setInvalid();
1406     return false;
1407   }
1408   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1409   // must actually be at least one array element; even a VLA cannot have a
1410   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1411   return true;
1412 }
1413 
diagnoseUnsizedArrayPointerArithmetic(EvalInfo & Info,const Expr * E)1414 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1415                                                                 const Expr *E) {
1416   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1417   // Do not set the designator as invalid: we can represent this situation,
1418   // and correct handling of __builtin_object_size requires us to do so.
1419 }
1420 
diagnosePointerArithmetic(EvalInfo & Info,const Expr * E,const APSInt & N)1421 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1422                                                     const Expr *E,
1423                                                     const APSInt &N) {
1424   // If we're complaining, we must be able to statically determine the size of
1425   // the most derived array.
1426   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1427     Info.CCEDiag(E, diag::note_constexpr_array_index)
1428       << N << /*array*/ 0
1429       << static_cast<unsigned>(getMostDerivedArraySize());
1430   else
1431     Info.CCEDiag(E, diag::note_constexpr_array_index)
1432       << N << /*non-array*/ 1;
1433   setInvalid();
1434 }
1435 
CallStackFrame(EvalInfo & Info,SourceLocation CallLoc,const FunctionDecl * Callee,const LValue * This,CallRef Call)1436 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1437                                const FunctionDecl *Callee, const LValue *This,
1438                                CallRef Call)
1439     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1440       Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1441   Info.CurrentCall = this;
1442   ++Info.CallStackDepth;
1443 }
1444 
~CallStackFrame()1445 CallStackFrame::~CallStackFrame() {
1446   assert(Info.CurrentCall == this && "calls retired out of order");
1447   --Info.CallStackDepth;
1448   Info.CurrentCall = Caller;
1449 }
1450 
isRead(AccessKinds AK)1451 static bool isRead(AccessKinds AK) {
1452   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1453 }
1454 
isModification(AccessKinds AK)1455 static bool isModification(AccessKinds AK) {
1456   switch (AK) {
1457   case AK_Read:
1458   case AK_ReadObjectRepresentation:
1459   case AK_MemberCall:
1460   case AK_DynamicCast:
1461   case AK_TypeId:
1462     return false;
1463   case AK_Assign:
1464   case AK_Increment:
1465   case AK_Decrement:
1466   case AK_Construct:
1467   case AK_Destroy:
1468     return true;
1469   }
1470   llvm_unreachable("unknown access kind");
1471 }
1472 
isAnyAccess(AccessKinds AK)1473 static bool isAnyAccess(AccessKinds AK) {
1474   return isRead(AK) || isModification(AK);
1475 }
1476 
1477 /// Is this an access per the C++ definition?
isFormalAccess(AccessKinds AK)1478 static bool isFormalAccess(AccessKinds AK) {
1479   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1480 }
1481 
1482 /// Is this kind of axcess valid on an indeterminate object value?
isValidIndeterminateAccess(AccessKinds AK)1483 static bool isValidIndeterminateAccess(AccessKinds AK) {
1484   switch (AK) {
1485   case AK_Read:
1486   case AK_Increment:
1487   case AK_Decrement:
1488     // These need the object's value.
1489     return false;
1490 
1491   case AK_ReadObjectRepresentation:
1492   case AK_Assign:
1493   case AK_Construct:
1494   case AK_Destroy:
1495     // Construction and destruction don't need the value.
1496     return true;
1497 
1498   case AK_MemberCall:
1499   case AK_DynamicCast:
1500   case AK_TypeId:
1501     // These aren't really meaningful on scalars.
1502     return true;
1503   }
1504   llvm_unreachable("unknown access kind");
1505 }
1506 
1507 namespace {
1508   struct ComplexValue {
1509   private:
1510     bool IsInt;
1511 
1512   public:
1513     APSInt IntReal, IntImag;
1514     APFloat FloatReal, FloatImag;
1515 
ComplexValue__anond52d8a670711::ComplexValue1516     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1517 
makeComplexFloat__anond52d8a670711::ComplexValue1518     void makeComplexFloat() { IsInt = false; }
isComplexFloat__anond52d8a670711::ComplexValue1519     bool isComplexFloat() const { return !IsInt; }
getComplexFloatReal__anond52d8a670711::ComplexValue1520     APFloat &getComplexFloatReal() { return FloatReal; }
getComplexFloatImag__anond52d8a670711::ComplexValue1521     APFloat &getComplexFloatImag() { return FloatImag; }
1522 
makeComplexInt__anond52d8a670711::ComplexValue1523     void makeComplexInt() { IsInt = true; }
isComplexInt__anond52d8a670711::ComplexValue1524     bool isComplexInt() const { return IsInt; }
getComplexIntReal__anond52d8a670711::ComplexValue1525     APSInt &getComplexIntReal() { return IntReal; }
getComplexIntImag__anond52d8a670711::ComplexValue1526     APSInt &getComplexIntImag() { return IntImag; }
1527 
moveInto__anond52d8a670711::ComplexValue1528     void moveInto(APValue &v) const {
1529       if (isComplexFloat())
1530         v = APValue(FloatReal, FloatImag);
1531       else
1532         v = APValue(IntReal, IntImag);
1533     }
setFrom__anond52d8a670711::ComplexValue1534     void setFrom(const APValue &v) {
1535       assert(v.isComplexFloat() || v.isComplexInt());
1536       if (v.isComplexFloat()) {
1537         makeComplexFloat();
1538         FloatReal = v.getComplexFloatReal();
1539         FloatImag = v.getComplexFloatImag();
1540       } else {
1541         makeComplexInt();
1542         IntReal = v.getComplexIntReal();
1543         IntImag = v.getComplexIntImag();
1544       }
1545     }
1546   };
1547 
1548   struct LValue {
1549     APValue::LValueBase Base;
1550     CharUnits Offset;
1551     SubobjectDesignator Designator;
1552     bool IsNullPtr : 1;
1553     bool InvalidBase : 1;
1554 
getLValueBase__anond52d8a670711::LValue1555     const APValue::LValueBase getLValueBase() const { return Base; }
getLValueOffset__anond52d8a670711::LValue1556     CharUnits &getLValueOffset() { return Offset; }
getLValueOffset__anond52d8a670711::LValue1557     const CharUnits &getLValueOffset() const { return Offset; }
getLValueDesignator__anond52d8a670711::LValue1558     SubobjectDesignator &getLValueDesignator() { return Designator; }
getLValueDesignator__anond52d8a670711::LValue1559     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
isNullPointer__anond52d8a670711::LValue1560     bool isNullPointer() const { return IsNullPtr;}
1561 
getLValueCallIndex__anond52d8a670711::LValue1562     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
getLValueVersion__anond52d8a670711::LValue1563     unsigned getLValueVersion() const { return Base.getVersion(); }
1564 
moveInto__anond52d8a670711::LValue1565     void moveInto(APValue &V) const {
1566       if (Designator.Invalid)
1567         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1568       else {
1569         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1570         V = APValue(Base, Offset, Designator.Entries,
1571                     Designator.IsOnePastTheEnd, IsNullPtr);
1572       }
1573     }
setFrom__anond52d8a670711::LValue1574     void setFrom(ASTContext &Ctx, const APValue &V) {
1575       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1576       Base = V.getLValueBase();
1577       Offset = V.getLValueOffset();
1578       InvalidBase = false;
1579       Designator = SubobjectDesignator(Ctx, V);
1580       IsNullPtr = V.isNullPointer();
1581     }
1582 
set__anond52d8a670711::LValue1583     void set(APValue::LValueBase B, bool BInvalid = false) {
1584 #ifndef NDEBUG
1585       // We only allow a few types of invalid bases. Enforce that here.
1586       if (BInvalid) {
1587         const auto *E = B.get<const Expr *>();
1588         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1589                "Unexpected type of invalid base");
1590       }
1591 #endif
1592 
1593       Base = B;
1594       Offset = CharUnits::fromQuantity(0);
1595       InvalidBase = BInvalid;
1596       Designator = SubobjectDesignator(getType(B));
1597       IsNullPtr = false;
1598     }
1599 
setNull__anond52d8a670711::LValue1600     void setNull(ASTContext &Ctx, QualType PointerTy) {
1601       Base = (const ValueDecl *)nullptr;
1602       Offset =
1603           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1604       InvalidBase = false;
1605       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1606       IsNullPtr = true;
1607     }
1608 
setInvalid__anond52d8a670711::LValue1609     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1610       set(B, true);
1611     }
1612 
toString__anond52d8a670711::LValue1613     std::string toString(ASTContext &Ctx, QualType T) const {
1614       APValue Printable;
1615       moveInto(Printable);
1616       return Printable.getAsString(Ctx, T);
1617     }
1618 
1619   private:
1620     // Check that this LValue is not based on a null pointer. If it is, produce
1621     // a diagnostic and mark the designator as invalid.
1622     template <typename GenDiagType>
checkNullPointerDiagnosingWith__anond52d8a670711::LValue1623     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1624       if (Designator.Invalid)
1625         return false;
1626       if (IsNullPtr) {
1627         GenDiag();
1628         Designator.setInvalid();
1629         return false;
1630       }
1631       return true;
1632     }
1633 
1634   public:
checkNullPointer__anond52d8a670711::LValue1635     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1636                           CheckSubobjectKind CSK) {
1637       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1638         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1639       });
1640     }
1641 
checkNullPointerForFoldAccess__anond52d8a670711::LValue1642     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1643                                        AccessKinds AK) {
1644       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1645         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1646       });
1647     }
1648 
1649     // Check this LValue refers to an object. If not, set the designator to be
1650     // invalid and emit a diagnostic.
checkSubobject__anond52d8a670711::LValue1651     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1652       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1653              Designator.checkSubobject(Info, E, CSK);
1654     }
1655 
addDecl__anond52d8a670711::LValue1656     void addDecl(EvalInfo &Info, const Expr *E,
1657                  const Decl *D, bool Virtual = false) {
1658       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1659         Designator.addDeclUnchecked(D, Virtual);
1660     }
addUnsizedArray__anond52d8a670711::LValue1661     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1662       if (!Designator.Entries.empty()) {
1663         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1664         Designator.setInvalid();
1665         return;
1666       }
1667       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1668         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1669         Designator.FirstEntryIsAnUnsizedArray = true;
1670         Designator.addUnsizedArrayUnchecked(ElemTy);
1671       }
1672     }
addArray__anond52d8a670711::LValue1673     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1674       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1675         Designator.addArrayUnchecked(CAT);
1676     }
addComplex__anond52d8a670711::LValue1677     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1678       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1679         Designator.addComplexUnchecked(EltTy, Imag);
1680     }
clearIsNullPointer__anond52d8a670711::LValue1681     void clearIsNullPointer() {
1682       IsNullPtr = false;
1683     }
adjustOffsetAndIndex__anond52d8a670711::LValue1684     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1685                               const APSInt &Index, CharUnits ElementSize) {
1686       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1687       // but we're not required to diagnose it and it's valid in C++.)
1688       if (!Index)
1689         return;
1690 
1691       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1692       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1693       // offsets.
1694       uint64_t Offset64 = Offset.getQuantity();
1695       uint64_t ElemSize64 = ElementSize.getQuantity();
1696       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1697       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1698 
1699       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1700         Designator.adjustIndex(Info, E, Index);
1701       clearIsNullPointer();
1702     }
adjustOffset__anond52d8a670711::LValue1703     void adjustOffset(CharUnits N) {
1704       Offset += N;
1705       if (N.getQuantity())
1706         clearIsNullPointer();
1707     }
1708   };
1709 
1710   struct MemberPtr {
MemberPtr__anond52d8a670711::MemberPtr1711     MemberPtr() {}
MemberPtr__anond52d8a670711::MemberPtr1712     explicit MemberPtr(const ValueDecl *Decl)
1713         : DeclAndIsDerivedMember(Decl, false) {}
1714 
1715     /// The member or (direct or indirect) field referred to by this member
1716     /// pointer, or 0 if this is a null member pointer.
getDecl__anond52d8a670711::MemberPtr1717     const ValueDecl *getDecl() const {
1718       return DeclAndIsDerivedMember.getPointer();
1719     }
1720     /// Is this actually a member of some type derived from the relevant class?
isDerivedMember__anond52d8a670711::MemberPtr1721     bool isDerivedMember() const {
1722       return DeclAndIsDerivedMember.getInt();
1723     }
1724     /// Get the class which the declaration actually lives in.
getContainingRecord__anond52d8a670711::MemberPtr1725     const CXXRecordDecl *getContainingRecord() const {
1726       return cast<CXXRecordDecl>(
1727           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1728     }
1729 
moveInto__anond52d8a670711::MemberPtr1730     void moveInto(APValue &V) const {
1731       V = APValue(getDecl(), isDerivedMember(), Path);
1732     }
setFrom__anond52d8a670711::MemberPtr1733     void setFrom(const APValue &V) {
1734       assert(V.isMemberPointer());
1735       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1736       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1737       Path.clear();
1738       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1739       Path.insert(Path.end(), P.begin(), P.end());
1740     }
1741 
1742     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1743     /// whether the member is a member of some class derived from the class type
1744     /// of the member pointer.
1745     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1746     /// Path - The path of base/derived classes from the member declaration's
1747     /// class (exclusive) to the class type of the member pointer (inclusive).
1748     SmallVector<const CXXRecordDecl*, 4> Path;
1749 
1750     /// Perform a cast towards the class of the Decl (either up or down the
1751     /// hierarchy).
castBack__anond52d8a670711::MemberPtr1752     bool castBack(const CXXRecordDecl *Class) {
1753       assert(!Path.empty());
1754       const CXXRecordDecl *Expected;
1755       if (Path.size() >= 2)
1756         Expected = Path[Path.size() - 2];
1757       else
1758         Expected = getContainingRecord();
1759       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1760         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1761         // if B does not contain the original member and is not a base or
1762         // derived class of the class containing the original member, the result
1763         // of the cast is undefined.
1764         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1765         // (D::*). We consider that to be a language defect.
1766         return false;
1767       }
1768       Path.pop_back();
1769       return true;
1770     }
1771     /// Perform a base-to-derived member pointer cast.
castToDerived__anond52d8a670711::MemberPtr1772     bool castToDerived(const CXXRecordDecl *Derived) {
1773       if (!getDecl())
1774         return true;
1775       if (!isDerivedMember()) {
1776         Path.push_back(Derived);
1777         return true;
1778       }
1779       if (!castBack(Derived))
1780         return false;
1781       if (Path.empty())
1782         DeclAndIsDerivedMember.setInt(false);
1783       return true;
1784     }
1785     /// Perform a derived-to-base member pointer cast.
castToBase__anond52d8a670711::MemberPtr1786     bool castToBase(const CXXRecordDecl *Base) {
1787       if (!getDecl())
1788         return true;
1789       if (Path.empty())
1790         DeclAndIsDerivedMember.setInt(true);
1791       if (isDerivedMember()) {
1792         Path.push_back(Base);
1793         return true;
1794       }
1795       return castBack(Base);
1796     }
1797   };
1798 
1799   /// Compare two member pointers, which are assumed to be of the same type.
operator ==(const MemberPtr & LHS,const MemberPtr & RHS)1800   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1801     if (!LHS.getDecl() || !RHS.getDecl())
1802       return !LHS.getDecl() && !RHS.getDecl();
1803     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1804       return false;
1805     return LHS.Path == RHS.Path;
1806   }
1807 }
1808 
1809 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1810 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1811                             const LValue &This, const Expr *E,
1812                             bool AllowNonLiteralTypes = false);
1813 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1814                            bool InvalidBaseOK = false);
1815 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1816                             bool InvalidBaseOK = false);
1817 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1818                                   EvalInfo &Info);
1819 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1820 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1821 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1822                                     EvalInfo &Info);
1823 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1824 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1825 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1826                            EvalInfo &Info);
1827 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1828 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1829                                   EvalInfo &Info);
1830 
1831 /// Evaluate an integer or fixed point expression into an APResult.
1832 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1833                                         EvalInfo &Info);
1834 
1835 /// Evaluate only a fixed point expression into an APResult.
1836 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1837                                EvalInfo &Info);
1838 
1839 //===----------------------------------------------------------------------===//
1840 // Misc utilities
1841 //===----------------------------------------------------------------------===//
1842 
1843 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1844 /// preserving its value (by extending by up to one bit as needed).
negateAsSigned(APSInt & Int)1845 static void negateAsSigned(APSInt &Int) {
1846   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1847     Int = Int.extend(Int.getBitWidth() + 1);
1848     Int.setIsSigned(true);
1849   }
1850   Int = -Int;
1851 }
1852 
1853 template<typename KeyT>
createTemporary(const KeyT * Key,QualType T,ScopeKind Scope,LValue & LV)1854 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1855                                          ScopeKind Scope, LValue &LV) {
1856   unsigned Version = getTempVersion();
1857   APValue::LValueBase Base(Key, Index, Version);
1858   LV.set(Base);
1859   return createLocal(Base, Key, T, Scope);
1860 }
1861 
1862 /// Allocate storage for a parameter of a function call made in this frame.
createParam(CallRef Args,const ParmVarDecl * PVD,LValue & LV)1863 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1864                                      LValue &LV) {
1865   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1866   APValue::LValueBase Base(PVD, Index, Args.Version);
1867   LV.set(Base);
1868   // We always destroy parameters at the end of the call, even if we'd allow
1869   // them to live to the end of the full-expression at runtime, in order to
1870   // give portable results and match other compilers.
1871   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1872 }
1873 
createLocal(APValue::LValueBase Base,const void * Key,QualType T,ScopeKind Scope)1874 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1875                                      QualType T, ScopeKind Scope) {
1876   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1877   unsigned Version = Base.getVersion();
1878   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1879   assert(Result.isAbsent() && "local created multiple times");
1880 
1881   // If we're creating a local immediately in the operand of a speculative
1882   // evaluation, don't register a cleanup to be run outside the speculative
1883   // evaluation context, since we won't actually be able to initialize this
1884   // object.
1885   if (Index <= Info.SpeculativeEvaluationDepth) {
1886     if (T.isDestructedType())
1887       Info.noteSideEffect();
1888   } else {
1889     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1890   }
1891   return Result;
1892 }
1893 
createHeapAlloc(const Expr * E,QualType T,LValue & LV)1894 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1895   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1896     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1897     return nullptr;
1898   }
1899 
1900   DynamicAllocLValue DA(NumHeapAllocs++);
1901   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1902   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1903                                    std::forward_as_tuple(DA), std::tuple<>());
1904   assert(Result.second && "reused a heap alloc index?");
1905   Result.first->second.AllocExpr = E;
1906   return &Result.first->second.Value;
1907 }
1908 
1909 /// Produce a string describing the given constexpr call.
describe(raw_ostream & Out)1910 void CallStackFrame::describe(raw_ostream &Out) {
1911   unsigned ArgIndex = 0;
1912   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1913                       !isa<CXXConstructorDecl>(Callee) &&
1914                       cast<CXXMethodDecl>(Callee)->isInstance();
1915 
1916   if (!IsMemberCall)
1917     Out << *Callee << '(';
1918 
1919   if (This && IsMemberCall) {
1920     APValue Val;
1921     This->moveInto(Val);
1922     Val.printPretty(Out, Info.Ctx,
1923                     This->Designator.MostDerivedType);
1924     // FIXME: Add parens around Val if needed.
1925     Out << "->" << *Callee << '(';
1926     IsMemberCall = false;
1927   }
1928 
1929   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1930        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1931     if (ArgIndex > (unsigned)IsMemberCall)
1932       Out << ", ";
1933 
1934     const ParmVarDecl *Param = *I;
1935     APValue *V = Info.getParamSlot(Arguments, Param);
1936     if (V)
1937       V->printPretty(Out, Info.Ctx, Param->getType());
1938     else
1939       Out << "<...>";
1940 
1941     if (ArgIndex == 0 && IsMemberCall)
1942       Out << "->" << *Callee << '(';
1943   }
1944 
1945   Out << ')';
1946 }
1947 
1948 /// Evaluate an expression to see if it had side-effects, and discard its
1949 /// result.
1950 /// \return \c true if the caller should keep evaluating.
EvaluateIgnoredValue(EvalInfo & Info,const Expr * E)1951 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1952   assert(!E->isValueDependent());
1953   APValue Scratch;
1954   if (!Evaluate(Scratch, Info, E))
1955     // We don't need the value, but we might have skipped a side effect here.
1956     return Info.noteSideEffect();
1957   return true;
1958 }
1959 
1960 /// Should this call expression be treated as a no-op?
IsNoOpCall(const CallExpr * E)1961 static bool IsNoOpCall(const CallExpr *E) {
1962   unsigned Builtin = E->getBuiltinCallee();
1963   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1964           Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1965           Builtin == Builtin::BI__builtin_function_start);
1966 }
1967 
IsGlobalLValue(APValue::LValueBase B)1968 static bool IsGlobalLValue(APValue::LValueBase B) {
1969   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1970   // constant expression of pointer type that evaluates to...
1971 
1972   // ... a null pointer value, or a prvalue core constant expression of type
1973   // std::nullptr_t.
1974   if (!B) return true;
1975 
1976   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1977     // ... the address of an object with static storage duration,
1978     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1979       return VD->hasGlobalStorage();
1980     if (isa<TemplateParamObjectDecl>(D))
1981       return true;
1982     // ... the address of a function,
1983     // ... the address of a GUID [MS extension],
1984     // ... the address of an unnamed global constant
1985     return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
1986   }
1987 
1988   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1989     return true;
1990 
1991   const Expr *E = B.get<const Expr*>();
1992   switch (E->getStmtClass()) {
1993   default:
1994     return false;
1995   case Expr::CompoundLiteralExprClass: {
1996     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1997     return CLE->isFileScope() && CLE->isLValue();
1998   }
1999   case Expr::MaterializeTemporaryExprClass:
2000     // A materialized temporary might have been lifetime-extended to static
2001     // storage duration.
2002     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2003   // A string literal has static storage duration.
2004   case Expr::StringLiteralClass:
2005   case Expr::PredefinedExprClass:
2006   case Expr::ObjCStringLiteralClass:
2007   case Expr::ObjCEncodeExprClass:
2008     return true;
2009   case Expr::ObjCBoxedExprClass:
2010     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2011   case Expr::CallExprClass:
2012     return IsNoOpCall(cast<CallExpr>(E));
2013   // For GCC compatibility, &&label has static storage duration.
2014   case Expr::AddrLabelExprClass:
2015     return true;
2016   // A Block literal expression may be used as the initialization value for
2017   // Block variables at global or local static scope.
2018   case Expr::BlockExprClass:
2019     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2020   // The APValue generated from a __builtin_source_location will be emitted as a
2021   // literal.
2022   case Expr::SourceLocExprClass:
2023     return true;
2024   case Expr::ImplicitValueInitExprClass:
2025     // FIXME:
2026     // We can never form an lvalue with an implicit value initialization as its
2027     // base through expression evaluation, so these only appear in one case: the
2028     // implicit variable declaration we invent when checking whether a constexpr
2029     // constructor can produce a constant expression. We must assume that such
2030     // an expression might be a global lvalue.
2031     return true;
2032   }
2033 }
2034 
GetLValueBaseDecl(const LValue & LVal)2035 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2036   return LVal.Base.dyn_cast<const ValueDecl*>();
2037 }
2038 
IsLiteralLValue(const LValue & Value)2039 static bool IsLiteralLValue(const LValue &Value) {
2040   if (Value.getLValueCallIndex())
2041     return false;
2042   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2043   return E && !isa<MaterializeTemporaryExpr>(E);
2044 }
2045 
IsWeakLValue(const LValue & Value)2046 static bool IsWeakLValue(const LValue &Value) {
2047   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2048   return Decl && Decl->isWeak();
2049 }
2050 
isZeroSized(const LValue & Value)2051 static bool isZeroSized(const LValue &Value) {
2052   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2053   if (Decl && isa<VarDecl>(Decl)) {
2054     QualType Ty = Decl->getType();
2055     if (Ty->isArrayType())
2056       return Ty->isIncompleteType() ||
2057              Decl->getASTContext().getTypeSize(Ty) == 0;
2058   }
2059   return false;
2060 }
2061 
HasSameBase(const LValue & A,const LValue & B)2062 static bool HasSameBase(const LValue &A, const LValue &B) {
2063   if (!A.getLValueBase())
2064     return !B.getLValueBase();
2065   if (!B.getLValueBase())
2066     return false;
2067 
2068   if (A.getLValueBase().getOpaqueValue() !=
2069       B.getLValueBase().getOpaqueValue())
2070     return false;
2071 
2072   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2073          A.getLValueVersion() == B.getLValueVersion();
2074 }
2075 
NoteLValueLocation(EvalInfo & Info,APValue::LValueBase Base)2076 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2077   assert(Base && "no location for a null lvalue");
2078   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2079 
2080   // For a parameter, find the corresponding call stack frame (if it still
2081   // exists), and point at the parameter of the function definition we actually
2082   // invoked.
2083   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2084     unsigned Idx = PVD->getFunctionScopeIndex();
2085     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2086       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2087           F->Arguments.Version == Base.getVersion() && F->Callee &&
2088           Idx < F->Callee->getNumParams()) {
2089         VD = F->Callee->getParamDecl(Idx);
2090         break;
2091       }
2092     }
2093   }
2094 
2095   if (VD)
2096     Info.Note(VD->getLocation(), diag::note_declared_at);
2097   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2098     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2099   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2100     // FIXME: Produce a note for dangling pointers too.
2101     if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2102       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2103                 diag::note_constexpr_dynamic_alloc_here);
2104   }
2105   // We have no information to show for a typeid(T) object.
2106 }
2107 
2108 enum class CheckEvaluationResultKind {
2109   ConstantExpression,
2110   FullyInitialized,
2111 };
2112 
2113 /// Materialized temporaries that we've already checked to determine if they're
2114 /// initializsed by a constant expression.
2115 using CheckedTemporaries =
2116     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2117 
2118 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2119                                   EvalInfo &Info, SourceLocation DiagLoc,
2120                                   QualType Type, const APValue &Value,
2121                                   ConstantExprKind Kind,
2122                                   SourceLocation SubobjectLoc,
2123                                   CheckedTemporaries &CheckedTemps);
2124 
2125 /// Check that this reference or pointer core constant expression is a valid
2126 /// value for an address or reference constant expression. Return true if we
2127 /// 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)2128 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2129                                           QualType Type, const LValue &LVal,
2130                                           ConstantExprKind Kind,
2131                                           CheckedTemporaries &CheckedTemps) {
2132   bool IsReferenceType = Type->isReferenceType();
2133 
2134   APValue::LValueBase Base = LVal.getLValueBase();
2135   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2136 
2137   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2138   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2139 
2140   // Additional restrictions apply in a template argument. We only enforce the
2141   // C++20 restrictions here; additional syntactic and semantic restrictions
2142   // are applied elsewhere.
2143   if (isTemplateArgument(Kind)) {
2144     int InvalidBaseKind = -1;
2145     StringRef Ident;
2146     if (Base.is<TypeInfoLValue>())
2147       InvalidBaseKind = 0;
2148     else if (isa_and_nonnull<StringLiteral>(BaseE))
2149       InvalidBaseKind = 1;
2150     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2151              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2152       InvalidBaseKind = 2;
2153     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2154       InvalidBaseKind = 3;
2155       Ident = PE->getIdentKindName();
2156     }
2157 
2158     if (InvalidBaseKind != -1) {
2159       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2160           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2161           << Ident;
2162       return false;
2163     }
2164   }
2165 
2166   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2167     if (FD->isConsteval()) {
2168       Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2169           << !Type->isAnyPointerType();
2170       Info.Note(FD->getLocation(), diag::note_declared_at);
2171       return false;
2172     }
2173   }
2174 
2175   // Check that the object is a global. Note that the fake 'this' object we
2176   // manufacture when checking potential constant expressions is conservatively
2177   // assumed to be global here.
2178   if (!IsGlobalLValue(Base)) {
2179     if (Info.getLangOpts().CPlusPlus11) {
2180       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2181           << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2182           << BaseVD;
2183       auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2184       if (VarD && VarD->isConstexpr()) {
2185         // Non-static local constexpr variables have unintuitive semantics:
2186         //   constexpr int a = 1;
2187         //   constexpr const int *p = &a;
2188         // ... is invalid because the address of 'a' is not constant. Suggest
2189         // adding a 'static' in this case.
2190         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2191             << VarD
2192             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2193       } else {
2194         NoteLValueLocation(Info, Base);
2195       }
2196     } else {
2197       Info.FFDiag(Loc);
2198     }
2199     // Don't allow references to temporaries to escape.
2200     return false;
2201   }
2202   assert((Info.checkingPotentialConstantExpression() ||
2203           LVal.getLValueCallIndex() == 0) &&
2204          "have call index for global lvalue");
2205 
2206   if (Base.is<DynamicAllocLValue>()) {
2207     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2208         << IsReferenceType << !Designator.Entries.empty();
2209     NoteLValueLocation(Info, Base);
2210     return false;
2211   }
2212 
2213   if (BaseVD) {
2214     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2215       // Check if this is a thread-local variable.
2216       if (Var->getTLSKind())
2217         // FIXME: Diagnostic!
2218         return false;
2219 
2220       // A dllimport variable never acts like a constant, unless we're
2221       // evaluating a value for use only in name mangling.
2222       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2223         // FIXME: Diagnostic!
2224         return false;
2225 
2226       // In CUDA/HIP device compilation, only device side variables have
2227       // constant addresses.
2228       if (Info.getCtx().getLangOpts().CUDA &&
2229           Info.getCtx().getLangOpts().CUDAIsDevice &&
2230           Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2231         if ((!Var->hasAttr<CUDADeviceAttr>() &&
2232              !Var->hasAttr<CUDAConstantAttr>() &&
2233              !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2234              !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2235             Var->hasAttr<HIPManagedAttr>())
2236           return false;
2237       }
2238     }
2239     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2240       // __declspec(dllimport) must be handled very carefully:
2241       // We must never initialize an expression with the thunk in C++.
2242       // Doing otherwise would allow the same id-expression to yield
2243       // different addresses for the same function in different translation
2244       // units.  However, this means that we must dynamically initialize the
2245       // expression with the contents of the import address table at runtime.
2246       //
2247       // The C language has no notion of ODR; furthermore, it has no notion of
2248       // dynamic initialization.  This means that we are permitted to
2249       // perform initialization with the address of the thunk.
2250       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2251           FD->hasAttr<DLLImportAttr>())
2252         // FIXME: Diagnostic!
2253         return false;
2254     }
2255   } else if (const auto *MTE =
2256                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2257     if (CheckedTemps.insert(MTE).second) {
2258       QualType TempType = getType(Base);
2259       if (TempType.isDestructedType()) {
2260         Info.FFDiag(MTE->getExprLoc(),
2261                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2262             << TempType;
2263         return false;
2264       }
2265 
2266       APValue *V = MTE->getOrCreateValue(false);
2267       assert(V && "evasluation result refers to uninitialised temporary");
2268       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2269                                  Info, MTE->getExprLoc(), TempType, *V,
2270                                  Kind, SourceLocation(), CheckedTemps))
2271         return false;
2272     }
2273   }
2274 
2275   // Allow address constant expressions to be past-the-end pointers. This is
2276   // an extension: the standard requires them to point to an object.
2277   if (!IsReferenceType)
2278     return true;
2279 
2280   // A reference constant expression must refer to an object.
2281   if (!Base) {
2282     // FIXME: diagnostic
2283     Info.CCEDiag(Loc);
2284     return true;
2285   }
2286 
2287   // Does this refer one past the end of some object?
2288   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2289     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2290       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2291     NoteLValueLocation(Info, Base);
2292   }
2293 
2294   return true;
2295 }
2296 
2297 /// Member pointers are constant expressions unless they point to a
2298 /// non-virtual dllimport member function.
CheckMemberPointerConstantExpression(EvalInfo & Info,SourceLocation Loc,QualType Type,const APValue & Value,ConstantExprKind Kind)2299 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2300                                                  SourceLocation Loc,
2301                                                  QualType Type,
2302                                                  const APValue &Value,
2303                                                  ConstantExprKind Kind) {
2304   const ValueDecl *Member = Value.getMemberPointerDecl();
2305   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2306   if (!FD)
2307     return true;
2308   if (FD->isConsteval()) {
2309     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2310     Info.Note(FD->getLocation(), diag::note_declared_at);
2311     return false;
2312   }
2313   return isForManglingOnly(Kind) || FD->isVirtual() ||
2314          !FD->hasAttr<DLLImportAttr>();
2315 }
2316 
2317 /// Check that this core constant expression is of literal type, and if not,
2318 /// produce an appropriate diagnostic.
CheckLiteralType(EvalInfo & Info,const Expr * E,const LValue * This=nullptr)2319 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2320                              const LValue *This = nullptr) {
2321   if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2322     return true;
2323 
2324   // C++1y: A constant initializer for an object o [...] may also invoke
2325   // constexpr constructors for o and its subobjects even if those objects
2326   // are of non-literal class types.
2327   //
2328   // C++11 missed this detail for aggregates, so classes like this:
2329   //   struct foo_t { union { int i; volatile int j; } u; };
2330   // are not (obviously) initializable like so:
2331   //   __attribute__((__require_constant_initialization__))
2332   //   static const foo_t x = {{0}};
2333   // because "i" is a subobject with non-literal initialization (due to the
2334   // volatile member of the union). See:
2335   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2336   // Therefore, we use the C++1y behavior.
2337   if (This && Info.EvaluatingDecl == This->getLValueBase())
2338     return true;
2339 
2340   // Prvalue constant expressions must be of literal types.
2341   if (Info.getLangOpts().CPlusPlus11)
2342     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2343       << E->getType();
2344   else
2345     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2346   return false;
2347 }
2348 
CheckEvaluationResult(CheckEvaluationResultKind CERK,EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value,ConstantExprKind Kind,SourceLocation SubobjectLoc,CheckedTemporaries & CheckedTemps)2349 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2350                                   EvalInfo &Info, SourceLocation DiagLoc,
2351                                   QualType Type, const APValue &Value,
2352                                   ConstantExprKind Kind,
2353                                   SourceLocation SubobjectLoc,
2354                                   CheckedTemporaries &CheckedTemps) {
2355   if (!Value.hasValue()) {
2356     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2357       << true << Type;
2358     if (SubobjectLoc.isValid())
2359       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2360     return false;
2361   }
2362 
2363   // We allow _Atomic(T) to be initialized from anything that T can be
2364   // initialized from.
2365   if (const AtomicType *AT = Type->getAs<AtomicType>())
2366     Type = AT->getValueType();
2367 
2368   // Core issue 1454: For a literal constant expression of array or class type,
2369   // each subobject of its value shall have been initialized by a constant
2370   // expression.
2371   if (Value.isArray()) {
2372     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2373     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2374       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2375                                  Value.getArrayInitializedElt(I), Kind,
2376                                  SubobjectLoc, CheckedTemps))
2377         return false;
2378     }
2379     if (!Value.hasArrayFiller())
2380       return true;
2381     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2382                                  Value.getArrayFiller(), Kind, SubobjectLoc,
2383                                  CheckedTemps);
2384   }
2385   if (Value.isUnion() && Value.getUnionField()) {
2386     return CheckEvaluationResult(
2387         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2388         Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2389         CheckedTemps);
2390   }
2391   if (Value.isStruct()) {
2392     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2393     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2394       unsigned BaseIndex = 0;
2395       for (const CXXBaseSpecifier &BS : CD->bases()) {
2396         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2397                                    Value.getStructBase(BaseIndex), Kind,
2398                                    BS.getBeginLoc(), CheckedTemps))
2399           return false;
2400         ++BaseIndex;
2401       }
2402     }
2403     for (const auto *I : RD->fields()) {
2404       if (I->isUnnamedBitfield())
2405         continue;
2406 
2407       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2408                                  Value.getStructField(I->getFieldIndex()),
2409                                  Kind, I->getLocation(), CheckedTemps))
2410         return false;
2411     }
2412   }
2413 
2414   if (Value.isLValue() &&
2415       CERK == CheckEvaluationResultKind::ConstantExpression) {
2416     LValue LVal;
2417     LVal.setFrom(Info.Ctx, Value);
2418     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2419                                          CheckedTemps);
2420   }
2421 
2422   if (Value.isMemberPointer() &&
2423       CERK == CheckEvaluationResultKind::ConstantExpression)
2424     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2425 
2426   // Everything else is fine.
2427   return true;
2428 }
2429 
2430 /// Check that this core constant expression value is a valid value for a
2431 /// constant expression. If not, report an appropriate diagnostic. Does not
2432 /// check that the expression is of literal type.
CheckConstantExpression(EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value,ConstantExprKind Kind)2433 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2434                                     QualType Type, const APValue &Value,
2435                                     ConstantExprKind Kind) {
2436   // Nothing to check for a constant expression of type 'cv void'.
2437   if (Type->isVoidType())
2438     return true;
2439 
2440   CheckedTemporaries CheckedTemps;
2441   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2442                                Info, DiagLoc, Type, Value, Kind,
2443                                SourceLocation(), CheckedTemps);
2444 }
2445 
2446 /// Check that this evaluated value is fully-initialized and can be loaded by
2447 /// an lvalue-to-rvalue conversion.
CheckFullyInitialized(EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value)2448 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2449                                   QualType Type, const APValue &Value) {
2450   CheckedTemporaries CheckedTemps;
2451   return CheckEvaluationResult(
2452       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2453       ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2454 }
2455 
2456 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2457 /// "the allocated storage is deallocated within the evaluation".
CheckMemoryLeaks(EvalInfo & Info)2458 static bool CheckMemoryLeaks(EvalInfo &Info) {
2459   if (!Info.HeapAllocs.empty()) {
2460     // We can still fold to a constant despite a compile-time memory leak,
2461     // so long as the heap allocation isn't referenced in the result (we check
2462     // that in CheckConstantExpression).
2463     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2464                  diag::note_constexpr_memory_leak)
2465         << unsigned(Info.HeapAllocs.size() - 1);
2466   }
2467   return true;
2468 }
2469 
EvalPointerValueAsBool(const APValue & Value,bool & Result)2470 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2471   // A null base expression indicates a null pointer.  These are always
2472   // evaluatable, and they are false unless the offset is zero.
2473   if (!Value.getLValueBase()) {
2474     // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2475     Result = !Value.getLValueOffset().isZero();
2476     return true;
2477   }
2478 
2479   // We have a non-null base.  These are generally known to be true, but if it's
2480   // a weak declaration it can be null at runtime.
2481   Result = true;
2482   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2483   return !Decl || !Decl->isWeak();
2484 }
2485 
HandleConversionToBool(const APValue & Val,bool & Result)2486 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2487   // TODO: This function should produce notes if it fails.
2488   switch (Val.getKind()) {
2489   case APValue::None:
2490   case APValue::Indeterminate:
2491     return false;
2492   case APValue::Int:
2493     Result = Val.getInt().getBoolValue();
2494     return true;
2495   case APValue::FixedPoint:
2496     Result = Val.getFixedPoint().getBoolValue();
2497     return true;
2498   case APValue::Float:
2499     Result = !Val.getFloat().isZero();
2500     return true;
2501   case APValue::ComplexInt:
2502     Result = Val.getComplexIntReal().getBoolValue() ||
2503              Val.getComplexIntImag().getBoolValue();
2504     return true;
2505   case APValue::ComplexFloat:
2506     Result = !Val.getComplexFloatReal().isZero() ||
2507              !Val.getComplexFloatImag().isZero();
2508     return true;
2509   case APValue::LValue:
2510     return EvalPointerValueAsBool(Val, Result);
2511   case APValue::MemberPointer:
2512     if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2513       return false;
2514     }
2515     Result = Val.getMemberPointerDecl();
2516     return true;
2517   case APValue::Vector:
2518   case APValue::Array:
2519   case APValue::Struct:
2520   case APValue::Union:
2521   case APValue::AddrLabelDiff:
2522     return false;
2523   }
2524 
2525   llvm_unreachable("unknown APValue kind");
2526 }
2527 
EvaluateAsBooleanCondition(const Expr * E,bool & Result,EvalInfo & Info)2528 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2529                                        EvalInfo &Info) {
2530   assert(!E->isValueDependent());
2531   assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2532   APValue Val;
2533   if (!Evaluate(Val, Info, E))
2534     return false;
2535   return HandleConversionToBool(Val, Result);
2536 }
2537 
2538 template<typename T>
HandleOverflow(EvalInfo & Info,const Expr * E,const T & SrcValue,QualType DestType)2539 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2540                            const T &SrcValue, QualType DestType) {
2541   Info.CCEDiag(E, diag::note_constexpr_overflow)
2542     << SrcValue << DestType;
2543   return Info.noteUndefinedBehavior();
2544 }
2545 
HandleFloatToIntCast(EvalInfo & Info,const Expr * E,QualType SrcType,const APFloat & Value,QualType DestType,APSInt & Result)2546 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2547                                  QualType SrcType, const APFloat &Value,
2548                                  QualType DestType, APSInt &Result) {
2549   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2550   // Determine whether we are converting to unsigned or signed.
2551   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2552 
2553   Result = APSInt(DestWidth, !DestSigned);
2554   bool ignored;
2555   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2556       & APFloat::opInvalidOp)
2557     return HandleOverflow(Info, E, Value, DestType);
2558   return true;
2559 }
2560 
2561 /// Get rounding mode to use in evaluation of the specified expression.
2562 ///
2563 /// If rounding mode is unknown at compile time, still try to evaluate the
2564 /// expression. If the result is exact, it does not depend on rounding mode.
2565 /// So return "tonearest" mode instead of "dynamic".
getActiveRoundingMode(EvalInfo & Info,const Expr * E)2566 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2567   llvm::RoundingMode RM =
2568       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2569   if (RM == llvm::RoundingMode::Dynamic)
2570     RM = llvm::RoundingMode::NearestTiesToEven;
2571   return RM;
2572 }
2573 
2574 /// Check if the given evaluation result is allowed for constant evaluation.
checkFloatingPointResult(EvalInfo & Info,const Expr * E,APFloat::opStatus St)2575 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2576                                      APFloat::opStatus St) {
2577   // In a constant context, assume that any dynamic rounding mode or FP
2578   // exception state matches the default floating-point environment.
2579   if (Info.InConstantContext)
2580     return true;
2581 
2582   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2583   if ((St & APFloat::opInexact) &&
2584       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2585     // Inexact result means that it depends on rounding mode. If the requested
2586     // mode is dynamic, the evaluation cannot be made in compile time.
2587     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2588     return false;
2589   }
2590 
2591   if ((St != APFloat::opOK) &&
2592       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2593        FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2594        FPO.getAllowFEnvAccess())) {
2595     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2596     return false;
2597   }
2598 
2599   if ((St & APFloat::opStatus::opInvalidOp) &&
2600       FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2601     // There is no usefully definable result.
2602     Info.FFDiag(E);
2603     return false;
2604   }
2605 
2606   // FIXME: if:
2607   // - evaluation triggered other FP exception, and
2608   // - exception mode is not "ignore", and
2609   // - the expression being evaluated is not a part of global variable
2610   //   initializer,
2611   // the evaluation probably need to be rejected.
2612   return true;
2613 }
2614 
HandleFloatToFloatCast(EvalInfo & Info,const Expr * E,QualType SrcType,QualType DestType,APFloat & Result)2615 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2616                                    QualType SrcType, QualType DestType,
2617                                    APFloat &Result) {
2618   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2619   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2620   APFloat::opStatus St;
2621   APFloat Value = Result;
2622   bool ignored;
2623   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2624   return checkFloatingPointResult(Info, E, St);
2625 }
2626 
HandleIntToIntCast(EvalInfo & Info,const Expr * E,QualType DestType,QualType SrcType,const APSInt & Value)2627 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2628                                  QualType DestType, QualType SrcType,
2629                                  const APSInt &Value) {
2630   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2631   // Figure out if this is a truncate, extend or noop cast.
2632   // If the input is signed, do a sign extend, noop, or truncate.
2633   APSInt Result = Value.extOrTrunc(DestWidth);
2634   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2635   if (DestType->isBooleanType())
2636     Result = Value.getBoolValue();
2637   return Result;
2638 }
2639 
HandleIntToFloatCast(EvalInfo & Info,const Expr * E,const FPOptions FPO,QualType SrcType,const APSInt & Value,QualType DestType,APFloat & Result)2640 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2641                                  const FPOptions FPO,
2642                                  QualType SrcType, const APSInt &Value,
2643                                  QualType DestType, APFloat &Result) {
2644   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2645   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2646   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2647   return checkFloatingPointResult(Info, E, St);
2648 }
2649 
truncateBitfieldValue(EvalInfo & Info,const Expr * E,APValue & Value,const FieldDecl * FD)2650 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2651                                   APValue &Value, const FieldDecl *FD) {
2652   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2653 
2654   if (!Value.isInt()) {
2655     // Trying to store a pointer-cast-to-integer into a bitfield.
2656     // FIXME: In this case, we should provide the diagnostic for casting
2657     // a pointer to an integer.
2658     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2659     Info.FFDiag(E);
2660     return false;
2661   }
2662 
2663   APSInt &Int = Value.getInt();
2664   unsigned OldBitWidth = Int.getBitWidth();
2665   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2666   if (NewBitWidth < OldBitWidth)
2667     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2668   return true;
2669 }
2670 
EvalAndBitcastToAPInt(EvalInfo & Info,const Expr * E,llvm::APInt & Res)2671 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2672                                   llvm::APInt &Res) {
2673   APValue SVal;
2674   if (!Evaluate(SVal, Info, E))
2675     return false;
2676   if (SVal.isInt()) {
2677     Res = SVal.getInt();
2678     return true;
2679   }
2680   if (SVal.isFloat()) {
2681     Res = SVal.getFloat().bitcastToAPInt();
2682     return true;
2683   }
2684   if (SVal.isVector()) {
2685     QualType VecTy = E->getType();
2686     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2687     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2688     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2689     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2690     Res = llvm::APInt::getZero(VecSize);
2691     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2692       APValue &Elt = SVal.getVectorElt(i);
2693       llvm::APInt EltAsInt;
2694       if (Elt.isInt()) {
2695         EltAsInt = Elt.getInt();
2696       } else if (Elt.isFloat()) {
2697         EltAsInt = Elt.getFloat().bitcastToAPInt();
2698       } else {
2699         // Don't try to handle vectors of anything other than int or float
2700         // (not sure if it's possible to hit this case).
2701         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2702         return false;
2703       }
2704       unsigned BaseEltSize = EltAsInt.getBitWidth();
2705       if (BigEndian)
2706         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2707       else
2708         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2709     }
2710     return true;
2711   }
2712   // Give up if the input isn't an int, float, or vector.  For example, we
2713   // reject "(v4i16)(intptr_t)&a".
2714   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2715   return false;
2716 }
2717 
2718 /// Perform the given integer operation, which is known to need at most BitWidth
2719 /// bits, and check for overflow in the original type (if that type was not an
2720 /// unsigned type).
2721 template<typename Operation>
CheckedIntArithmetic(EvalInfo & Info,const Expr * E,const APSInt & LHS,const APSInt & RHS,unsigned BitWidth,Operation Op,APSInt & Result)2722 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2723                                  const APSInt &LHS, const APSInt &RHS,
2724                                  unsigned BitWidth, Operation Op,
2725                                  APSInt &Result) {
2726   if (LHS.isUnsigned()) {
2727     Result = Op(LHS, RHS);
2728     return true;
2729   }
2730 
2731   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2732   Result = Value.trunc(LHS.getBitWidth());
2733   if (Result.extend(BitWidth) != Value) {
2734     if (Info.checkingForUndefinedBehavior())
2735       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2736                                        diag::warn_integer_constant_overflow)
2737           << toString(Result, 10) << E->getType();
2738     return HandleOverflow(Info, E, Value, E->getType());
2739   }
2740   return true;
2741 }
2742 
2743 /// Perform the given binary integer operation.
handleIntIntBinOp(EvalInfo & Info,const Expr * E,const APSInt & LHS,BinaryOperatorKind Opcode,APSInt RHS,APSInt & Result)2744 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2745                               BinaryOperatorKind Opcode, APSInt RHS,
2746                               APSInt &Result) {
2747   bool HandleOverflowResult = true;
2748   switch (Opcode) {
2749   default:
2750     Info.FFDiag(E);
2751     return false;
2752   case BO_Mul:
2753     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2754                                 std::multiplies<APSInt>(), Result);
2755   case BO_Add:
2756     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2757                                 std::plus<APSInt>(), Result);
2758   case BO_Sub:
2759     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2760                                 std::minus<APSInt>(), Result);
2761   case BO_And: Result = LHS & RHS; return true;
2762   case BO_Xor: Result = LHS ^ RHS; return true;
2763   case BO_Or:  Result = LHS | RHS; return true;
2764   case BO_Div:
2765   case BO_Rem:
2766     if (RHS == 0) {
2767       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2768       return false;
2769     }
2770     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2771     // this operation and gives the two's complement result.
2772     if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2773         LHS.isMinSignedValue())
2774       HandleOverflowResult = HandleOverflow(
2775           Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2776     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2777     return HandleOverflowResult;
2778   case BO_Shl: {
2779     if (Info.getLangOpts().OpenCL)
2780       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2781       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2782                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2783                     RHS.isUnsigned());
2784     else if (RHS.isSigned() && RHS.isNegative()) {
2785       // During constant-folding, a negative shift is an opposite shift. Such
2786       // a shift is not a constant expression.
2787       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2788       RHS = -RHS;
2789       goto shift_right;
2790     }
2791   shift_left:
2792     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2793     // the shifted type.
2794     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2795     if (SA != RHS) {
2796       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2797         << RHS << E->getType() << LHS.getBitWidth();
2798     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2799       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2800       // operand, and must not overflow the corresponding unsigned type.
2801       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2802       // E1 x 2^E2 module 2^N.
2803       if (LHS.isNegative())
2804         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2805       else if (LHS.countLeadingZeros() < SA)
2806         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2807     }
2808     Result = LHS << SA;
2809     return true;
2810   }
2811   case BO_Shr: {
2812     if (Info.getLangOpts().OpenCL)
2813       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2814       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2815                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2816                     RHS.isUnsigned());
2817     else if (RHS.isSigned() && RHS.isNegative()) {
2818       // During constant-folding, a negative shift is an opposite shift. Such a
2819       // shift is not a constant expression.
2820       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2821       RHS = -RHS;
2822       goto shift_left;
2823     }
2824   shift_right:
2825     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2826     // shifted type.
2827     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2828     if (SA != RHS)
2829       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2830         << RHS << E->getType() << LHS.getBitWidth();
2831     Result = LHS >> SA;
2832     return true;
2833   }
2834 
2835   case BO_LT: Result = LHS < RHS; return true;
2836   case BO_GT: Result = LHS > RHS; return true;
2837   case BO_LE: Result = LHS <= RHS; return true;
2838   case BO_GE: Result = LHS >= RHS; return true;
2839   case BO_EQ: Result = LHS == RHS; return true;
2840   case BO_NE: Result = LHS != RHS; return true;
2841   case BO_Cmp:
2842     llvm_unreachable("BO_Cmp should be handled elsewhere");
2843   }
2844 }
2845 
2846 /// Perform the given binary floating-point operation, in-place, on LHS.
handleFloatFloatBinOp(EvalInfo & Info,const BinaryOperator * E,APFloat & LHS,BinaryOperatorKind Opcode,const APFloat & RHS)2847 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2848                                   APFloat &LHS, BinaryOperatorKind Opcode,
2849                                   const APFloat &RHS) {
2850   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2851   APFloat::opStatus St;
2852   switch (Opcode) {
2853   default:
2854     Info.FFDiag(E);
2855     return false;
2856   case BO_Mul:
2857     St = LHS.multiply(RHS, RM);
2858     break;
2859   case BO_Add:
2860     St = LHS.add(RHS, RM);
2861     break;
2862   case BO_Sub:
2863     St = LHS.subtract(RHS, RM);
2864     break;
2865   case BO_Div:
2866     // [expr.mul]p4:
2867     //   If the second operand of / or % is zero the behavior is undefined.
2868     if (RHS.isZero())
2869       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2870     St = LHS.divide(RHS, RM);
2871     break;
2872   }
2873 
2874   // [expr.pre]p4:
2875   //   If during the evaluation of an expression, the result is not
2876   //   mathematically defined [...], the behavior is undefined.
2877   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2878   if (LHS.isNaN()) {
2879     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2880     return Info.noteUndefinedBehavior();
2881   }
2882 
2883   return checkFloatingPointResult(Info, E, St);
2884 }
2885 
handleLogicalOpForVector(const APInt & LHSValue,BinaryOperatorKind Opcode,const APInt & RHSValue,APInt & Result)2886 static bool handleLogicalOpForVector(const APInt &LHSValue,
2887                                      BinaryOperatorKind Opcode,
2888                                      const APInt &RHSValue, APInt &Result) {
2889   bool LHS = (LHSValue != 0);
2890   bool RHS = (RHSValue != 0);
2891 
2892   if (Opcode == BO_LAnd)
2893     Result = LHS && RHS;
2894   else
2895     Result = LHS || RHS;
2896   return true;
2897 }
handleLogicalOpForVector(const APFloat & LHSValue,BinaryOperatorKind Opcode,const APFloat & RHSValue,APInt & Result)2898 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2899                                      BinaryOperatorKind Opcode,
2900                                      const APFloat &RHSValue, APInt &Result) {
2901   bool LHS = !LHSValue.isZero();
2902   bool RHS = !RHSValue.isZero();
2903 
2904   if (Opcode == BO_LAnd)
2905     Result = LHS && RHS;
2906   else
2907     Result = LHS || RHS;
2908   return true;
2909 }
2910 
handleLogicalOpForVector(const APValue & LHSValue,BinaryOperatorKind Opcode,const APValue & RHSValue,APInt & Result)2911 static bool handleLogicalOpForVector(const APValue &LHSValue,
2912                                      BinaryOperatorKind Opcode,
2913                                      const APValue &RHSValue, APInt &Result) {
2914   // The result is always an int type, however operands match the first.
2915   if (LHSValue.getKind() == APValue::Int)
2916     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2917                                     RHSValue.getInt(), Result);
2918   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2919   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2920                                   RHSValue.getFloat(), Result);
2921 }
2922 
2923 template <typename APTy>
2924 static bool
handleCompareOpForVectorHelper(const APTy & LHSValue,BinaryOperatorKind Opcode,const APTy & RHSValue,APInt & Result)2925 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2926                                const APTy &RHSValue, APInt &Result) {
2927   switch (Opcode) {
2928   default:
2929     llvm_unreachable("unsupported binary operator");
2930   case BO_EQ:
2931     Result = (LHSValue == RHSValue);
2932     break;
2933   case BO_NE:
2934     Result = (LHSValue != RHSValue);
2935     break;
2936   case BO_LT:
2937     Result = (LHSValue < RHSValue);
2938     break;
2939   case BO_GT:
2940     Result = (LHSValue > RHSValue);
2941     break;
2942   case BO_LE:
2943     Result = (LHSValue <= RHSValue);
2944     break;
2945   case BO_GE:
2946     Result = (LHSValue >= RHSValue);
2947     break;
2948   }
2949 
2950   // The boolean operations on these vector types use an instruction that
2951   // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2952   // to -1 to make sure that we produce the correct value.
2953   Result.negate();
2954 
2955   return true;
2956 }
2957 
handleCompareOpForVector(const APValue & LHSValue,BinaryOperatorKind Opcode,const APValue & RHSValue,APInt & Result)2958 static bool handleCompareOpForVector(const APValue &LHSValue,
2959                                      BinaryOperatorKind Opcode,
2960                                      const APValue &RHSValue, APInt &Result) {
2961   // The result is always an int type, however operands match the first.
2962   if (LHSValue.getKind() == APValue::Int)
2963     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2964                                           RHSValue.getInt(), Result);
2965   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2966   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2967                                         RHSValue.getFloat(), Result);
2968 }
2969 
2970 // Perform binary operations for vector types, in place on the LHS.
handleVectorVectorBinOp(EvalInfo & Info,const BinaryOperator * E,BinaryOperatorKind Opcode,APValue & LHSValue,const APValue & RHSValue)2971 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2972                                     BinaryOperatorKind Opcode,
2973                                     APValue &LHSValue,
2974                                     const APValue &RHSValue) {
2975   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2976          "Operation not supported on vector types");
2977 
2978   const auto *VT = E->getType()->castAs<VectorType>();
2979   unsigned NumElements = VT->getNumElements();
2980   QualType EltTy = VT->getElementType();
2981 
2982   // In the cases (typically C as I've observed) where we aren't evaluating
2983   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2984   // just give up.
2985   if (!LHSValue.isVector()) {
2986     assert(LHSValue.isLValue() &&
2987            "A vector result that isn't a vector OR uncalculated LValue");
2988     Info.FFDiag(E);
2989     return false;
2990   }
2991 
2992   assert(LHSValue.getVectorLength() == NumElements &&
2993          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2994 
2995   SmallVector<APValue, 4> ResultElements;
2996 
2997   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2998     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2999     APValue RHSElt = RHSValue.getVectorElt(EltNum);
3000 
3001     if (EltTy->isIntegerType()) {
3002       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3003                        EltTy->isUnsignedIntegerType()};
3004       bool Success = true;
3005 
3006       if (BinaryOperator::isLogicalOp(Opcode))
3007         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3008       else if (BinaryOperator::isComparisonOp(Opcode))
3009         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3010       else
3011         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3012                                     RHSElt.getInt(), EltResult);
3013 
3014       if (!Success) {
3015         Info.FFDiag(E);
3016         return false;
3017       }
3018       ResultElements.emplace_back(EltResult);
3019 
3020     } else if (EltTy->isFloatingType()) {
3021       assert(LHSElt.getKind() == APValue::Float &&
3022              RHSElt.getKind() == APValue::Float &&
3023              "Mismatched LHS/RHS/Result Type");
3024       APFloat LHSFloat = LHSElt.getFloat();
3025 
3026       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3027                                  RHSElt.getFloat())) {
3028         Info.FFDiag(E);
3029         return false;
3030       }
3031 
3032       ResultElements.emplace_back(LHSFloat);
3033     }
3034   }
3035 
3036   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3037   return true;
3038 }
3039 
3040 /// Cast an lvalue referring to a base subobject to a derived class, by
3041 /// truncating the lvalue's path to the given length.
CastToDerivedClass(EvalInfo & Info,const Expr * E,LValue & Result,const RecordDecl * TruncatedType,unsigned TruncatedElements)3042 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3043                                const RecordDecl *TruncatedType,
3044                                unsigned TruncatedElements) {
3045   SubobjectDesignator &D = Result.Designator;
3046 
3047   // Check we actually point to a derived class object.
3048   if (TruncatedElements == D.Entries.size())
3049     return true;
3050   assert(TruncatedElements >= D.MostDerivedPathLength &&
3051          "not casting to a derived class");
3052   if (!Result.checkSubobject(Info, E, CSK_Derived))
3053     return false;
3054 
3055   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3056   const RecordDecl *RD = TruncatedType;
3057   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3058     if (RD->isInvalidDecl()) return false;
3059     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3060     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3061     if (isVirtualBaseClass(D.Entries[I]))
3062       Result.Offset -= Layout.getVBaseClassOffset(Base);
3063     else
3064       Result.Offset -= Layout.getBaseClassOffset(Base);
3065     RD = Base;
3066   }
3067   D.Entries.resize(TruncatedElements);
3068   return true;
3069 }
3070 
HandleLValueDirectBase(EvalInfo & Info,const Expr * E,LValue & Obj,const CXXRecordDecl * Derived,const CXXRecordDecl * Base,const ASTRecordLayout * RL=nullptr)3071 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3072                                    const CXXRecordDecl *Derived,
3073                                    const CXXRecordDecl *Base,
3074                                    const ASTRecordLayout *RL = nullptr) {
3075   if (!RL) {
3076     if (Derived->isInvalidDecl()) return false;
3077     RL = &Info.Ctx.getASTRecordLayout(Derived);
3078   }
3079 
3080   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3081   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3082   return true;
3083 }
3084 
HandleLValueBase(EvalInfo & Info,const Expr * E,LValue & Obj,const CXXRecordDecl * DerivedDecl,const CXXBaseSpecifier * Base)3085 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3086                              const CXXRecordDecl *DerivedDecl,
3087                              const CXXBaseSpecifier *Base) {
3088   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3089 
3090   if (!Base->isVirtual())
3091     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3092 
3093   SubobjectDesignator &D = Obj.Designator;
3094   if (D.Invalid)
3095     return false;
3096 
3097   // Extract most-derived object and corresponding type.
3098   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3099   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3100     return false;
3101 
3102   // Find the virtual base class.
3103   if (DerivedDecl->isInvalidDecl()) return false;
3104   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3105   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3106   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3107   return true;
3108 }
3109 
HandleLValueBasePath(EvalInfo & Info,const CastExpr * E,QualType Type,LValue & Result)3110 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3111                                  QualType Type, LValue &Result) {
3112   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3113                                      PathE = E->path_end();
3114        PathI != PathE; ++PathI) {
3115     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3116                           *PathI))
3117       return false;
3118     Type = (*PathI)->getType();
3119   }
3120   return true;
3121 }
3122 
3123 /// 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)3124 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3125                             const CXXRecordDecl *DerivedRD,
3126                             const CXXRecordDecl *BaseRD) {
3127   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3128                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3129   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3130     llvm_unreachable("Class must be derived from the passed in base class!");
3131 
3132   for (CXXBasePathElement &Elem : Paths.front())
3133     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3134       return false;
3135   return true;
3136 }
3137 
3138 /// Update LVal to refer to the given field, which must be a member of the type
3139 /// currently described by LVal.
HandleLValueMember(EvalInfo & Info,const Expr * E,LValue & LVal,const FieldDecl * FD,const ASTRecordLayout * RL=nullptr)3140 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3141                                const FieldDecl *FD,
3142                                const ASTRecordLayout *RL = nullptr) {
3143   if (!RL) {
3144     if (FD->getParent()->isInvalidDecl()) return false;
3145     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3146   }
3147 
3148   unsigned I = FD->getFieldIndex();
3149   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3150   LVal.addDecl(Info, E, FD);
3151   return true;
3152 }
3153 
3154 /// Update LVal to refer to the given indirect field.
HandleLValueIndirectMember(EvalInfo & Info,const Expr * E,LValue & LVal,const IndirectFieldDecl * IFD)3155 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3156                                        LValue &LVal,
3157                                        const IndirectFieldDecl *IFD) {
3158   for (const auto *C : IFD->chain())
3159     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3160       return false;
3161   return true;
3162 }
3163 
3164 /// Get the size of the given type in char units.
HandleSizeof(EvalInfo & Info,SourceLocation Loc,QualType Type,CharUnits & Size)3165 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3166                          QualType Type, CharUnits &Size) {
3167   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3168   // extension.
3169   if (Type->isVoidType() || Type->isFunctionType()) {
3170     Size = CharUnits::One();
3171     return true;
3172   }
3173 
3174   if (Type->isDependentType()) {
3175     Info.FFDiag(Loc);
3176     return false;
3177   }
3178 
3179   if (!Type->isConstantSizeType()) {
3180     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3181     // FIXME: Better diagnostic.
3182     Info.FFDiag(Loc);
3183     return false;
3184   }
3185 
3186   Size = Info.Ctx.getTypeSizeInChars(Type);
3187   return true;
3188 }
3189 
3190 /// Update a pointer value to model pointer arithmetic.
3191 /// \param Info - Information about the ongoing evaluation.
3192 /// \param E - The expression being evaluated, for diagnostic purposes.
3193 /// \param LVal - The pointer value to be updated.
3194 /// \param EltTy - The pointee type represented by LVal.
3195 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
HandleLValueArrayAdjustment(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,APSInt Adjustment)3196 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3197                                         LValue &LVal, QualType EltTy,
3198                                         APSInt Adjustment) {
3199   CharUnits SizeOfPointee;
3200   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3201     return false;
3202 
3203   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3204   return true;
3205 }
3206 
HandleLValueArrayAdjustment(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,int64_t Adjustment)3207 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3208                                         LValue &LVal, QualType EltTy,
3209                                         int64_t Adjustment) {
3210   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3211                                      APSInt::get(Adjustment));
3212 }
3213 
3214 /// Update an lvalue to refer to a component of a complex number.
3215 /// \param Info - Information about the ongoing evaluation.
3216 /// \param LVal - The lvalue to be updated.
3217 /// \param EltTy - The complex number's component type.
3218 /// \param Imag - False for the real component, true for the imaginary.
HandleLValueComplexElement(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,bool Imag)3219 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3220                                        LValue &LVal, QualType EltTy,
3221                                        bool Imag) {
3222   if (Imag) {
3223     CharUnits SizeOfComponent;
3224     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3225       return false;
3226     LVal.Offset += SizeOfComponent;
3227   }
3228   LVal.addComplex(Info, E, EltTy, Imag);
3229   return true;
3230 }
3231 
3232 /// Try to evaluate the initializer for a variable declaration.
3233 ///
3234 /// \param Info   Information about the ongoing evaluation.
3235 /// \param E      An expression to be used when printing diagnostics.
3236 /// \param VD     The variable whose initializer should be obtained.
3237 /// \param Version The version of the variable within the frame.
3238 /// \param Frame  The frame in which the variable was created. Must be null
3239 ///               if this variable is not local to the evaluation.
3240 /// \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)3241 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3242                                 const VarDecl *VD, CallStackFrame *Frame,
3243                                 unsigned Version, APValue *&Result) {
3244   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3245 
3246   // If this is a local variable, dig out its value.
3247   if (Frame) {
3248     Result = Frame->getTemporary(VD, Version);
3249     if (Result)
3250       return true;
3251 
3252     if (!isa<ParmVarDecl>(VD)) {
3253       // Assume variables referenced within a lambda's call operator that were
3254       // not declared within the call operator are captures and during checking
3255       // of a potential constant expression, assume they are unknown constant
3256       // expressions.
3257       assert(isLambdaCallOperator(Frame->Callee) &&
3258              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3259              "missing value for local variable");
3260       if (Info.checkingPotentialConstantExpression())
3261         return false;
3262       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3263       // still reachable at all?
3264       Info.FFDiag(E->getBeginLoc(),
3265                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3266           << "captures not currently allowed";
3267       return false;
3268     }
3269   }
3270 
3271   // If we're currently evaluating the initializer of this declaration, use that
3272   // in-flight value.
3273   if (Info.EvaluatingDecl == Base) {
3274     Result = Info.EvaluatingDeclValue;
3275     return true;
3276   }
3277 
3278   if (isa<ParmVarDecl>(VD)) {
3279     // Assume parameters of a potential constant expression are usable in
3280     // constant expressions.
3281     if (!Info.checkingPotentialConstantExpression() ||
3282         !Info.CurrentCall->Callee ||
3283         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3284       if (Info.getLangOpts().CPlusPlus11) {
3285         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3286             << VD;
3287         NoteLValueLocation(Info, Base);
3288       } else {
3289         Info.FFDiag(E);
3290       }
3291     }
3292     return false;
3293   }
3294 
3295   // Dig out the initializer, and use the declaration which it's attached to.
3296   // FIXME: We should eventually check whether the variable has a reachable
3297   // initializing declaration.
3298   const Expr *Init = VD->getAnyInitializer(VD);
3299   if (!Init) {
3300     // Don't diagnose during potential constant expression checking; an
3301     // initializer might be added later.
3302     if (!Info.checkingPotentialConstantExpression()) {
3303       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3304         << VD;
3305       NoteLValueLocation(Info, Base);
3306     }
3307     return false;
3308   }
3309 
3310   if (Init->isValueDependent()) {
3311     // The DeclRefExpr is not value-dependent, but the variable it refers to
3312     // has a value-dependent initializer. This should only happen in
3313     // constant-folding cases, where the variable is not actually of a suitable
3314     // type for use in a constant expression (otherwise the DeclRefExpr would
3315     // have been value-dependent too), so diagnose that.
3316     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3317     if (!Info.checkingPotentialConstantExpression()) {
3318       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3319                          ? diag::note_constexpr_ltor_non_constexpr
3320                          : diag::note_constexpr_ltor_non_integral, 1)
3321           << VD << VD->getType();
3322       NoteLValueLocation(Info, Base);
3323     }
3324     return false;
3325   }
3326 
3327   // Check that we can fold the initializer. In C++, we will have already done
3328   // this in the cases where it matters for conformance.
3329   if (!VD->evaluateValue()) {
3330     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3331     NoteLValueLocation(Info, Base);
3332     return false;
3333   }
3334 
3335   // Check that the variable is actually usable in constant expressions. For a
3336   // const integral variable or a reference, we might have a non-constant
3337   // initializer that we can nonetheless evaluate the initializer for. Such
3338   // variables are not usable in constant expressions. In C++98, the
3339   // initializer also syntactically needs to be an ICE.
3340   //
3341   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3342   // expressions here; doing so would regress diagnostics for things like
3343   // reading from a volatile constexpr variable.
3344   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3345        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3346       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3347        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3348     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3349     NoteLValueLocation(Info, Base);
3350   }
3351 
3352   // Never use the initializer of a weak variable, not even for constant
3353   // folding. We can't be sure that this is the definition that will be used.
3354   if (VD->isWeak()) {
3355     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3356     NoteLValueLocation(Info, Base);
3357     return false;
3358   }
3359 
3360   Result = VD->getEvaluatedValue();
3361   return true;
3362 }
3363 
3364 /// Get the base index of the given base class within an APValue representing
3365 /// the given derived class.
getBaseIndex(const CXXRecordDecl * Derived,const CXXRecordDecl * Base)3366 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3367                              const CXXRecordDecl *Base) {
3368   Base = Base->getCanonicalDecl();
3369   unsigned Index = 0;
3370   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3371          E = Derived->bases_end(); I != E; ++I, ++Index) {
3372     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3373       return Index;
3374   }
3375 
3376   llvm_unreachable("base class missing from derived class's bases list");
3377 }
3378 
3379 /// Extract the value of a character from a string literal.
extractStringLiteralCharacter(EvalInfo & Info,const Expr * Lit,uint64_t Index)3380 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3381                                             uint64_t Index) {
3382   assert(!isa<SourceLocExpr>(Lit) &&
3383          "SourceLocExpr should have already been converted to a StringLiteral");
3384 
3385   // FIXME: Support MakeStringConstant
3386   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3387     std::string Str;
3388     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3389     assert(Index <= Str.size() && "Index too large");
3390     return APSInt::getUnsigned(Str.c_str()[Index]);
3391   }
3392 
3393   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3394     Lit = PE->getFunctionName();
3395   const StringLiteral *S = cast<StringLiteral>(Lit);
3396   const ConstantArrayType *CAT =
3397       Info.Ctx.getAsConstantArrayType(S->getType());
3398   assert(CAT && "string literal isn't an array");
3399   QualType CharType = CAT->getElementType();
3400   assert(CharType->isIntegerType() && "unexpected character type");
3401 
3402   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3403                CharType->isUnsignedIntegerType());
3404   if (Index < S->getLength())
3405     Value = S->getCodeUnit(Index);
3406   return Value;
3407 }
3408 
3409 // Expand a string literal into an array of characters.
3410 //
3411 // FIXME: This is inefficient; we should probably introduce something similar
3412 // to the LLVM ConstantDataArray to make this cheaper.
expandStringLiteral(EvalInfo & Info,const StringLiteral * S,APValue & Result,QualType AllocType=QualType ())3413 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3414                                 APValue &Result,
3415                                 QualType AllocType = QualType()) {
3416   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3417       AllocType.isNull() ? S->getType() : AllocType);
3418   assert(CAT && "string literal isn't an array");
3419   QualType CharType = CAT->getElementType();
3420   assert(CharType->isIntegerType() && "unexpected character type");
3421 
3422   unsigned Elts = CAT->getSize().getZExtValue();
3423   Result = APValue(APValue::UninitArray(),
3424                    std::min(S->getLength(), Elts), Elts);
3425   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3426                CharType->isUnsignedIntegerType());
3427   if (Result.hasArrayFiller())
3428     Result.getArrayFiller() = APValue(Value);
3429   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3430     Value = S->getCodeUnit(I);
3431     Result.getArrayInitializedElt(I) = APValue(Value);
3432   }
3433 }
3434 
3435 // Expand an array so that it has more than Index filled elements.
expandArray(APValue & Array,unsigned Index)3436 static void expandArray(APValue &Array, unsigned Index) {
3437   unsigned Size = Array.getArraySize();
3438   assert(Index < Size);
3439 
3440   // Always at least double the number of elements for which we store a value.
3441   unsigned OldElts = Array.getArrayInitializedElts();
3442   unsigned NewElts = std::max(Index+1, OldElts * 2);
3443   NewElts = std::min(Size, std::max(NewElts, 8u));
3444 
3445   // Copy the data across.
3446   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3447   for (unsigned I = 0; I != OldElts; ++I)
3448     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3449   for (unsigned I = OldElts; I != NewElts; ++I)
3450     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3451   if (NewValue.hasArrayFiller())
3452     NewValue.getArrayFiller() = Array.getArrayFiller();
3453   Array.swap(NewValue);
3454 }
3455 
3456 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3457 /// conversion. If it's of class type, we may assume that the copy operation
3458 /// is trivial. Note that this is never true for a union type with fields
3459 /// (because the copy always "reads" the active member) and always true for
3460 /// a non-class type.
3461 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
isReadByLvalueToRvalueConversion(QualType T)3462 static bool isReadByLvalueToRvalueConversion(QualType T) {
3463   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3464   return !RD || isReadByLvalueToRvalueConversion(RD);
3465 }
isReadByLvalueToRvalueConversion(const CXXRecordDecl * RD)3466 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3467   // FIXME: A trivial copy of a union copies the object representation, even if
3468   // the union is empty.
3469   if (RD->isUnion())
3470     return !RD->field_empty();
3471   if (RD->isEmpty())
3472     return false;
3473 
3474   for (auto *Field : RD->fields())
3475     if (!Field->isUnnamedBitfield() &&
3476         isReadByLvalueToRvalueConversion(Field->getType()))
3477       return true;
3478 
3479   for (auto &BaseSpec : RD->bases())
3480     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3481       return true;
3482 
3483   return false;
3484 }
3485 
3486 /// Diagnose an attempt to read from any unreadable field within the specified
3487 /// type, which might be a class type.
diagnoseMutableFields(EvalInfo & Info,const Expr * E,AccessKinds AK,QualType T)3488 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3489                                   QualType T) {
3490   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3491   if (!RD)
3492     return false;
3493 
3494   if (!RD->hasMutableFields())
3495     return false;
3496 
3497   for (auto *Field : RD->fields()) {
3498     // If we're actually going to read this field in some way, then it can't
3499     // be mutable. If we're in a union, then assigning to a mutable field
3500     // (even an empty one) can change the active member, so that's not OK.
3501     // FIXME: Add core issue number for the union case.
3502     if (Field->isMutable() &&
3503         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3504       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3505       Info.Note(Field->getLocation(), diag::note_declared_at);
3506       return true;
3507     }
3508 
3509     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3510       return true;
3511   }
3512 
3513   for (auto &BaseSpec : RD->bases())
3514     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3515       return true;
3516 
3517   // All mutable fields were empty, and thus not actually read.
3518   return false;
3519 }
3520 
lifetimeStartedInEvaluation(EvalInfo & Info,APValue::LValueBase Base,bool MutableSubobject=false)3521 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3522                                         APValue::LValueBase Base,
3523                                         bool MutableSubobject = false) {
3524   // A temporary or transient heap allocation we created.
3525   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3526     return true;
3527 
3528   switch (Info.IsEvaluatingDecl) {
3529   case EvalInfo::EvaluatingDeclKind::None:
3530     return false;
3531 
3532   case EvalInfo::EvaluatingDeclKind::Ctor:
3533     // The variable whose initializer we're evaluating.
3534     if (Info.EvaluatingDecl == Base)
3535       return true;
3536 
3537     // A temporary lifetime-extended by the variable whose initializer we're
3538     // evaluating.
3539     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3540       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3541         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3542     return false;
3543 
3544   case EvalInfo::EvaluatingDeclKind::Dtor:
3545     // C++2a [expr.const]p6:
3546     //   [during constant destruction] the lifetime of a and its non-mutable
3547     //   subobjects (but not its mutable subobjects) [are] considered to start
3548     //   within e.
3549     if (MutableSubobject || Base != Info.EvaluatingDecl)
3550       return false;
3551     // FIXME: We can meaningfully extend this to cover non-const objects, but
3552     // we will need special handling: we should be able to access only
3553     // subobjects of such objects that are themselves declared const.
3554     QualType T = getType(Base);
3555     return T.isConstQualified() || T->isReferenceType();
3556   }
3557 
3558   llvm_unreachable("unknown evaluating decl kind");
3559 }
3560 
3561 namespace {
3562 /// A handle to a complete object (an object that is not a subobject of
3563 /// another object).
3564 struct CompleteObject {
3565   /// The identity of the object.
3566   APValue::LValueBase Base;
3567   /// The value of the complete object.
3568   APValue *Value;
3569   /// The type of the complete object.
3570   QualType Type;
3571 
CompleteObject__anond52d8a670a11::CompleteObject3572   CompleteObject() : Value(nullptr) {}
CompleteObject__anond52d8a670a11::CompleteObject3573   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3574       : Base(Base), Value(Value), Type(Type) {}
3575 
mayAccessMutableMembers__anond52d8a670a11::CompleteObject3576   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3577     // If this isn't a "real" access (eg, if it's just accessing the type
3578     // info), allow it. We assume the type doesn't change dynamically for
3579     // subobjects of constexpr objects (even though we'd hit UB here if it
3580     // did). FIXME: Is this right?
3581     if (!isAnyAccess(AK))
3582       return true;
3583 
3584     // In C++14 onwards, it is permitted to read a mutable member whose
3585     // lifetime began within the evaluation.
3586     // FIXME: Should we also allow this in C++11?
3587     if (!Info.getLangOpts().CPlusPlus14)
3588       return false;
3589     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3590   }
3591 
operator bool__anond52d8a670a11::CompleteObject3592   explicit operator bool() const { return !Type.isNull(); }
3593 };
3594 } // end anonymous namespace
3595 
getSubobjectType(QualType ObjType,QualType SubobjType,bool IsMutable=false)3596 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3597                                  bool IsMutable = false) {
3598   // C++ [basic.type.qualifier]p1:
3599   // - A const object is an object of type const T or a non-mutable subobject
3600   //   of a const object.
3601   if (ObjType.isConstQualified() && !IsMutable)
3602     SubobjType.addConst();
3603   // - A volatile object is an object of type const T or a subobject of a
3604   //   volatile object.
3605   if (ObjType.isVolatileQualified())
3606     SubobjType.addVolatile();
3607   return SubobjType;
3608 }
3609 
3610 /// Find the designated sub-object of an rvalue.
3611 template<typename SubobjectHandler>
3612 typename SubobjectHandler::result_type
findSubobject(EvalInfo & Info,const Expr * E,const CompleteObject & Obj,const SubobjectDesignator & Sub,SubobjectHandler & handler)3613 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3614               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3615   if (Sub.Invalid)
3616     // A diagnostic will have already been produced.
3617     return handler.failed();
3618   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3619     if (Info.getLangOpts().CPlusPlus11)
3620       Info.FFDiag(E, Sub.isOnePastTheEnd()
3621                          ? diag::note_constexpr_access_past_end
3622                          : diag::note_constexpr_access_unsized_array)
3623           << handler.AccessKind;
3624     else
3625       Info.FFDiag(E);
3626     return handler.failed();
3627   }
3628 
3629   APValue *O = Obj.Value;
3630   QualType ObjType = Obj.Type;
3631   const FieldDecl *LastField = nullptr;
3632   const FieldDecl *VolatileField = nullptr;
3633 
3634   // Walk the designator's path to find the subobject.
3635   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3636     // Reading an indeterminate value is undefined, but assigning over one is OK.
3637     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3638         (O->isIndeterminate() &&
3639          !isValidIndeterminateAccess(handler.AccessKind))) {
3640       if (!Info.checkingPotentialConstantExpression())
3641         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3642             << handler.AccessKind << O->isIndeterminate();
3643       return handler.failed();
3644     }
3645 
3646     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3647     //    const and volatile semantics are not applied on an object under
3648     //    {con,de}struction.
3649     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3650         ObjType->isRecordType() &&
3651         Info.isEvaluatingCtorDtor(
3652             Obj.Base,
3653             llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3654             ConstructionPhase::None) {
3655       ObjType = Info.Ctx.getCanonicalType(ObjType);
3656       ObjType.removeLocalConst();
3657       ObjType.removeLocalVolatile();
3658     }
3659 
3660     // If this is our last pass, check that the final object type is OK.
3661     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3662       // Accesses to volatile objects are prohibited.
3663       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3664         if (Info.getLangOpts().CPlusPlus) {
3665           int DiagKind;
3666           SourceLocation Loc;
3667           const NamedDecl *Decl = nullptr;
3668           if (VolatileField) {
3669             DiagKind = 2;
3670             Loc = VolatileField->getLocation();
3671             Decl = VolatileField;
3672           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3673             DiagKind = 1;
3674             Loc = VD->getLocation();
3675             Decl = VD;
3676           } else {
3677             DiagKind = 0;
3678             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3679               Loc = E->getExprLoc();
3680           }
3681           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3682               << handler.AccessKind << DiagKind << Decl;
3683           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3684         } else {
3685           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3686         }
3687         return handler.failed();
3688       }
3689 
3690       // If we are reading an object of class type, there may still be more
3691       // things we need to check: if there are any mutable subobjects, we
3692       // cannot perform this read. (This only happens when performing a trivial
3693       // copy or assignment.)
3694       if (ObjType->isRecordType() &&
3695           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3696           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3697         return handler.failed();
3698     }
3699 
3700     if (I == N) {
3701       if (!handler.found(*O, ObjType))
3702         return false;
3703 
3704       // If we modified a bit-field, truncate it to the right width.
3705       if (isModification(handler.AccessKind) &&
3706           LastField && LastField->isBitField() &&
3707           !truncateBitfieldValue(Info, E, *O, LastField))
3708         return false;
3709 
3710       return true;
3711     }
3712 
3713     LastField = nullptr;
3714     if (ObjType->isArrayType()) {
3715       // Next subobject is an array element.
3716       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3717       assert(CAT && "vla in literal type?");
3718       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3719       if (CAT->getSize().ule(Index)) {
3720         // Note, it should not be possible to form a pointer with a valid
3721         // designator which points more than one past the end of the array.
3722         if (Info.getLangOpts().CPlusPlus11)
3723           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3724             << handler.AccessKind;
3725         else
3726           Info.FFDiag(E);
3727         return handler.failed();
3728       }
3729 
3730       ObjType = CAT->getElementType();
3731 
3732       if (O->getArrayInitializedElts() > Index)
3733         O = &O->getArrayInitializedElt(Index);
3734       else if (!isRead(handler.AccessKind)) {
3735         expandArray(*O, Index);
3736         O = &O->getArrayInitializedElt(Index);
3737       } else
3738         O = &O->getArrayFiller();
3739     } else if (ObjType->isAnyComplexType()) {
3740       // Next subobject is a complex number.
3741       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3742       if (Index > 1) {
3743         if (Info.getLangOpts().CPlusPlus11)
3744           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3745             << handler.AccessKind;
3746         else
3747           Info.FFDiag(E);
3748         return handler.failed();
3749       }
3750 
3751       ObjType = getSubobjectType(
3752           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3753 
3754       assert(I == N - 1 && "extracting subobject of scalar?");
3755       if (O->isComplexInt()) {
3756         return handler.found(Index ? O->getComplexIntImag()
3757                                    : O->getComplexIntReal(), ObjType);
3758       } else {
3759         assert(O->isComplexFloat());
3760         return handler.found(Index ? O->getComplexFloatImag()
3761                                    : O->getComplexFloatReal(), ObjType);
3762       }
3763     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3764       if (Field->isMutable() &&
3765           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3766         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3767           << handler.AccessKind << Field;
3768         Info.Note(Field->getLocation(), diag::note_declared_at);
3769         return handler.failed();
3770       }
3771 
3772       // Next subobject is a class, struct or union field.
3773       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3774       if (RD->isUnion()) {
3775         const FieldDecl *UnionField = O->getUnionField();
3776         if (!UnionField ||
3777             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3778           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3779             // Placement new onto an inactive union member makes it active.
3780             O->setUnion(Field, APValue());
3781           } else {
3782             // FIXME: If O->getUnionValue() is absent, report that there's no
3783             // active union member rather than reporting the prior active union
3784             // member. We'll need to fix nullptr_t to not use APValue() as its
3785             // representation first.
3786             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3787                 << handler.AccessKind << Field << !UnionField << UnionField;
3788             return handler.failed();
3789           }
3790         }
3791         O = &O->getUnionValue();
3792       } else
3793         O = &O->getStructField(Field->getFieldIndex());
3794 
3795       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3796       LastField = Field;
3797       if (Field->getType().isVolatileQualified())
3798         VolatileField = Field;
3799     } else {
3800       // Next subobject is a base class.
3801       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3802       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3803       O = &O->getStructBase(getBaseIndex(Derived, Base));
3804 
3805       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3806     }
3807   }
3808 }
3809 
3810 namespace {
3811 struct ExtractSubobjectHandler {
3812   EvalInfo &Info;
3813   const Expr *E;
3814   APValue &Result;
3815   const AccessKinds AccessKind;
3816 
3817   typedef bool result_type;
failed__anond52d8a670b11::ExtractSubobjectHandler3818   bool failed() { return false; }
found__anond52d8a670b11::ExtractSubobjectHandler3819   bool found(APValue &Subobj, QualType SubobjType) {
3820     Result = Subobj;
3821     if (AccessKind == AK_ReadObjectRepresentation)
3822       return true;
3823     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3824   }
found__anond52d8a670b11::ExtractSubobjectHandler3825   bool found(APSInt &Value, QualType SubobjType) {
3826     Result = APValue(Value);
3827     return true;
3828   }
found__anond52d8a670b11::ExtractSubobjectHandler3829   bool found(APFloat &Value, QualType SubobjType) {
3830     Result = APValue(Value);
3831     return true;
3832   }
3833 };
3834 } // end anonymous namespace
3835 
3836 /// 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)3837 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3838                              const CompleteObject &Obj,
3839                              const SubobjectDesignator &Sub, APValue &Result,
3840                              AccessKinds AK = AK_Read) {
3841   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3842   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3843   return findSubobject(Info, E, Obj, Sub, Handler);
3844 }
3845 
3846 namespace {
3847 struct ModifySubobjectHandler {
3848   EvalInfo &Info;
3849   APValue &NewVal;
3850   const Expr *E;
3851 
3852   typedef bool result_type;
3853   static const AccessKinds AccessKind = AK_Assign;
3854 
checkConst__anond52d8a670c11::ModifySubobjectHandler3855   bool checkConst(QualType QT) {
3856     // Assigning to a const object has undefined behavior.
3857     if (QT.isConstQualified()) {
3858       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3859       return false;
3860     }
3861     return true;
3862   }
3863 
failed__anond52d8a670c11::ModifySubobjectHandler3864   bool failed() { return false; }
found__anond52d8a670c11::ModifySubobjectHandler3865   bool found(APValue &Subobj, QualType SubobjType) {
3866     if (!checkConst(SubobjType))
3867       return false;
3868     // We've been given ownership of NewVal, so just swap it in.
3869     Subobj.swap(NewVal);
3870     return true;
3871   }
found__anond52d8a670c11::ModifySubobjectHandler3872   bool found(APSInt &Value, QualType SubobjType) {
3873     if (!checkConst(SubobjType))
3874       return false;
3875     if (!NewVal.isInt()) {
3876       // Maybe trying to write a cast pointer value into a complex?
3877       Info.FFDiag(E);
3878       return false;
3879     }
3880     Value = NewVal.getInt();
3881     return true;
3882   }
found__anond52d8a670c11::ModifySubobjectHandler3883   bool found(APFloat &Value, QualType SubobjType) {
3884     if (!checkConst(SubobjType))
3885       return false;
3886     Value = NewVal.getFloat();
3887     return true;
3888   }
3889 };
3890 } // end anonymous namespace
3891 
3892 const AccessKinds ModifySubobjectHandler::AccessKind;
3893 
3894 /// 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)3895 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3896                             const CompleteObject &Obj,
3897                             const SubobjectDesignator &Sub,
3898                             APValue &NewVal) {
3899   ModifySubobjectHandler Handler = { Info, NewVal, E };
3900   return findSubobject(Info, E, Obj, Sub, Handler);
3901 }
3902 
3903 /// Find the position where two subobject designators diverge, or equivalently
3904 /// the length of the common initial subsequence.
FindDesignatorMismatch(QualType ObjType,const SubobjectDesignator & A,const SubobjectDesignator & B,bool & WasArrayIndex)3905 static unsigned FindDesignatorMismatch(QualType ObjType,
3906                                        const SubobjectDesignator &A,
3907                                        const SubobjectDesignator &B,
3908                                        bool &WasArrayIndex) {
3909   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3910   for (/**/; I != N; ++I) {
3911     if (!ObjType.isNull() &&
3912         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3913       // Next subobject is an array element.
3914       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3915         WasArrayIndex = true;
3916         return I;
3917       }
3918       if (ObjType->isAnyComplexType())
3919         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3920       else
3921         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3922     } else {
3923       if (A.Entries[I].getAsBaseOrMember() !=
3924           B.Entries[I].getAsBaseOrMember()) {
3925         WasArrayIndex = false;
3926         return I;
3927       }
3928       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3929         // Next subobject is a field.
3930         ObjType = FD->getType();
3931       else
3932         // Next subobject is a base class.
3933         ObjType = QualType();
3934     }
3935   }
3936   WasArrayIndex = false;
3937   return I;
3938 }
3939 
3940 /// Determine whether the given subobject designators refer to elements of the
3941 /// same array object.
AreElementsOfSameArray(QualType ObjType,const SubobjectDesignator & A,const SubobjectDesignator & B)3942 static bool AreElementsOfSameArray(QualType ObjType,
3943                                    const SubobjectDesignator &A,
3944                                    const SubobjectDesignator &B) {
3945   if (A.Entries.size() != B.Entries.size())
3946     return false;
3947 
3948   bool IsArray = A.MostDerivedIsArrayElement;
3949   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3950     // A is a subobject of the array element.
3951     return false;
3952 
3953   // If A (and B) designates an array element, the last entry will be the array
3954   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3955   // of length 1' case, and the entire path must match.
3956   bool WasArrayIndex;
3957   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3958   return CommonLength >= A.Entries.size() - IsArray;
3959 }
3960 
3961 /// Find the complete object to which an LValue refers.
findCompleteObject(EvalInfo & Info,const Expr * E,AccessKinds AK,const LValue & LVal,QualType LValType)3962 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3963                                          AccessKinds AK, const LValue &LVal,
3964                                          QualType LValType) {
3965   if (LVal.InvalidBase) {
3966     Info.FFDiag(E);
3967     return CompleteObject();
3968   }
3969 
3970   if (!LVal.Base) {
3971     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3972     return CompleteObject();
3973   }
3974 
3975   CallStackFrame *Frame = nullptr;
3976   unsigned Depth = 0;
3977   if (LVal.getLValueCallIndex()) {
3978     std::tie(Frame, Depth) =
3979         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3980     if (!Frame) {
3981       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3982         << AK << LVal.Base.is<const ValueDecl*>();
3983       NoteLValueLocation(Info, LVal.Base);
3984       return CompleteObject();
3985     }
3986   }
3987 
3988   bool IsAccess = isAnyAccess(AK);
3989 
3990   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3991   // is not a constant expression (even if the object is non-volatile). We also
3992   // apply this rule to C++98, in order to conform to the expected 'volatile'
3993   // semantics.
3994   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3995     if (Info.getLangOpts().CPlusPlus)
3996       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3997         << AK << LValType;
3998     else
3999       Info.FFDiag(E);
4000     return CompleteObject();
4001   }
4002 
4003   // Compute value storage location and type of base object.
4004   APValue *BaseVal = nullptr;
4005   QualType BaseType = getType(LVal.Base);
4006 
4007   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4008       lifetimeStartedInEvaluation(Info, LVal.Base)) {
4009     // This is the object whose initializer we're evaluating, so its lifetime
4010     // started in the current evaluation.
4011     BaseVal = Info.EvaluatingDeclValue;
4012   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4013     // Allow reading from a GUID declaration.
4014     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4015       if (isModification(AK)) {
4016         // All the remaining cases do not permit modification of the object.
4017         Info.FFDiag(E, diag::note_constexpr_modify_global);
4018         return CompleteObject();
4019       }
4020       APValue &V = GD->getAsAPValue();
4021       if (V.isAbsent()) {
4022         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4023             << GD->getType();
4024         return CompleteObject();
4025       }
4026       return CompleteObject(LVal.Base, &V, GD->getType());
4027     }
4028 
4029     // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4030     if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4031       if (isModification(AK)) {
4032         Info.FFDiag(E, diag::note_constexpr_modify_global);
4033         return CompleteObject();
4034       }
4035       return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4036                             GCD->getType());
4037     }
4038 
4039     // Allow reading from template parameter objects.
4040     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4041       if (isModification(AK)) {
4042         Info.FFDiag(E, diag::note_constexpr_modify_global);
4043         return CompleteObject();
4044       }
4045       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4046                             TPO->getType());
4047     }
4048 
4049     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4050     // In C++11, constexpr, non-volatile variables initialized with constant
4051     // expressions are constant expressions too. Inside constexpr functions,
4052     // parameters are constant expressions even if they're non-const.
4053     // In C++1y, objects local to a constant expression (those with a Frame) are
4054     // both readable and writable inside constant expressions.
4055     // In C, such things can also be folded, although they are not ICEs.
4056     const VarDecl *VD = dyn_cast<VarDecl>(D);
4057     if (VD) {
4058       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4059         VD = VDef;
4060     }
4061     if (!VD || VD->isInvalidDecl()) {
4062       Info.FFDiag(E);
4063       return CompleteObject();
4064     }
4065 
4066     bool IsConstant = BaseType.isConstant(Info.Ctx);
4067 
4068     // Unless we're looking at a local variable or argument in a constexpr call,
4069     // the variable we're reading must be const.
4070     if (!Frame) {
4071       if (IsAccess && isa<ParmVarDecl>(VD)) {
4072         // Access of a parameter that's not associated with a frame isn't going
4073         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4074         // suitable diagnostic.
4075       } else if (Info.getLangOpts().CPlusPlus14 &&
4076                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4077         // OK, we can read and modify an object if we're in the process of
4078         // evaluating its initializer, because its lifetime began in this
4079         // evaluation.
4080       } else if (isModification(AK)) {
4081         // All the remaining cases do not permit modification of the object.
4082         Info.FFDiag(E, diag::note_constexpr_modify_global);
4083         return CompleteObject();
4084       } else if (VD->isConstexpr()) {
4085         // OK, we can read this variable.
4086       } else if (BaseType->isIntegralOrEnumerationType()) {
4087         if (!IsConstant) {
4088           if (!IsAccess)
4089             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4090           if (Info.getLangOpts().CPlusPlus) {
4091             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4092             Info.Note(VD->getLocation(), diag::note_declared_at);
4093           } else {
4094             Info.FFDiag(E);
4095           }
4096           return CompleteObject();
4097         }
4098       } else if (!IsAccess) {
4099         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4100       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4101                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4102         // This variable might end up being constexpr. Don't diagnose it yet.
4103       } else if (IsConstant) {
4104         // Keep evaluating to see what we can do. In particular, we support
4105         // folding of const floating-point types, in order to make static const
4106         // data members of such types (supported as an extension) more useful.
4107         if (Info.getLangOpts().CPlusPlus) {
4108           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4109                               ? diag::note_constexpr_ltor_non_constexpr
4110                               : diag::note_constexpr_ltor_non_integral, 1)
4111               << VD << BaseType;
4112           Info.Note(VD->getLocation(), diag::note_declared_at);
4113         } else {
4114           Info.CCEDiag(E);
4115         }
4116       } else {
4117         // Never allow reading a non-const value.
4118         if (Info.getLangOpts().CPlusPlus) {
4119           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4120                              ? diag::note_constexpr_ltor_non_constexpr
4121                              : diag::note_constexpr_ltor_non_integral, 1)
4122               << VD << BaseType;
4123           Info.Note(VD->getLocation(), diag::note_declared_at);
4124         } else {
4125           Info.FFDiag(E);
4126         }
4127         return CompleteObject();
4128       }
4129     }
4130 
4131     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4132       return CompleteObject();
4133   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4134     std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4135     if (!Alloc) {
4136       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4137       return CompleteObject();
4138     }
4139     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4140                           LVal.Base.getDynamicAllocType());
4141   } else {
4142     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4143 
4144     if (!Frame) {
4145       if (const MaterializeTemporaryExpr *MTE =
4146               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4147         assert(MTE->getStorageDuration() == SD_Static &&
4148                "should have a frame for a non-global materialized temporary");
4149 
4150         // C++20 [expr.const]p4: [DR2126]
4151         //   An object or reference is usable in constant expressions if it is
4152         //   - a temporary object of non-volatile const-qualified literal type
4153         //     whose lifetime is extended to that of a variable that is usable
4154         //     in constant expressions
4155         //
4156         // C++20 [expr.const]p5:
4157         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4158         //   - a non-volatile glvalue that refers to an object that is usable
4159         //     in constant expressions, or
4160         //   - a non-volatile glvalue of literal type that refers to a
4161         //     non-volatile object whose lifetime began within the evaluation
4162         //     of E;
4163         //
4164         // C++11 misses the 'began within the evaluation of e' check and
4165         // instead allows all temporaries, including things like:
4166         //   int &&r = 1;
4167         //   int x = ++r;
4168         //   constexpr int k = r;
4169         // Therefore we use the C++14-onwards rules in C++11 too.
4170         //
4171         // Note that temporaries whose lifetimes began while evaluating a
4172         // variable's constructor are not usable while evaluating the
4173         // corresponding destructor, not even if they're of const-qualified
4174         // types.
4175         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4176             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4177           if (!IsAccess)
4178             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4179           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4180           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4181           return CompleteObject();
4182         }
4183 
4184         BaseVal = MTE->getOrCreateValue(false);
4185         assert(BaseVal && "got reference to unevaluated temporary");
4186       } else {
4187         if (!IsAccess)
4188           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4189         APValue Val;
4190         LVal.moveInto(Val);
4191         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4192             << AK
4193             << Val.getAsString(Info.Ctx,
4194                                Info.Ctx.getLValueReferenceType(LValType));
4195         NoteLValueLocation(Info, LVal.Base);
4196         return CompleteObject();
4197       }
4198     } else {
4199       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4200       assert(BaseVal && "missing value for temporary");
4201     }
4202   }
4203 
4204   // In C++14, we can't safely access any mutable state when we might be
4205   // evaluating after an unmodeled side effect. Parameters are modeled as state
4206   // in the caller, but aren't visible once the call returns, so they can be
4207   // modified in a speculatively-evaluated call.
4208   //
4209   // FIXME: Not all local state is mutable. Allow local constant subobjects
4210   // to be read here (but take care with 'mutable' fields).
4211   unsigned VisibleDepth = Depth;
4212   if (llvm::isa_and_nonnull<ParmVarDecl>(
4213           LVal.Base.dyn_cast<const ValueDecl *>()))
4214     ++VisibleDepth;
4215   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4216        Info.EvalStatus.HasSideEffects) ||
4217       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4218     return CompleteObject();
4219 
4220   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4221 }
4222 
4223 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4224 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4225 /// glvalue referred to by an entity of reference type.
4226 ///
4227 /// \param Info - Information about the ongoing evaluation.
4228 /// \param Conv - The expression for which we are performing the conversion.
4229 ///               Used for diagnostics.
4230 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4231 ///               case of a non-class type).
4232 /// \param LVal - The glvalue on which we are attempting to perform this action.
4233 /// \param RVal - The produced value will be placed here.
4234 /// \param WantObjectRepresentation - If true, we're looking for the object
4235 ///               representation rather than the value, and in particular,
4236 ///               there is no requirement that the result be fully initialized.
4237 static bool
handleLValueToRValueConversion(EvalInfo & Info,const Expr * Conv,QualType Type,const LValue & LVal,APValue & RVal,bool WantObjectRepresentation=false)4238 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4239                                const LValue &LVal, APValue &RVal,
4240                                bool WantObjectRepresentation = false) {
4241   if (LVal.Designator.Invalid)
4242     return false;
4243 
4244   // Check for special cases where there is no existing APValue to look at.
4245   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4246 
4247   AccessKinds AK =
4248       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4249 
4250   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4251     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4252       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4253       // initializer until now for such expressions. Such an expression can't be
4254       // an ICE in C, so this only matters for fold.
4255       if (Type.isVolatileQualified()) {
4256         Info.FFDiag(Conv);
4257         return false;
4258       }
4259 
4260       APValue Lit;
4261       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4262         return false;
4263 
4264       // According to GCC info page:
4265       //
4266       // 6.28 Compound Literals
4267       //
4268       // As an optimization, G++ sometimes gives array compound literals longer
4269       // lifetimes: when the array either appears outside a function or has a
4270       // const-qualified type. If foo and its initializer had elements of type
4271       // char *const rather than char *, or if foo were a global variable, the
4272       // array would have static storage duration. But it is probably safest
4273       // just to avoid the use of array compound literals in C++ code.
4274       //
4275       // Obey that rule by checking constness for converted array types.
4276 
4277       QualType CLETy = CLE->getType();
4278       if (CLETy->isArrayType() && !Type->isArrayType()) {
4279         if (!CLETy.isConstant(Info.Ctx)) {
4280           Info.FFDiag(Conv);
4281           Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4282           return false;
4283         }
4284       }
4285 
4286       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4287       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4288     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4289       // Special-case character extraction so we don't have to construct an
4290       // APValue for the whole string.
4291       assert(LVal.Designator.Entries.size() <= 1 &&
4292              "Can only read characters from string literals");
4293       if (LVal.Designator.Entries.empty()) {
4294         // Fail for now for LValue to RValue conversion of an array.
4295         // (This shouldn't show up in C/C++, but it could be triggered by a
4296         // weird EvaluateAsRValue call from a tool.)
4297         Info.FFDiag(Conv);
4298         return false;
4299       }
4300       if (LVal.Designator.isOnePastTheEnd()) {
4301         if (Info.getLangOpts().CPlusPlus11)
4302           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4303         else
4304           Info.FFDiag(Conv);
4305         return false;
4306       }
4307       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4308       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4309       return true;
4310     }
4311   }
4312 
4313   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4314   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4315 }
4316 
4317 /// Perform an assignment of Val to LVal. Takes ownership of Val.
handleAssignment(EvalInfo & Info,const Expr * E,const LValue & LVal,QualType LValType,APValue & Val)4318 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4319                              QualType LValType, APValue &Val) {
4320   if (LVal.Designator.Invalid)
4321     return false;
4322 
4323   if (!Info.getLangOpts().CPlusPlus14) {
4324     Info.FFDiag(E);
4325     return false;
4326   }
4327 
4328   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4329   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4330 }
4331 
4332 namespace {
4333 struct CompoundAssignSubobjectHandler {
4334   EvalInfo &Info;
4335   const CompoundAssignOperator *E;
4336   QualType PromotedLHSType;
4337   BinaryOperatorKind Opcode;
4338   const APValue &RHS;
4339 
4340   static const AccessKinds AccessKind = AK_Assign;
4341 
4342   typedef bool result_type;
4343 
checkConst__anond52d8a670d11::CompoundAssignSubobjectHandler4344   bool checkConst(QualType QT) {
4345     // Assigning to a const object has undefined behavior.
4346     if (QT.isConstQualified()) {
4347       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4348       return false;
4349     }
4350     return true;
4351   }
4352 
failed__anond52d8a670d11::CompoundAssignSubobjectHandler4353   bool failed() { return false; }
found__anond52d8a670d11::CompoundAssignSubobjectHandler4354   bool found(APValue &Subobj, QualType SubobjType) {
4355     switch (Subobj.getKind()) {
4356     case APValue::Int:
4357       return found(Subobj.getInt(), SubobjType);
4358     case APValue::Float:
4359       return found(Subobj.getFloat(), SubobjType);
4360     case APValue::ComplexInt:
4361     case APValue::ComplexFloat:
4362       // FIXME: Implement complex compound assignment.
4363       Info.FFDiag(E);
4364       return false;
4365     case APValue::LValue:
4366       return foundPointer(Subobj, SubobjType);
4367     case APValue::Vector:
4368       return foundVector(Subobj, SubobjType);
4369     default:
4370       // FIXME: can this happen?
4371       Info.FFDiag(E);
4372       return false;
4373     }
4374   }
4375 
foundVector__anond52d8a670d11::CompoundAssignSubobjectHandler4376   bool foundVector(APValue &Value, QualType SubobjType) {
4377     if (!checkConst(SubobjType))
4378       return false;
4379 
4380     if (!SubobjType->isVectorType()) {
4381       Info.FFDiag(E);
4382       return false;
4383     }
4384     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4385   }
4386 
found__anond52d8a670d11::CompoundAssignSubobjectHandler4387   bool found(APSInt &Value, QualType SubobjType) {
4388     if (!checkConst(SubobjType))
4389       return false;
4390 
4391     if (!SubobjType->isIntegerType()) {
4392       // We don't support compound assignment on integer-cast-to-pointer
4393       // values.
4394       Info.FFDiag(E);
4395       return false;
4396     }
4397 
4398     if (RHS.isInt()) {
4399       APSInt LHS =
4400           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4401       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4402         return false;
4403       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4404       return true;
4405     } else if (RHS.isFloat()) {
4406       const FPOptions FPO = E->getFPFeaturesInEffect(
4407                                     Info.Ctx.getLangOpts());
4408       APFloat FValue(0.0);
4409       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4410                                   PromotedLHSType, FValue) &&
4411              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4412              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4413                                   Value);
4414     }
4415 
4416     Info.FFDiag(E);
4417     return false;
4418   }
found__anond52d8a670d11::CompoundAssignSubobjectHandler4419   bool found(APFloat &Value, QualType SubobjType) {
4420     return checkConst(SubobjType) &&
4421            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4422                                   Value) &&
4423            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4424            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4425   }
foundPointer__anond52d8a670d11::CompoundAssignSubobjectHandler4426   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4427     if (!checkConst(SubobjType))
4428       return false;
4429 
4430     QualType PointeeType;
4431     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4432       PointeeType = PT->getPointeeType();
4433 
4434     if (PointeeType.isNull() || !RHS.isInt() ||
4435         (Opcode != BO_Add && Opcode != BO_Sub)) {
4436       Info.FFDiag(E);
4437       return false;
4438     }
4439 
4440     APSInt Offset = RHS.getInt();
4441     if (Opcode == BO_Sub)
4442       negateAsSigned(Offset);
4443 
4444     LValue LVal;
4445     LVal.setFrom(Info.Ctx, Subobj);
4446     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4447       return false;
4448     LVal.moveInto(Subobj);
4449     return true;
4450   }
4451 };
4452 } // end anonymous namespace
4453 
4454 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4455 
4456 /// 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)4457 static bool handleCompoundAssignment(EvalInfo &Info,
4458                                      const CompoundAssignOperator *E,
4459                                      const LValue &LVal, QualType LValType,
4460                                      QualType PromotedLValType,
4461                                      BinaryOperatorKind Opcode,
4462                                      const APValue &RVal) {
4463   if (LVal.Designator.Invalid)
4464     return false;
4465 
4466   if (!Info.getLangOpts().CPlusPlus14) {
4467     Info.FFDiag(E);
4468     return false;
4469   }
4470 
4471   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4472   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4473                                              RVal };
4474   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4475 }
4476 
4477 namespace {
4478 struct IncDecSubobjectHandler {
4479   EvalInfo &Info;
4480   const UnaryOperator *E;
4481   AccessKinds AccessKind;
4482   APValue *Old;
4483 
4484   typedef bool result_type;
4485 
checkConst__anond52d8a670e11::IncDecSubobjectHandler4486   bool checkConst(QualType QT) {
4487     // Assigning to a const object has undefined behavior.
4488     if (QT.isConstQualified()) {
4489       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4490       return false;
4491     }
4492     return true;
4493   }
4494 
failed__anond52d8a670e11::IncDecSubobjectHandler4495   bool failed() { return false; }
found__anond52d8a670e11::IncDecSubobjectHandler4496   bool found(APValue &Subobj, QualType SubobjType) {
4497     // Stash the old value. Also clear Old, so we don't clobber it later
4498     // if we're post-incrementing a complex.
4499     if (Old) {
4500       *Old = Subobj;
4501       Old = nullptr;
4502     }
4503 
4504     switch (Subobj.getKind()) {
4505     case APValue::Int:
4506       return found(Subobj.getInt(), SubobjType);
4507     case APValue::Float:
4508       return found(Subobj.getFloat(), SubobjType);
4509     case APValue::ComplexInt:
4510       return found(Subobj.getComplexIntReal(),
4511                    SubobjType->castAs<ComplexType>()->getElementType()
4512                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4513     case APValue::ComplexFloat:
4514       return found(Subobj.getComplexFloatReal(),
4515                    SubobjType->castAs<ComplexType>()->getElementType()
4516                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4517     case APValue::LValue:
4518       return foundPointer(Subobj, SubobjType);
4519     default:
4520       // FIXME: can this happen?
4521       Info.FFDiag(E);
4522       return false;
4523     }
4524   }
found__anond52d8a670e11::IncDecSubobjectHandler4525   bool found(APSInt &Value, QualType SubobjType) {
4526     if (!checkConst(SubobjType))
4527       return false;
4528 
4529     if (!SubobjType->isIntegerType()) {
4530       // We don't support increment / decrement on integer-cast-to-pointer
4531       // values.
4532       Info.FFDiag(E);
4533       return false;
4534     }
4535 
4536     if (Old) *Old = APValue(Value);
4537 
4538     // bool arithmetic promotes to int, and the conversion back to bool
4539     // doesn't reduce mod 2^n, so special-case it.
4540     if (SubobjType->isBooleanType()) {
4541       if (AccessKind == AK_Increment)
4542         Value = 1;
4543       else
4544         Value = !Value;
4545       return true;
4546     }
4547 
4548     bool WasNegative = Value.isNegative();
4549     if (AccessKind == AK_Increment) {
4550       ++Value;
4551 
4552       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4553         APSInt ActualValue(Value, /*IsUnsigned*/true);
4554         return HandleOverflow(Info, E, ActualValue, SubobjType);
4555       }
4556     } else {
4557       --Value;
4558 
4559       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4560         unsigned BitWidth = Value.getBitWidth();
4561         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4562         ActualValue.setBit(BitWidth);
4563         return HandleOverflow(Info, E, ActualValue, SubobjType);
4564       }
4565     }
4566     return true;
4567   }
found__anond52d8a670e11::IncDecSubobjectHandler4568   bool found(APFloat &Value, QualType SubobjType) {
4569     if (!checkConst(SubobjType))
4570       return false;
4571 
4572     if (Old) *Old = APValue(Value);
4573 
4574     APFloat One(Value.getSemantics(), 1);
4575     if (AccessKind == AK_Increment)
4576       Value.add(One, APFloat::rmNearestTiesToEven);
4577     else
4578       Value.subtract(One, APFloat::rmNearestTiesToEven);
4579     return true;
4580   }
foundPointer__anond52d8a670e11::IncDecSubobjectHandler4581   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4582     if (!checkConst(SubobjType))
4583       return false;
4584 
4585     QualType PointeeType;
4586     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4587       PointeeType = PT->getPointeeType();
4588     else {
4589       Info.FFDiag(E);
4590       return false;
4591     }
4592 
4593     LValue LVal;
4594     LVal.setFrom(Info.Ctx, Subobj);
4595     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4596                                      AccessKind == AK_Increment ? 1 : -1))
4597       return false;
4598     LVal.moveInto(Subobj);
4599     return true;
4600   }
4601 };
4602 } // end anonymous namespace
4603 
4604 /// Perform an increment or decrement on LVal.
handleIncDec(EvalInfo & Info,const Expr * E,const LValue & LVal,QualType LValType,bool IsIncrement,APValue * Old)4605 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4606                          QualType LValType, bool IsIncrement, APValue *Old) {
4607   if (LVal.Designator.Invalid)
4608     return false;
4609 
4610   if (!Info.getLangOpts().CPlusPlus14) {
4611     Info.FFDiag(E);
4612     return false;
4613   }
4614 
4615   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4616   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4617   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4618   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4619 }
4620 
4621 /// Build an lvalue for the object argument of a member function call.
EvaluateObjectArgument(EvalInfo & Info,const Expr * Object,LValue & This)4622 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4623                                    LValue &This) {
4624   if (Object->getType()->isPointerType() && Object->isPRValue())
4625     return EvaluatePointer(Object, This, Info);
4626 
4627   if (Object->isGLValue())
4628     return EvaluateLValue(Object, This, Info);
4629 
4630   if (Object->getType()->isLiteralType(Info.Ctx))
4631     return EvaluateTemporary(Object, This, Info);
4632 
4633   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4634   return false;
4635 }
4636 
4637 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4638 /// lvalue referring to the result.
4639 ///
4640 /// \param Info - Information about the ongoing evaluation.
4641 /// \param LV - An lvalue referring to the base of the member pointer.
4642 /// \param RHS - The member pointer expression.
4643 /// \param IncludeMember - Specifies whether the member itself is included in
4644 ///        the resulting LValue subobject designator. This is not possible when
4645 ///        creating a bound member function.
4646 /// \return The field or method declaration to which the member pointer refers,
4647 ///         or 0 if evaluation fails.
HandleMemberPointerAccess(EvalInfo & Info,QualType LVType,LValue & LV,const Expr * RHS,bool IncludeMember=true)4648 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4649                                                   QualType LVType,
4650                                                   LValue &LV,
4651                                                   const Expr *RHS,
4652                                                   bool IncludeMember = true) {
4653   MemberPtr MemPtr;
4654   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4655     return nullptr;
4656 
4657   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4658   // member value, the behavior is undefined.
4659   if (!MemPtr.getDecl()) {
4660     // FIXME: Specific diagnostic.
4661     Info.FFDiag(RHS);
4662     return nullptr;
4663   }
4664 
4665   if (MemPtr.isDerivedMember()) {
4666     // This is a member of some derived class. Truncate LV appropriately.
4667     // The end of the derived-to-base path for the base object must match the
4668     // derived-to-base path for the member pointer.
4669     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4670         LV.Designator.Entries.size()) {
4671       Info.FFDiag(RHS);
4672       return nullptr;
4673     }
4674     unsigned PathLengthToMember =
4675         LV.Designator.Entries.size() - MemPtr.Path.size();
4676     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4677       const CXXRecordDecl *LVDecl = getAsBaseClass(
4678           LV.Designator.Entries[PathLengthToMember + I]);
4679       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4680       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4681         Info.FFDiag(RHS);
4682         return nullptr;
4683       }
4684     }
4685 
4686     // Truncate the lvalue to the appropriate derived class.
4687     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4688                             PathLengthToMember))
4689       return nullptr;
4690   } else if (!MemPtr.Path.empty()) {
4691     // Extend the LValue path with the member pointer's path.
4692     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4693                                   MemPtr.Path.size() + IncludeMember);
4694 
4695     // Walk down to the appropriate base class.
4696     if (const PointerType *PT = LVType->getAs<PointerType>())
4697       LVType = PT->getPointeeType();
4698     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4699     assert(RD && "member pointer access on non-class-type expression");
4700     // The first class in the path is that of the lvalue.
4701     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4702       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4703       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4704         return nullptr;
4705       RD = Base;
4706     }
4707     // Finally cast to the class containing the member.
4708     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4709                                 MemPtr.getContainingRecord()))
4710       return nullptr;
4711   }
4712 
4713   // Add the member. Note that we cannot build bound member functions here.
4714   if (IncludeMember) {
4715     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4716       if (!HandleLValueMember(Info, RHS, LV, FD))
4717         return nullptr;
4718     } else if (const IndirectFieldDecl *IFD =
4719                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4720       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4721         return nullptr;
4722     } else {
4723       llvm_unreachable("can't construct reference to bound member function");
4724     }
4725   }
4726 
4727   return MemPtr.getDecl();
4728 }
4729 
HandleMemberPointerAccess(EvalInfo & Info,const BinaryOperator * BO,LValue & LV,bool IncludeMember=true)4730 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4731                                                   const BinaryOperator *BO,
4732                                                   LValue &LV,
4733                                                   bool IncludeMember = true) {
4734   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4735 
4736   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4737     if (Info.noteFailure()) {
4738       MemberPtr MemPtr;
4739       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4740     }
4741     return nullptr;
4742   }
4743 
4744   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4745                                    BO->getRHS(), IncludeMember);
4746 }
4747 
4748 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4749 /// the provided lvalue, which currently refers to the base object.
HandleBaseToDerivedCast(EvalInfo & Info,const CastExpr * E,LValue & Result)4750 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4751                                     LValue &Result) {
4752   SubobjectDesignator &D = Result.Designator;
4753   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4754     return false;
4755 
4756   QualType TargetQT = E->getType();
4757   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4758     TargetQT = PT->getPointeeType();
4759 
4760   // Check this cast lands within the final derived-to-base subobject path.
4761   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4762     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4763       << D.MostDerivedType << TargetQT;
4764     return false;
4765   }
4766 
4767   // Check the type of the final cast. We don't need to check the path,
4768   // since a cast can only be formed if the path is unique.
4769   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4770   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4771   const CXXRecordDecl *FinalType;
4772   if (NewEntriesSize == D.MostDerivedPathLength)
4773     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4774   else
4775     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4776   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4777     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4778       << D.MostDerivedType << TargetQT;
4779     return false;
4780   }
4781 
4782   // Truncate the lvalue to the appropriate derived class.
4783   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4784 }
4785 
4786 /// Get the value to use for a default-initialized object of type T.
4787 /// Return false if it encounters something invalid.
getDefaultInitValue(QualType T,APValue & Result)4788 static bool getDefaultInitValue(QualType T, APValue &Result) {
4789   bool Success = true;
4790   if (auto *RD = T->getAsCXXRecordDecl()) {
4791     if (RD->isInvalidDecl()) {
4792       Result = APValue();
4793       return false;
4794     }
4795     if (RD->isUnion()) {
4796       Result = APValue((const FieldDecl *)nullptr);
4797       return true;
4798     }
4799     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4800                      std::distance(RD->field_begin(), RD->field_end()));
4801 
4802     unsigned Index = 0;
4803     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4804                                                   End = RD->bases_end();
4805          I != End; ++I, ++Index)
4806       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4807 
4808     for (const auto *I : RD->fields()) {
4809       if (I->isUnnamedBitfield())
4810         continue;
4811       Success &= getDefaultInitValue(I->getType(),
4812                                      Result.getStructField(I->getFieldIndex()));
4813     }
4814     return Success;
4815   }
4816 
4817   if (auto *AT =
4818           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4819     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4820     if (Result.hasArrayFiller())
4821       Success &=
4822           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4823 
4824     return Success;
4825   }
4826 
4827   Result = APValue::IndeterminateValue();
4828   return true;
4829 }
4830 
4831 namespace {
4832 enum EvalStmtResult {
4833   /// Evaluation failed.
4834   ESR_Failed,
4835   /// Hit a 'return' statement.
4836   ESR_Returned,
4837   /// Evaluation succeeded.
4838   ESR_Succeeded,
4839   /// Hit a 'continue' statement.
4840   ESR_Continue,
4841   /// Hit a 'break' statement.
4842   ESR_Break,
4843   /// Still scanning for 'case' or 'default' statement.
4844   ESR_CaseNotFound
4845 };
4846 }
4847 
EvaluateVarDecl(EvalInfo & Info,const VarDecl * VD)4848 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4849   if (VD->isInvalidDecl())
4850     return false;
4851   // We don't need to evaluate the initializer for a static local.
4852   if (!VD->hasLocalStorage())
4853     return true;
4854 
4855   LValue Result;
4856   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4857                                                    ScopeKind::Block, Result);
4858 
4859   const Expr *InitE = VD->getInit();
4860   if (!InitE) {
4861     if (VD->getType()->isDependentType())
4862       return Info.noteSideEffect();
4863     return getDefaultInitValue(VD->getType(), Val);
4864   }
4865   if (InitE->isValueDependent())
4866     return false;
4867 
4868   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4869     // Wipe out any partially-computed value, to allow tracking that this
4870     // evaluation failed.
4871     Val = APValue();
4872     return false;
4873   }
4874 
4875   return true;
4876 }
4877 
EvaluateDecl(EvalInfo & Info,const Decl * D)4878 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4879   bool OK = true;
4880 
4881   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4882     OK &= EvaluateVarDecl(Info, VD);
4883 
4884   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4885     for (auto *BD : DD->bindings())
4886       if (auto *VD = BD->getHoldingVar())
4887         OK &= EvaluateDecl(Info, VD);
4888 
4889   return OK;
4890 }
4891 
EvaluateDependentExpr(const Expr * E,EvalInfo & Info)4892 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4893   assert(E->isValueDependent());
4894   if (Info.noteSideEffect())
4895     return true;
4896   assert(E->containsErrors() && "valid value-dependent expression should never "
4897                                 "reach invalid code path.");
4898   return false;
4899 }
4900 
4901 /// Evaluate a condition (either a variable declaration or an expression).
EvaluateCond(EvalInfo & Info,const VarDecl * CondDecl,const Expr * Cond,bool & Result)4902 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4903                          const Expr *Cond, bool &Result) {
4904   if (Cond->isValueDependent())
4905     return false;
4906   FullExpressionRAII Scope(Info);
4907   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4908     return false;
4909   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4910     return false;
4911   return Scope.destroy();
4912 }
4913 
4914 namespace {
4915 /// A location where the result (returned value) of evaluating a
4916 /// statement should be stored.
4917 struct StmtResult {
4918   /// The APValue that should be filled in with the returned value.
4919   APValue &Value;
4920   /// The location containing the result, if any (used to support RVO).
4921   const LValue *Slot;
4922 };
4923 
4924 struct TempVersionRAII {
4925   CallStackFrame &Frame;
4926 
TempVersionRAII__anond52d8a671011::TempVersionRAII4927   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4928     Frame.pushTempVersion();
4929   }
4930 
~TempVersionRAII__anond52d8a671011::TempVersionRAII4931   ~TempVersionRAII() {
4932     Frame.popTempVersion();
4933   }
4934 };
4935 
4936 }
4937 
4938 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4939                                    const Stmt *S,
4940                                    const SwitchCase *SC = nullptr);
4941 
4942 /// Evaluate the body of a loop, and translate the result as appropriate.
EvaluateLoopBody(StmtResult & Result,EvalInfo & Info,const Stmt * Body,const SwitchCase * Case=nullptr)4943 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4944                                        const Stmt *Body,
4945                                        const SwitchCase *Case = nullptr) {
4946   BlockScopeRAII Scope(Info);
4947 
4948   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4949   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4950     ESR = ESR_Failed;
4951 
4952   switch (ESR) {
4953   case ESR_Break:
4954     return ESR_Succeeded;
4955   case ESR_Succeeded:
4956   case ESR_Continue:
4957     return ESR_Continue;
4958   case ESR_Failed:
4959   case ESR_Returned:
4960   case ESR_CaseNotFound:
4961     return ESR;
4962   }
4963   llvm_unreachable("Invalid EvalStmtResult!");
4964 }
4965 
4966 /// Evaluate a switch statement.
EvaluateSwitch(StmtResult & Result,EvalInfo & Info,const SwitchStmt * SS)4967 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4968                                      const SwitchStmt *SS) {
4969   BlockScopeRAII Scope(Info);
4970 
4971   // Evaluate the switch condition.
4972   APSInt Value;
4973   {
4974     if (const Stmt *Init = SS->getInit()) {
4975       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4976       if (ESR != ESR_Succeeded) {
4977         if (ESR != ESR_Failed && !Scope.destroy())
4978           ESR = ESR_Failed;
4979         return ESR;
4980       }
4981     }
4982 
4983     FullExpressionRAII CondScope(Info);
4984     if (SS->getConditionVariable() &&
4985         !EvaluateDecl(Info, SS->getConditionVariable()))
4986       return ESR_Failed;
4987     if (SS->getCond()->isValueDependent()) {
4988       if (!EvaluateDependentExpr(SS->getCond(), Info))
4989         return ESR_Failed;
4990     } else {
4991       if (!EvaluateInteger(SS->getCond(), Value, Info))
4992         return ESR_Failed;
4993     }
4994     if (!CondScope.destroy())
4995       return ESR_Failed;
4996   }
4997 
4998   // Find the switch case corresponding to the value of the condition.
4999   // FIXME: Cache this lookup.
5000   const SwitchCase *Found = nullptr;
5001   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5002        SC = SC->getNextSwitchCase()) {
5003     if (isa<DefaultStmt>(SC)) {
5004       Found = SC;
5005       continue;
5006     }
5007 
5008     const CaseStmt *CS = cast<CaseStmt>(SC);
5009     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5010     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5011                               : LHS;
5012     if (LHS <= Value && Value <= RHS) {
5013       Found = SC;
5014       break;
5015     }
5016   }
5017 
5018   if (!Found)
5019     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5020 
5021   // Search the switch body for the switch case and evaluate it from there.
5022   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5023   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5024     return ESR_Failed;
5025 
5026   switch (ESR) {
5027   case ESR_Break:
5028     return ESR_Succeeded;
5029   case ESR_Succeeded:
5030   case ESR_Continue:
5031   case ESR_Failed:
5032   case ESR_Returned:
5033     return ESR;
5034   case ESR_CaseNotFound:
5035     // This can only happen if the switch case is nested within a statement
5036     // expression. We have no intention of supporting that.
5037     Info.FFDiag(Found->getBeginLoc(),
5038                 diag::note_constexpr_stmt_expr_unsupported);
5039     return ESR_Failed;
5040   }
5041   llvm_unreachable("Invalid EvalStmtResult!");
5042 }
5043 
CheckLocalVariableDeclaration(EvalInfo & Info,const VarDecl * VD)5044 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5045   // An expression E is a core constant expression unless the evaluation of E
5046   // would evaluate one of the following: [C++2b] - a control flow that passes
5047   // through a declaration of a variable with static or thread storage duration
5048   // unless that variable is usable in constant expressions.
5049   if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5050       !VD->isUsableInConstantExpressions(Info.Ctx)) {
5051     Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5052         << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5053     return false;
5054   }
5055   return true;
5056 }
5057 
5058 // Evaluate a statement.
EvaluateStmt(StmtResult & Result,EvalInfo & Info,const Stmt * S,const SwitchCase * Case)5059 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5060                                    const Stmt *S, const SwitchCase *Case) {
5061   if (!Info.nextStep(S))
5062     return ESR_Failed;
5063 
5064   // If we're hunting down a 'case' or 'default' label, recurse through
5065   // substatements until we hit the label.
5066   if (Case) {
5067     switch (S->getStmtClass()) {
5068     case Stmt::CompoundStmtClass:
5069       // FIXME: Precompute which substatement of a compound statement we
5070       // would jump to, and go straight there rather than performing a
5071       // linear scan each time.
5072     case Stmt::LabelStmtClass:
5073     case Stmt::AttributedStmtClass:
5074     case Stmt::DoStmtClass:
5075       break;
5076 
5077     case Stmt::CaseStmtClass:
5078     case Stmt::DefaultStmtClass:
5079       if (Case == S)
5080         Case = nullptr;
5081       break;
5082 
5083     case Stmt::IfStmtClass: {
5084       // FIXME: Precompute which side of an 'if' we would jump to, and go
5085       // straight there rather than scanning both sides.
5086       const IfStmt *IS = cast<IfStmt>(S);
5087 
5088       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5089       // preceded by our switch label.
5090       BlockScopeRAII Scope(Info);
5091 
5092       // Step into the init statement in case it brings an (uninitialized)
5093       // variable into scope.
5094       if (const Stmt *Init = IS->getInit()) {
5095         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5096         if (ESR != ESR_CaseNotFound) {
5097           assert(ESR != ESR_Succeeded);
5098           return ESR;
5099         }
5100       }
5101 
5102       // Condition variable must be initialized if it exists.
5103       // FIXME: We can skip evaluating the body if there's a condition
5104       // variable, as there can't be any case labels within it.
5105       // (The same is true for 'for' statements.)
5106 
5107       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5108       if (ESR == ESR_Failed)
5109         return ESR;
5110       if (ESR != ESR_CaseNotFound)
5111         return Scope.destroy() ? ESR : ESR_Failed;
5112       if (!IS->getElse())
5113         return ESR_CaseNotFound;
5114 
5115       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5116       if (ESR == ESR_Failed)
5117         return ESR;
5118       if (ESR != ESR_CaseNotFound)
5119         return Scope.destroy() ? ESR : ESR_Failed;
5120       return ESR_CaseNotFound;
5121     }
5122 
5123     case Stmt::WhileStmtClass: {
5124       EvalStmtResult ESR =
5125           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5126       if (ESR != ESR_Continue)
5127         return ESR;
5128       break;
5129     }
5130 
5131     case Stmt::ForStmtClass: {
5132       const ForStmt *FS = cast<ForStmt>(S);
5133       BlockScopeRAII Scope(Info);
5134 
5135       // Step into the init statement in case it brings an (uninitialized)
5136       // variable into scope.
5137       if (const Stmt *Init = FS->getInit()) {
5138         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5139         if (ESR != ESR_CaseNotFound) {
5140           assert(ESR != ESR_Succeeded);
5141           return ESR;
5142         }
5143       }
5144 
5145       EvalStmtResult ESR =
5146           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5147       if (ESR != ESR_Continue)
5148         return ESR;
5149       if (const auto *Inc = FS->getInc()) {
5150         if (Inc->isValueDependent()) {
5151           if (!EvaluateDependentExpr(Inc, Info))
5152             return ESR_Failed;
5153         } else {
5154           FullExpressionRAII IncScope(Info);
5155           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5156             return ESR_Failed;
5157         }
5158       }
5159       break;
5160     }
5161 
5162     case Stmt::DeclStmtClass: {
5163       // Start the lifetime of any uninitialized variables we encounter. They
5164       // might be used by the selected branch of the switch.
5165       const DeclStmt *DS = cast<DeclStmt>(S);
5166       for (const auto *D : DS->decls()) {
5167         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5168           if (!CheckLocalVariableDeclaration(Info, VD))
5169             return ESR_Failed;
5170           if (VD->hasLocalStorage() && !VD->getInit())
5171             if (!EvaluateVarDecl(Info, VD))
5172               return ESR_Failed;
5173           // FIXME: If the variable has initialization that can't be jumped
5174           // over, bail out of any immediately-surrounding compound-statement
5175           // too. There can't be any case labels here.
5176         }
5177       }
5178       return ESR_CaseNotFound;
5179     }
5180 
5181     default:
5182       return ESR_CaseNotFound;
5183     }
5184   }
5185 
5186   switch (S->getStmtClass()) {
5187   default:
5188     if (const Expr *E = dyn_cast<Expr>(S)) {
5189       if (E->isValueDependent()) {
5190         if (!EvaluateDependentExpr(E, Info))
5191           return ESR_Failed;
5192       } else {
5193         // Don't bother evaluating beyond an expression-statement which couldn't
5194         // be evaluated.
5195         // FIXME: Do we need the FullExpressionRAII object here?
5196         // VisitExprWithCleanups should create one when necessary.
5197         FullExpressionRAII Scope(Info);
5198         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5199           return ESR_Failed;
5200       }
5201       return ESR_Succeeded;
5202     }
5203 
5204     Info.FFDiag(S->getBeginLoc());
5205     return ESR_Failed;
5206 
5207   case Stmt::NullStmtClass:
5208     return ESR_Succeeded;
5209 
5210   case Stmt::DeclStmtClass: {
5211     const DeclStmt *DS = cast<DeclStmt>(S);
5212     for (const auto *D : DS->decls()) {
5213       const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5214       if (VD && !CheckLocalVariableDeclaration(Info, VD))
5215         return ESR_Failed;
5216       // Each declaration initialization is its own full-expression.
5217       FullExpressionRAII Scope(Info);
5218       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5219         return ESR_Failed;
5220       if (!Scope.destroy())
5221         return ESR_Failed;
5222     }
5223     return ESR_Succeeded;
5224   }
5225 
5226   case Stmt::ReturnStmtClass: {
5227     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5228     FullExpressionRAII Scope(Info);
5229     if (RetExpr && RetExpr->isValueDependent()) {
5230       EvaluateDependentExpr(RetExpr, Info);
5231       // We know we returned, but we don't know what the value is.
5232       return ESR_Failed;
5233     }
5234     if (RetExpr &&
5235         !(Result.Slot
5236               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5237               : Evaluate(Result.Value, Info, RetExpr)))
5238       return ESR_Failed;
5239     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5240   }
5241 
5242   case Stmt::CompoundStmtClass: {
5243     BlockScopeRAII Scope(Info);
5244 
5245     const CompoundStmt *CS = cast<CompoundStmt>(S);
5246     for (const auto *BI : CS->body()) {
5247       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5248       if (ESR == ESR_Succeeded)
5249         Case = nullptr;
5250       else if (ESR != ESR_CaseNotFound) {
5251         if (ESR != ESR_Failed && !Scope.destroy())
5252           return ESR_Failed;
5253         return ESR;
5254       }
5255     }
5256     if (Case)
5257       return ESR_CaseNotFound;
5258     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5259   }
5260 
5261   case Stmt::IfStmtClass: {
5262     const IfStmt *IS = cast<IfStmt>(S);
5263 
5264     // Evaluate the condition, as either a var decl or as an expression.
5265     BlockScopeRAII Scope(Info);
5266     if (const Stmt *Init = IS->getInit()) {
5267       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5268       if (ESR != ESR_Succeeded) {
5269         if (ESR != ESR_Failed && !Scope.destroy())
5270           return ESR_Failed;
5271         return ESR;
5272       }
5273     }
5274     bool Cond;
5275     if (IS->isConsteval()) {
5276       Cond = IS->isNonNegatedConsteval();
5277       // If we are not in a constant context, if consteval should not evaluate
5278       // to true.
5279       if (!Info.InConstantContext)
5280         Cond = !Cond;
5281     } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5282                              Cond))
5283       return ESR_Failed;
5284 
5285     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5286       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5287       if (ESR != ESR_Succeeded) {
5288         if (ESR != ESR_Failed && !Scope.destroy())
5289           return ESR_Failed;
5290         return ESR;
5291       }
5292     }
5293     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5294   }
5295 
5296   case Stmt::WhileStmtClass: {
5297     const WhileStmt *WS = cast<WhileStmt>(S);
5298     while (true) {
5299       BlockScopeRAII Scope(Info);
5300       bool Continue;
5301       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5302                         Continue))
5303         return ESR_Failed;
5304       if (!Continue)
5305         break;
5306 
5307       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5308       if (ESR != ESR_Continue) {
5309         if (ESR != ESR_Failed && !Scope.destroy())
5310           return ESR_Failed;
5311         return ESR;
5312       }
5313       if (!Scope.destroy())
5314         return ESR_Failed;
5315     }
5316     return ESR_Succeeded;
5317   }
5318 
5319   case Stmt::DoStmtClass: {
5320     const DoStmt *DS = cast<DoStmt>(S);
5321     bool Continue;
5322     do {
5323       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5324       if (ESR != ESR_Continue)
5325         return ESR;
5326       Case = nullptr;
5327 
5328       if (DS->getCond()->isValueDependent()) {
5329         EvaluateDependentExpr(DS->getCond(), Info);
5330         // Bailout as we don't know whether to keep going or terminate the loop.
5331         return ESR_Failed;
5332       }
5333       FullExpressionRAII CondScope(Info);
5334       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5335           !CondScope.destroy())
5336         return ESR_Failed;
5337     } while (Continue);
5338     return ESR_Succeeded;
5339   }
5340 
5341   case Stmt::ForStmtClass: {
5342     const ForStmt *FS = cast<ForStmt>(S);
5343     BlockScopeRAII ForScope(Info);
5344     if (FS->getInit()) {
5345       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5346       if (ESR != ESR_Succeeded) {
5347         if (ESR != ESR_Failed && !ForScope.destroy())
5348           return ESR_Failed;
5349         return ESR;
5350       }
5351     }
5352     while (true) {
5353       BlockScopeRAII IterScope(Info);
5354       bool Continue = true;
5355       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5356                                          FS->getCond(), Continue))
5357         return ESR_Failed;
5358       if (!Continue)
5359         break;
5360 
5361       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5362       if (ESR != ESR_Continue) {
5363         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5364           return ESR_Failed;
5365         return ESR;
5366       }
5367 
5368       if (const auto *Inc = FS->getInc()) {
5369         if (Inc->isValueDependent()) {
5370           if (!EvaluateDependentExpr(Inc, Info))
5371             return ESR_Failed;
5372         } else {
5373           FullExpressionRAII IncScope(Info);
5374           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5375             return ESR_Failed;
5376         }
5377       }
5378 
5379       if (!IterScope.destroy())
5380         return ESR_Failed;
5381     }
5382     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5383   }
5384 
5385   case Stmt::CXXForRangeStmtClass: {
5386     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5387     BlockScopeRAII Scope(Info);
5388 
5389     // Evaluate the init-statement if present.
5390     if (FS->getInit()) {
5391       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5392       if (ESR != ESR_Succeeded) {
5393         if (ESR != ESR_Failed && !Scope.destroy())
5394           return ESR_Failed;
5395         return ESR;
5396       }
5397     }
5398 
5399     // Initialize the __range variable.
5400     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5401     if (ESR != ESR_Succeeded) {
5402       if (ESR != ESR_Failed && !Scope.destroy())
5403         return ESR_Failed;
5404       return ESR;
5405     }
5406 
5407     // In error-recovery cases it's possible to get here even if we failed to
5408     // synthesize the __begin and __end variables.
5409     if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5410       return ESR_Failed;
5411 
5412     // Create the __begin and __end iterators.
5413     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5414     if (ESR != ESR_Succeeded) {
5415       if (ESR != ESR_Failed && !Scope.destroy())
5416         return ESR_Failed;
5417       return ESR;
5418     }
5419     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5420     if (ESR != ESR_Succeeded) {
5421       if (ESR != ESR_Failed && !Scope.destroy())
5422         return ESR_Failed;
5423       return ESR;
5424     }
5425 
5426     while (true) {
5427       // Condition: __begin != __end.
5428       {
5429         if (FS->getCond()->isValueDependent()) {
5430           EvaluateDependentExpr(FS->getCond(), Info);
5431           // We don't know whether to keep going or terminate the loop.
5432           return ESR_Failed;
5433         }
5434         bool Continue = true;
5435         FullExpressionRAII CondExpr(Info);
5436         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5437           return ESR_Failed;
5438         if (!Continue)
5439           break;
5440       }
5441 
5442       // User's variable declaration, initialized by *__begin.
5443       BlockScopeRAII InnerScope(Info);
5444       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5445       if (ESR != ESR_Succeeded) {
5446         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5447           return ESR_Failed;
5448         return ESR;
5449       }
5450 
5451       // Loop body.
5452       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5453       if (ESR != ESR_Continue) {
5454         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5455           return ESR_Failed;
5456         return ESR;
5457       }
5458       if (FS->getInc()->isValueDependent()) {
5459         if (!EvaluateDependentExpr(FS->getInc(), Info))
5460           return ESR_Failed;
5461       } else {
5462         // Increment: ++__begin
5463         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5464           return ESR_Failed;
5465       }
5466 
5467       if (!InnerScope.destroy())
5468         return ESR_Failed;
5469     }
5470 
5471     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5472   }
5473 
5474   case Stmt::SwitchStmtClass:
5475     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5476 
5477   case Stmt::ContinueStmtClass:
5478     return ESR_Continue;
5479 
5480   case Stmt::BreakStmtClass:
5481     return ESR_Break;
5482 
5483   case Stmt::LabelStmtClass:
5484     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5485 
5486   case Stmt::AttributedStmtClass:
5487     // As a general principle, C++11 attributes can be ignored without
5488     // any semantic impact.
5489     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5490                         Case);
5491 
5492   case Stmt::CaseStmtClass:
5493   case Stmt::DefaultStmtClass:
5494     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5495   case Stmt::CXXTryStmtClass:
5496     // Evaluate try blocks by evaluating all sub statements.
5497     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5498   }
5499 }
5500 
5501 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5502 /// default constructor. If so, we'll fold it whether or not it's marked as
5503 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5504 /// so we need special handling.
CheckTrivialDefaultConstructor(EvalInfo & Info,SourceLocation Loc,const CXXConstructorDecl * CD,bool IsValueInitialization)5505 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5506                                            const CXXConstructorDecl *CD,
5507                                            bool IsValueInitialization) {
5508   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5509     return false;
5510 
5511   // Value-initialization does not call a trivial default constructor, so such a
5512   // call is a core constant expression whether or not the constructor is
5513   // constexpr.
5514   if (!CD->isConstexpr() && !IsValueInitialization) {
5515     if (Info.getLangOpts().CPlusPlus11) {
5516       // FIXME: If DiagDecl is an implicitly-declared special member function,
5517       // we should be much more explicit about why it's not constexpr.
5518       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5519         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5520       Info.Note(CD->getLocation(), diag::note_declared_at);
5521     } else {
5522       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5523     }
5524   }
5525   return true;
5526 }
5527 
5528 /// CheckConstexprFunction - Check that a function can be called in a constant
5529 /// expression.
CheckConstexprFunction(EvalInfo & Info,SourceLocation CallLoc,const FunctionDecl * Declaration,const FunctionDecl * Definition,const Stmt * Body)5530 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5531                                    const FunctionDecl *Declaration,
5532                                    const FunctionDecl *Definition,
5533                                    const Stmt *Body) {
5534   // Potential constant expressions can contain calls to declared, but not yet
5535   // defined, constexpr functions.
5536   if (Info.checkingPotentialConstantExpression() && !Definition &&
5537       Declaration->isConstexpr())
5538     return false;
5539 
5540   // Bail out if the function declaration itself is invalid.  We will
5541   // have produced a relevant diagnostic while parsing it, so just
5542   // note the problematic sub-expression.
5543   if (Declaration->isInvalidDecl()) {
5544     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5545     return false;
5546   }
5547 
5548   // DR1872: An instantiated virtual constexpr function can't be called in a
5549   // constant expression (prior to C++20). We can still constant-fold such a
5550   // call.
5551   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5552       cast<CXXMethodDecl>(Declaration)->isVirtual())
5553     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5554 
5555   if (Definition && Definition->isInvalidDecl()) {
5556     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5557     return false;
5558   }
5559 
5560   // Can we evaluate this function call?
5561   if (Definition && Definition->isConstexpr() && Body)
5562     return true;
5563 
5564   if (Info.getLangOpts().CPlusPlus11) {
5565     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5566 
5567     // If this function is not constexpr because it is an inherited
5568     // non-constexpr constructor, diagnose that directly.
5569     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5570     if (CD && CD->isInheritingConstructor()) {
5571       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5572       if (!Inherited->isConstexpr())
5573         DiagDecl = CD = Inherited;
5574     }
5575 
5576     // FIXME: If DiagDecl is an implicitly-declared special member function
5577     // or an inheriting constructor, we should be much more explicit about why
5578     // it's not constexpr.
5579     if (CD && CD->isInheritingConstructor())
5580       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5581         << CD->getInheritedConstructor().getConstructor()->getParent();
5582     else
5583       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5584         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5585     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5586   } else {
5587     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5588   }
5589   return false;
5590 }
5591 
5592 namespace {
5593 struct CheckDynamicTypeHandler {
5594   AccessKinds AccessKind;
5595   typedef bool result_type;
failed__anond52d8a671111::CheckDynamicTypeHandler5596   bool failed() { return false; }
found__anond52d8a671111::CheckDynamicTypeHandler5597   bool found(APValue &Subobj, QualType SubobjType) { return true; }
found__anond52d8a671111::CheckDynamicTypeHandler5598   bool found(APSInt &Value, QualType SubobjType) { return true; }
found__anond52d8a671111::CheckDynamicTypeHandler5599   bool found(APFloat &Value, QualType SubobjType) { return true; }
5600 };
5601 } // end anonymous namespace
5602 
5603 /// Check that we can access the notional vptr of an object / determine its
5604 /// dynamic type.
checkDynamicType(EvalInfo & Info,const Expr * E,const LValue & This,AccessKinds AK,bool Polymorphic)5605 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5606                              AccessKinds AK, bool Polymorphic) {
5607   if (This.Designator.Invalid)
5608     return false;
5609 
5610   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5611 
5612   if (!Obj)
5613     return false;
5614 
5615   if (!Obj.Value) {
5616     // The object is not usable in constant expressions, so we can't inspect
5617     // its value to see if it's in-lifetime or what the active union members
5618     // are. We can still check for a one-past-the-end lvalue.
5619     if (This.Designator.isOnePastTheEnd() ||
5620         This.Designator.isMostDerivedAnUnsizedArray()) {
5621       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5622                          ? diag::note_constexpr_access_past_end
5623                          : diag::note_constexpr_access_unsized_array)
5624           << AK;
5625       return false;
5626     } else if (Polymorphic) {
5627       // Conservatively refuse to perform a polymorphic operation if we would
5628       // not be able to read a notional 'vptr' value.
5629       APValue Val;
5630       This.moveInto(Val);
5631       QualType StarThisType =
5632           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5633       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5634           << AK << Val.getAsString(Info.Ctx, StarThisType);
5635       return false;
5636     }
5637     return true;
5638   }
5639 
5640   CheckDynamicTypeHandler Handler{AK};
5641   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5642 }
5643 
5644 /// Check that the pointee of the 'this' pointer in a member function call is
5645 /// either within its lifetime or in its period of construction or destruction.
5646 static bool
checkNonVirtualMemberCallThisPointer(EvalInfo & Info,const Expr * E,const LValue & This,const CXXMethodDecl * NamedMember)5647 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5648                                      const LValue &This,
5649                                      const CXXMethodDecl *NamedMember) {
5650   return checkDynamicType(
5651       Info, E, This,
5652       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5653 }
5654 
5655 struct DynamicType {
5656   /// The dynamic class type of the object.
5657   const CXXRecordDecl *Type;
5658   /// The corresponding path length in the lvalue.
5659   unsigned PathLength;
5660 };
5661 
getBaseClassType(SubobjectDesignator & Designator,unsigned PathLength)5662 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5663                                              unsigned PathLength) {
5664   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5665       Designator.Entries.size() && "invalid path length");
5666   return (PathLength == Designator.MostDerivedPathLength)
5667              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5668              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5669 }
5670 
5671 /// Determine the dynamic type of an object.
ComputeDynamicType(EvalInfo & Info,const Expr * E,LValue & This,AccessKinds AK)5672 static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
5673                                                      const Expr *E,
5674                                                      LValue &This,
5675                                                      AccessKinds AK) {
5676   // If we don't have an lvalue denoting an object of class type, there is no
5677   // meaningful dynamic type. (We consider objects of non-class type to have no
5678   // dynamic type.)
5679   if (!checkDynamicType(Info, E, This, AK, true))
5680     return std::nullopt;
5681 
5682   // Refuse to compute a dynamic type in the presence of virtual bases. This
5683   // shouldn't happen other than in constant-folding situations, since literal
5684   // types can't have virtual bases.
5685   //
5686   // Note that consumers of DynamicType assume that the type has no virtual
5687   // bases, and will need modifications if this restriction is relaxed.
5688   const CXXRecordDecl *Class =
5689       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5690   if (!Class || Class->getNumVBases()) {
5691     Info.FFDiag(E);
5692     return std::nullopt;
5693   }
5694 
5695   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5696   // binary search here instead. But the overwhelmingly common case is that
5697   // we're not in the middle of a constructor, so it probably doesn't matter
5698   // in practice.
5699   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5700   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5701        PathLength <= Path.size(); ++PathLength) {
5702     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5703                                       Path.slice(0, PathLength))) {
5704     case ConstructionPhase::Bases:
5705     case ConstructionPhase::DestroyingBases:
5706       // We're constructing or destroying a base class. This is not the dynamic
5707       // type.
5708       break;
5709 
5710     case ConstructionPhase::None:
5711     case ConstructionPhase::AfterBases:
5712     case ConstructionPhase::AfterFields:
5713     case ConstructionPhase::Destroying:
5714       // We've finished constructing the base classes and not yet started
5715       // destroying them again, so this is the dynamic type.
5716       return DynamicType{getBaseClassType(This.Designator, PathLength),
5717                          PathLength};
5718     }
5719   }
5720 
5721   // CWG issue 1517: we're constructing a base class of the object described by
5722   // 'This', so that object has not yet begun its period of construction and
5723   // any polymorphic operation on it results in undefined behavior.
5724   Info.FFDiag(E);
5725   return std::nullopt;
5726 }
5727 
5728 /// Perform virtual dispatch.
HandleVirtualDispatch(EvalInfo & Info,const Expr * E,LValue & This,const CXXMethodDecl * Found,llvm::SmallVectorImpl<QualType> & CovariantAdjustmentPath)5729 static const CXXMethodDecl *HandleVirtualDispatch(
5730     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5731     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5732   std::optional<DynamicType> DynType = ComputeDynamicType(
5733       Info, E, This,
5734       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5735   if (!DynType)
5736     return nullptr;
5737 
5738   // Find the final overrider. It must be declared in one of the classes on the
5739   // path from the dynamic type to the static type.
5740   // FIXME: If we ever allow literal types to have virtual base classes, that
5741   // won't be true.
5742   const CXXMethodDecl *Callee = Found;
5743   unsigned PathLength = DynType->PathLength;
5744   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5745     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5746     const CXXMethodDecl *Overrider =
5747         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5748     if (Overrider) {
5749       Callee = Overrider;
5750       break;
5751     }
5752   }
5753 
5754   // C++2a [class.abstract]p6:
5755   //   the effect of making a virtual call to a pure virtual function [...] is
5756   //   undefined
5757   if (Callee->isPure()) {
5758     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5759     Info.Note(Callee->getLocation(), diag::note_declared_at);
5760     return nullptr;
5761   }
5762 
5763   // If necessary, walk the rest of the path to determine the sequence of
5764   // covariant adjustment steps to apply.
5765   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5766                                        Found->getReturnType())) {
5767     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5768     for (unsigned CovariantPathLength = PathLength + 1;
5769          CovariantPathLength != This.Designator.Entries.size();
5770          ++CovariantPathLength) {
5771       const CXXRecordDecl *NextClass =
5772           getBaseClassType(This.Designator, CovariantPathLength);
5773       const CXXMethodDecl *Next =
5774           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5775       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5776                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5777         CovariantAdjustmentPath.push_back(Next->getReturnType());
5778     }
5779     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5780                                          CovariantAdjustmentPath.back()))
5781       CovariantAdjustmentPath.push_back(Found->getReturnType());
5782   }
5783 
5784   // Perform 'this' adjustment.
5785   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5786     return nullptr;
5787 
5788   return Callee;
5789 }
5790 
5791 /// Perform the adjustment from a value returned by a virtual function to
5792 /// a value of the statically expected type, which may be a pointer or
5793 /// reference to a base class of the returned type.
HandleCovariantReturnAdjustment(EvalInfo & Info,const Expr * E,APValue & Result,ArrayRef<QualType> Path)5794 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5795                                             APValue &Result,
5796                                             ArrayRef<QualType> Path) {
5797   assert(Result.isLValue() &&
5798          "unexpected kind of APValue for covariant return");
5799   if (Result.isNullPointer())
5800     return true;
5801 
5802   LValue LVal;
5803   LVal.setFrom(Info.Ctx, Result);
5804 
5805   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5806   for (unsigned I = 1; I != Path.size(); ++I) {
5807     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5808     assert(OldClass && NewClass && "unexpected kind of covariant return");
5809     if (OldClass != NewClass &&
5810         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5811       return false;
5812     OldClass = NewClass;
5813   }
5814 
5815   LVal.moveInto(Result);
5816   return true;
5817 }
5818 
5819 /// Determine whether \p Base, which is known to be a direct base class of
5820 /// \p Derived, is a public base class.
isBaseClassPublic(const CXXRecordDecl * Derived,const CXXRecordDecl * Base)5821 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5822                               const CXXRecordDecl *Base) {
5823   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5824     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5825     if (BaseClass && declaresSameEntity(BaseClass, Base))
5826       return BaseSpec.getAccessSpecifier() == AS_public;
5827   }
5828   llvm_unreachable("Base is not a direct base of Derived");
5829 }
5830 
5831 /// Apply the given dynamic cast operation on the provided lvalue.
5832 ///
5833 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5834 /// to find a suitable target subobject.
HandleDynamicCast(EvalInfo & Info,const ExplicitCastExpr * E,LValue & Ptr)5835 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5836                               LValue &Ptr) {
5837   // We can't do anything with a non-symbolic pointer value.
5838   SubobjectDesignator &D = Ptr.Designator;
5839   if (D.Invalid)
5840     return false;
5841 
5842   // C++ [expr.dynamic.cast]p6:
5843   //   If v is a null pointer value, the result is a null pointer value.
5844   if (Ptr.isNullPointer() && !E->isGLValue())
5845     return true;
5846 
5847   // For all the other cases, we need the pointer to point to an object within
5848   // its lifetime / period of construction / destruction, and we need to know
5849   // its dynamic type.
5850   std::optional<DynamicType> DynType =
5851       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5852   if (!DynType)
5853     return false;
5854 
5855   // C++ [expr.dynamic.cast]p7:
5856   //   If T is "pointer to cv void", then the result is a pointer to the most
5857   //   derived object
5858   if (E->getType()->isVoidPointerType())
5859     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5860 
5861   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5862   assert(C && "dynamic_cast target is not void pointer nor class");
5863   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5864 
5865   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5866     // C++ [expr.dynamic.cast]p9:
5867     if (!E->isGLValue()) {
5868       //   The value of a failed cast to pointer type is the null pointer value
5869       //   of the required result type.
5870       Ptr.setNull(Info.Ctx, E->getType());
5871       return true;
5872     }
5873 
5874     //   A failed cast to reference type throws [...] std::bad_cast.
5875     unsigned DiagKind;
5876     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5877                    DynType->Type->isDerivedFrom(C)))
5878       DiagKind = 0;
5879     else if (!Paths || Paths->begin() == Paths->end())
5880       DiagKind = 1;
5881     else if (Paths->isAmbiguous(CQT))
5882       DiagKind = 2;
5883     else {
5884       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5885       DiagKind = 3;
5886     }
5887     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5888         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5889         << Info.Ctx.getRecordType(DynType->Type)
5890         << E->getType().getUnqualifiedType();
5891     return false;
5892   };
5893 
5894   // Runtime check, phase 1:
5895   //   Walk from the base subobject towards the derived object looking for the
5896   //   target type.
5897   for (int PathLength = Ptr.Designator.Entries.size();
5898        PathLength >= (int)DynType->PathLength; --PathLength) {
5899     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5900     if (declaresSameEntity(Class, C))
5901       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5902     // We can only walk across public inheritance edges.
5903     if (PathLength > (int)DynType->PathLength &&
5904         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5905                            Class))
5906       return RuntimeCheckFailed(nullptr);
5907   }
5908 
5909   // Runtime check, phase 2:
5910   //   Search the dynamic type for an unambiguous public base of type C.
5911   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5912                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5913   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5914       Paths.front().Access == AS_public) {
5915     // Downcast to the dynamic type...
5916     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5917       return false;
5918     // ... then upcast to the chosen base class subobject.
5919     for (CXXBasePathElement &Elem : Paths.front())
5920       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5921         return false;
5922     return true;
5923   }
5924 
5925   // Otherwise, the runtime check fails.
5926   return RuntimeCheckFailed(&Paths);
5927 }
5928 
5929 namespace {
5930 struct StartLifetimeOfUnionMemberHandler {
5931   EvalInfo &Info;
5932   const Expr *LHSExpr;
5933   const FieldDecl *Field;
5934   bool DuringInit;
5935   bool Failed = false;
5936   static const AccessKinds AccessKind = AK_Assign;
5937 
5938   typedef bool result_type;
failed__anond52d8a671311::StartLifetimeOfUnionMemberHandler5939   bool failed() { return Failed; }
found__anond52d8a671311::StartLifetimeOfUnionMemberHandler5940   bool found(APValue &Subobj, QualType SubobjType) {
5941     // We are supposed to perform no initialization but begin the lifetime of
5942     // the object. We interpret that as meaning to do what default
5943     // initialization of the object would do if all constructors involved were
5944     // trivial:
5945     //  * All base, non-variant member, and array element subobjects' lifetimes
5946     //    begin
5947     //  * No variant members' lifetimes begin
5948     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5949     assert(SubobjType->isUnionType());
5950     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5951       // This union member is already active. If it's also in-lifetime, there's
5952       // nothing to do.
5953       if (Subobj.getUnionValue().hasValue())
5954         return true;
5955     } else if (DuringInit) {
5956       // We're currently in the process of initializing a different union
5957       // member.  If we carried on, that initialization would attempt to
5958       // store to an inactive union member, resulting in undefined behavior.
5959       Info.FFDiag(LHSExpr,
5960                   diag::note_constexpr_union_member_change_during_init);
5961       return false;
5962     }
5963     APValue Result;
5964     Failed = !getDefaultInitValue(Field->getType(), Result);
5965     Subobj.setUnion(Field, Result);
5966     return true;
5967   }
found__anond52d8a671311::StartLifetimeOfUnionMemberHandler5968   bool found(APSInt &Value, QualType SubobjType) {
5969     llvm_unreachable("wrong value kind for union object");
5970   }
found__anond52d8a671311::StartLifetimeOfUnionMemberHandler5971   bool found(APFloat &Value, QualType SubobjType) {
5972     llvm_unreachable("wrong value kind for union object");
5973   }
5974 };
5975 } // end anonymous namespace
5976 
5977 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5978 
5979 /// Handle a builtin simple-assignment or a call to a trivial assignment
5980 /// operator whose left-hand side might involve a union member access. If it
5981 /// does, implicitly start the lifetime of any accessed union elements per
5982 /// C++20 [class.union]5.
HandleUnionActiveMemberChange(EvalInfo & Info,const Expr * LHSExpr,const LValue & LHS)5983 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5984                                           const LValue &LHS) {
5985   if (LHS.InvalidBase || LHS.Designator.Invalid)
5986     return false;
5987 
5988   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5989   // C++ [class.union]p5:
5990   //   define the set S(E) of subexpressions of E as follows:
5991   unsigned PathLength = LHS.Designator.Entries.size();
5992   for (const Expr *E = LHSExpr; E != nullptr;) {
5993     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5994     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5995       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5996       // Note that we can't implicitly start the lifetime of a reference,
5997       // so we don't need to proceed any further if we reach one.
5998       if (!FD || FD->getType()->isReferenceType())
5999         break;
6000 
6001       //    ... and also contains A.B if B names a union member ...
6002       if (FD->getParent()->isUnion()) {
6003         //    ... of a non-class, non-array type, or of a class type with a
6004         //    trivial default constructor that is not deleted, or an array of
6005         //    such types.
6006         auto *RD =
6007             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6008         if (!RD || RD->hasTrivialDefaultConstructor())
6009           UnionPathLengths.push_back({PathLength - 1, FD});
6010       }
6011 
6012       E = ME->getBase();
6013       --PathLength;
6014       assert(declaresSameEntity(FD,
6015                                 LHS.Designator.Entries[PathLength]
6016                                     .getAsBaseOrMember().getPointer()));
6017 
6018       //   -- If E is of the form A[B] and is interpreted as a built-in array
6019       //      subscripting operator, S(E) is [S(the array operand, if any)].
6020     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6021       // Step over an ArrayToPointerDecay implicit cast.
6022       auto *Base = ASE->getBase()->IgnoreImplicit();
6023       if (!Base->getType()->isArrayType())
6024         break;
6025 
6026       E = Base;
6027       --PathLength;
6028 
6029     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6030       // Step over a derived-to-base conversion.
6031       E = ICE->getSubExpr();
6032       if (ICE->getCastKind() == CK_NoOp)
6033         continue;
6034       if (ICE->getCastKind() != CK_DerivedToBase &&
6035           ICE->getCastKind() != CK_UncheckedDerivedToBase)
6036         break;
6037       // Walk path backwards as we walk up from the base to the derived class.
6038       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6039         --PathLength;
6040         (void)Elt;
6041         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6042                                   LHS.Designator.Entries[PathLength]
6043                                       .getAsBaseOrMember().getPointer()));
6044       }
6045 
6046     //   -- Otherwise, S(E) is empty.
6047     } else {
6048       break;
6049     }
6050   }
6051 
6052   // Common case: no unions' lifetimes are started.
6053   if (UnionPathLengths.empty())
6054     return true;
6055 
6056   //   if modification of X [would access an inactive union member], an object
6057   //   of the type of X is implicitly created
6058   CompleteObject Obj =
6059       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6060   if (!Obj)
6061     return false;
6062   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6063            llvm::reverse(UnionPathLengths)) {
6064     // Form a designator for the union object.
6065     SubobjectDesignator D = LHS.Designator;
6066     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6067 
6068     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6069                       ConstructionPhase::AfterBases;
6070     StartLifetimeOfUnionMemberHandler StartLifetime{
6071         Info, LHSExpr, LengthAndField.second, DuringInit};
6072     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6073       return false;
6074   }
6075 
6076   return true;
6077 }
6078 
EvaluateCallArg(const ParmVarDecl * PVD,const Expr * Arg,CallRef Call,EvalInfo & Info,bool NonNull=false)6079 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6080                             CallRef Call, EvalInfo &Info,
6081                             bool NonNull = false) {
6082   LValue LV;
6083   // Create the parameter slot and register its destruction. For a vararg
6084   // argument, create a temporary.
6085   // FIXME: For calling conventions that destroy parameters in the callee,
6086   // should we consider performing destruction when the function returns
6087   // instead?
6088   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6089                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6090                                                        ScopeKind::Call, LV);
6091   if (!EvaluateInPlace(V, Info, LV, Arg))
6092     return false;
6093 
6094   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6095   // undefined behavior, so is non-constant.
6096   if (NonNull && V.isLValue() && V.isNullPointer()) {
6097     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6098     return false;
6099   }
6100 
6101   return true;
6102 }
6103 
6104 /// Evaluate the arguments to a function call.
EvaluateArgs(ArrayRef<const Expr * > Args,CallRef Call,EvalInfo & Info,const FunctionDecl * Callee,bool RightToLeft=false)6105 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6106                          EvalInfo &Info, const FunctionDecl *Callee,
6107                          bool RightToLeft = false) {
6108   bool Success = true;
6109   llvm::SmallBitVector ForbiddenNullArgs;
6110   if (Callee->hasAttr<NonNullAttr>()) {
6111     ForbiddenNullArgs.resize(Args.size());
6112     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6113       if (!Attr->args_size()) {
6114         ForbiddenNullArgs.set();
6115         break;
6116       } else
6117         for (auto Idx : Attr->args()) {
6118           unsigned ASTIdx = Idx.getASTIndex();
6119           if (ASTIdx >= Args.size())
6120             continue;
6121           ForbiddenNullArgs[ASTIdx] = true;
6122         }
6123     }
6124   }
6125   for (unsigned I = 0; I < Args.size(); I++) {
6126     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6127     const ParmVarDecl *PVD =
6128         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6129     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6130     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6131       // If we're checking for a potential constant expression, evaluate all
6132       // initializers even if some of them fail.
6133       if (!Info.noteFailure())
6134         return false;
6135       Success = false;
6136     }
6137   }
6138   return Success;
6139 }
6140 
6141 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6142 /// constructor or assignment operator.
handleTrivialCopy(EvalInfo & Info,const ParmVarDecl * Param,const Expr * E,APValue & Result,bool CopyObjectRepresentation)6143 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6144                               const Expr *E, APValue &Result,
6145                               bool CopyObjectRepresentation) {
6146   // Find the reference argument.
6147   CallStackFrame *Frame = Info.CurrentCall;
6148   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6149   if (!RefValue) {
6150     Info.FFDiag(E);
6151     return false;
6152   }
6153 
6154   // Copy out the contents of the RHS object.
6155   LValue RefLValue;
6156   RefLValue.setFrom(Info.Ctx, *RefValue);
6157   return handleLValueToRValueConversion(
6158       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6159       CopyObjectRepresentation);
6160 }
6161 
6162 /// 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)6163 static bool HandleFunctionCall(SourceLocation CallLoc,
6164                                const FunctionDecl *Callee, const LValue *This,
6165                                ArrayRef<const Expr *> Args, CallRef Call,
6166                                const Stmt *Body, EvalInfo &Info,
6167                                APValue &Result, const LValue *ResultSlot) {
6168   if (!Info.CheckCallLimit(CallLoc))
6169     return false;
6170 
6171   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6172 
6173   // For a trivial copy or move assignment, perform an APValue copy. This is
6174   // essential for unions, where the operations performed by the assignment
6175   // operator cannot be represented as statements.
6176   //
6177   // Skip this for non-union classes with no fields; in that case, the defaulted
6178   // copy/move does not actually read the object.
6179   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6180   if (MD && MD->isDefaulted() &&
6181       (MD->getParent()->isUnion() ||
6182        (MD->isTrivial() &&
6183         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6184     assert(This &&
6185            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6186     APValue RHSValue;
6187     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6188                            MD->getParent()->isUnion()))
6189       return false;
6190     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6191                           RHSValue))
6192       return false;
6193     This->moveInto(Result);
6194     return true;
6195   } else if (MD && isLambdaCallOperator(MD)) {
6196     // We're in a lambda; determine the lambda capture field maps unless we're
6197     // just constexpr checking a lambda's call operator. constexpr checking is
6198     // done before the captures have been added to the closure object (unless
6199     // we're inferring constexpr-ness), so we don't have access to them in this
6200     // case. But since we don't need the captures to constexpr check, we can
6201     // just ignore them.
6202     if (!Info.checkingPotentialConstantExpression())
6203       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6204                                         Frame.LambdaThisCaptureField);
6205   }
6206 
6207   StmtResult Ret = {Result, ResultSlot};
6208   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6209   if (ESR == ESR_Succeeded) {
6210     if (Callee->getReturnType()->isVoidType())
6211       return true;
6212     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6213   }
6214   return ESR == ESR_Returned;
6215 }
6216 
6217 /// Evaluate a constructor call.
HandleConstructorCall(const Expr * E,const LValue & This,CallRef Call,const CXXConstructorDecl * Definition,EvalInfo & Info,APValue & Result)6218 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6219                                   CallRef Call,
6220                                   const CXXConstructorDecl *Definition,
6221                                   EvalInfo &Info, APValue &Result) {
6222   SourceLocation CallLoc = E->getExprLoc();
6223   if (!Info.CheckCallLimit(CallLoc))
6224     return false;
6225 
6226   const CXXRecordDecl *RD = Definition->getParent();
6227   if (RD->getNumVBases()) {
6228     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6229     return false;
6230   }
6231 
6232   EvalInfo::EvaluatingConstructorRAII EvalObj(
6233       Info,
6234       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6235       RD->getNumBases());
6236   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6237 
6238   // FIXME: Creating an APValue just to hold a nonexistent return value is
6239   // wasteful.
6240   APValue RetVal;
6241   StmtResult Ret = {RetVal, nullptr};
6242 
6243   // If it's a delegating constructor, delegate.
6244   if (Definition->isDelegatingConstructor()) {
6245     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6246     if ((*I)->getInit()->isValueDependent()) {
6247       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6248         return false;
6249     } else {
6250       FullExpressionRAII InitScope(Info);
6251       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6252           !InitScope.destroy())
6253         return false;
6254     }
6255     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6256   }
6257 
6258   // For a trivial copy or move constructor, perform an APValue copy. This is
6259   // essential for unions (or classes with anonymous union members), where the
6260   // operations performed by the constructor cannot be represented by
6261   // ctor-initializers.
6262   //
6263   // Skip this for empty non-union classes; we should not perform an
6264   // lvalue-to-rvalue conversion on them because their copy constructor does not
6265   // actually read them.
6266   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6267       (Definition->getParent()->isUnion() ||
6268        (Definition->isTrivial() &&
6269         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6270     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6271                              Definition->getParent()->isUnion());
6272   }
6273 
6274   // Reserve space for the struct members.
6275   if (!Result.hasValue()) {
6276     if (!RD->isUnion())
6277       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6278                        std::distance(RD->field_begin(), RD->field_end()));
6279     else
6280       // A union starts with no active member.
6281       Result = APValue((const FieldDecl*)nullptr);
6282   }
6283 
6284   if (RD->isInvalidDecl()) return false;
6285   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6286 
6287   // A scope for temporaries lifetime-extended by reference members.
6288   BlockScopeRAII LifetimeExtendedScope(Info);
6289 
6290   bool Success = true;
6291   unsigned BasesSeen = 0;
6292 #ifndef NDEBUG
6293   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6294 #endif
6295   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6296   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6297     // We might be initializing the same field again if this is an indirect
6298     // field initialization.
6299     if (FieldIt == RD->field_end() ||
6300         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6301       assert(Indirect && "fields out of order?");
6302       return;
6303     }
6304 
6305     // Default-initialize any fields with no explicit initializer.
6306     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6307       assert(FieldIt != RD->field_end() && "missing field?");
6308       if (!FieldIt->isUnnamedBitfield())
6309         Success &= getDefaultInitValue(
6310             FieldIt->getType(),
6311             Result.getStructField(FieldIt->getFieldIndex()));
6312     }
6313     ++FieldIt;
6314   };
6315   for (const auto *I : Definition->inits()) {
6316     LValue Subobject = This;
6317     LValue SubobjectParent = This;
6318     APValue *Value = &Result;
6319 
6320     // Determine the subobject to initialize.
6321     FieldDecl *FD = nullptr;
6322     if (I->isBaseInitializer()) {
6323       QualType BaseType(I->getBaseClass(), 0);
6324 #ifndef NDEBUG
6325       // Non-virtual base classes are initialized in the order in the class
6326       // definition. We have already checked for virtual base classes.
6327       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6328       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6329              "base class initializers not in expected order");
6330       ++BaseIt;
6331 #endif
6332       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6333                                   BaseType->getAsCXXRecordDecl(), &Layout))
6334         return false;
6335       Value = &Result.getStructBase(BasesSeen++);
6336     } else if ((FD = I->getMember())) {
6337       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6338         return false;
6339       if (RD->isUnion()) {
6340         Result = APValue(FD);
6341         Value = &Result.getUnionValue();
6342       } else {
6343         SkipToField(FD, false);
6344         Value = &Result.getStructField(FD->getFieldIndex());
6345       }
6346     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6347       // Walk the indirect field decl's chain to find the object to initialize,
6348       // and make sure we've initialized every step along it.
6349       auto IndirectFieldChain = IFD->chain();
6350       for (auto *C : IndirectFieldChain) {
6351         FD = cast<FieldDecl>(C);
6352         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6353         // Switch the union field if it differs. This happens if we had
6354         // preceding zero-initialization, and we're now initializing a union
6355         // subobject other than the first.
6356         // FIXME: In this case, the values of the other subobjects are
6357         // specified, since zero-initialization sets all padding bits to zero.
6358         if (!Value->hasValue() ||
6359             (Value->isUnion() && Value->getUnionField() != FD)) {
6360           if (CD->isUnion())
6361             *Value = APValue(FD);
6362           else
6363             // FIXME: This immediately starts the lifetime of all members of
6364             // an anonymous struct. It would be preferable to strictly start
6365             // member lifetime in initialization order.
6366             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6367         }
6368         // Store Subobject as its parent before updating it for the last element
6369         // in the chain.
6370         if (C == IndirectFieldChain.back())
6371           SubobjectParent = Subobject;
6372         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6373           return false;
6374         if (CD->isUnion())
6375           Value = &Value->getUnionValue();
6376         else {
6377           if (C == IndirectFieldChain.front() && !RD->isUnion())
6378             SkipToField(FD, true);
6379           Value = &Value->getStructField(FD->getFieldIndex());
6380         }
6381       }
6382     } else {
6383       llvm_unreachable("unknown base initializer kind");
6384     }
6385 
6386     // Need to override This for implicit field initializers as in this case
6387     // This refers to innermost anonymous struct/union containing initializer,
6388     // not to currently constructed class.
6389     const Expr *Init = I->getInit();
6390     if (Init->isValueDependent()) {
6391       if (!EvaluateDependentExpr(Init, Info))
6392         return false;
6393     } else {
6394       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6395                                     isa<CXXDefaultInitExpr>(Init));
6396       FullExpressionRAII InitScope(Info);
6397       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6398           (FD && FD->isBitField() &&
6399            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6400         // If we're checking for a potential constant expression, evaluate all
6401         // initializers even if some of them fail.
6402         if (!Info.noteFailure())
6403           return false;
6404         Success = false;
6405       }
6406     }
6407 
6408     // This is the point at which the dynamic type of the object becomes this
6409     // class type.
6410     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6411       EvalObj.finishedConstructingBases();
6412   }
6413 
6414   // Default-initialize any remaining fields.
6415   if (!RD->isUnion()) {
6416     for (; FieldIt != RD->field_end(); ++FieldIt) {
6417       if (!FieldIt->isUnnamedBitfield())
6418         Success &= getDefaultInitValue(
6419             FieldIt->getType(),
6420             Result.getStructField(FieldIt->getFieldIndex()));
6421     }
6422   }
6423 
6424   EvalObj.finishedConstructingFields();
6425 
6426   return Success &&
6427          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6428          LifetimeExtendedScope.destroy();
6429 }
6430 
HandleConstructorCall(const Expr * E,const LValue & This,ArrayRef<const Expr * > Args,const CXXConstructorDecl * Definition,EvalInfo & Info,APValue & Result)6431 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6432                                   ArrayRef<const Expr*> Args,
6433                                   const CXXConstructorDecl *Definition,
6434                                   EvalInfo &Info, APValue &Result) {
6435   CallScopeRAII CallScope(Info);
6436   CallRef Call = Info.CurrentCall->createCall(Definition);
6437   if (!EvaluateArgs(Args, Call, Info, Definition))
6438     return false;
6439 
6440   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6441          CallScope.destroy();
6442 }
6443 
HandleDestructionImpl(EvalInfo & Info,SourceLocation CallLoc,const LValue & This,APValue & Value,QualType T)6444 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6445                                   const LValue &This, APValue &Value,
6446                                   QualType T) {
6447   // Objects can only be destroyed while they're within their lifetimes.
6448   // FIXME: We have no representation for whether an object of type nullptr_t
6449   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6450   // as indeterminate instead?
6451   if (Value.isAbsent() && !T->isNullPtrType()) {
6452     APValue Printable;
6453     This.moveInto(Printable);
6454     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6455       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6456     return false;
6457   }
6458 
6459   // Invent an expression for location purposes.
6460   // FIXME: We shouldn't need to do this.
6461   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6462 
6463   // For arrays, destroy elements right-to-left.
6464   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6465     uint64_t Size = CAT->getSize().getZExtValue();
6466     QualType ElemT = CAT->getElementType();
6467 
6468     LValue ElemLV = This;
6469     ElemLV.addArray(Info, &LocE, CAT);
6470     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6471       return false;
6472 
6473     // Ensure that we have actual array elements available to destroy; the
6474     // destructors might mutate the value, so we can't run them on the array
6475     // filler.
6476     if (Size && Size > Value.getArrayInitializedElts())
6477       expandArray(Value, Value.getArraySize() - 1);
6478 
6479     for (; Size != 0; --Size) {
6480       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6481       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6482           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6483         return false;
6484     }
6485 
6486     // End the lifetime of this array now.
6487     Value = APValue();
6488     return true;
6489   }
6490 
6491   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6492   if (!RD) {
6493     if (T.isDestructedType()) {
6494       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6495       return false;
6496     }
6497 
6498     Value = APValue();
6499     return true;
6500   }
6501 
6502   if (RD->getNumVBases()) {
6503     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6504     return false;
6505   }
6506 
6507   const CXXDestructorDecl *DD = RD->getDestructor();
6508   if (!DD && !RD->hasTrivialDestructor()) {
6509     Info.FFDiag(CallLoc);
6510     return false;
6511   }
6512 
6513   if (!DD || DD->isTrivial() ||
6514       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6515     // A trivial destructor just ends the lifetime of the object. Check for
6516     // this case before checking for a body, because we might not bother
6517     // building a body for a trivial destructor. Note that it doesn't matter
6518     // whether the destructor is constexpr in this case; all trivial
6519     // destructors are constexpr.
6520     //
6521     // If an anonymous union would be destroyed, some enclosing destructor must
6522     // have been explicitly defined, and the anonymous union destruction should
6523     // have no effect.
6524     Value = APValue();
6525     return true;
6526   }
6527 
6528   if (!Info.CheckCallLimit(CallLoc))
6529     return false;
6530 
6531   const FunctionDecl *Definition = nullptr;
6532   const Stmt *Body = DD->getBody(Definition);
6533 
6534   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6535     return false;
6536 
6537   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6538 
6539   // We're now in the period of destruction of this object.
6540   unsigned BasesLeft = RD->getNumBases();
6541   EvalInfo::EvaluatingDestructorRAII EvalObj(
6542       Info,
6543       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6544   if (!EvalObj.DidInsert) {
6545     // C++2a [class.dtor]p19:
6546     //   the behavior is undefined if the destructor is invoked for an object
6547     //   whose lifetime has ended
6548     // (Note that formally the lifetime ends when the period of destruction
6549     // begins, even though certain uses of the object remain valid until the
6550     // period of destruction ends.)
6551     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6552     return false;
6553   }
6554 
6555   // FIXME: Creating an APValue just to hold a nonexistent return value is
6556   // wasteful.
6557   APValue RetVal;
6558   StmtResult Ret = {RetVal, nullptr};
6559   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6560     return false;
6561 
6562   // A union destructor does not implicitly destroy its members.
6563   if (RD->isUnion())
6564     return true;
6565 
6566   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6567 
6568   // We don't have a good way to iterate fields in reverse, so collect all the
6569   // fields first and then walk them backwards.
6570   SmallVector<FieldDecl*, 16> Fields(RD->fields());
6571   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6572     if (FD->isUnnamedBitfield())
6573       continue;
6574 
6575     LValue Subobject = This;
6576     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6577       return false;
6578 
6579     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6580     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6581                                FD->getType()))
6582       return false;
6583   }
6584 
6585   if (BasesLeft != 0)
6586     EvalObj.startedDestroyingBases();
6587 
6588   // Destroy base classes in reverse order.
6589   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6590     --BasesLeft;
6591 
6592     QualType BaseType = Base.getType();
6593     LValue Subobject = This;
6594     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6595                                 BaseType->getAsCXXRecordDecl(), &Layout))
6596       return false;
6597 
6598     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6599     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6600                                BaseType))
6601       return false;
6602   }
6603   assert(BasesLeft == 0 && "NumBases was wrong?");
6604 
6605   // The period of destruction ends now. The object is gone.
6606   Value = APValue();
6607   return true;
6608 }
6609 
6610 namespace {
6611 struct DestroyObjectHandler {
6612   EvalInfo &Info;
6613   const Expr *E;
6614   const LValue &This;
6615   const AccessKinds AccessKind;
6616 
6617   typedef bool result_type;
failed__anond52d8a671511::DestroyObjectHandler6618   bool failed() { return false; }
found__anond52d8a671511::DestroyObjectHandler6619   bool found(APValue &Subobj, QualType SubobjType) {
6620     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6621                                  SubobjType);
6622   }
found__anond52d8a671511::DestroyObjectHandler6623   bool found(APSInt &Value, QualType SubobjType) {
6624     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6625     return false;
6626   }
found__anond52d8a671511::DestroyObjectHandler6627   bool found(APFloat &Value, QualType SubobjType) {
6628     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6629     return false;
6630   }
6631 };
6632 }
6633 
6634 /// Perform a destructor or pseudo-destructor call on the given object, which
6635 /// might in general not be a complete object.
HandleDestruction(EvalInfo & Info,const Expr * E,const LValue & This,QualType ThisType)6636 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6637                               const LValue &This, QualType ThisType) {
6638   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6639   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6640   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6641 }
6642 
6643 /// Destroy and end the lifetime of the given complete object.
HandleDestruction(EvalInfo & Info,SourceLocation Loc,APValue::LValueBase LVBase,APValue & Value,QualType T)6644 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6645                               APValue::LValueBase LVBase, APValue &Value,
6646                               QualType T) {
6647   // If we've had an unmodeled side-effect, we can't rely on mutable state
6648   // (such as the object we're about to destroy) being correct.
6649   if (Info.EvalStatus.HasSideEffects)
6650     return false;
6651 
6652   LValue LV;
6653   LV.set({LVBase});
6654   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6655 }
6656 
6657 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
HandleOperatorNewCall(EvalInfo & Info,const CallExpr * E,LValue & Result)6658 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6659                                   LValue &Result) {
6660   if (Info.checkingPotentialConstantExpression() ||
6661       Info.SpeculativeEvaluationDepth)
6662     return false;
6663 
6664   // This is permitted only within a call to std::allocator<T>::allocate.
6665   auto Caller = Info.getStdAllocatorCaller("allocate");
6666   if (!Caller) {
6667     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6668                                      ? diag::note_constexpr_new_untyped
6669                                      : diag::note_constexpr_new);
6670     return false;
6671   }
6672 
6673   QualType ElemType = Caller.ElemType;
6674   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6675     Info.FFDiag(E->getExprLoc(),
6676                 diag::note_constexpr_new_not_complete_object_type)
6677         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6678     return false;
6679   }
6680 
6681   APSInt ByteSize;
6682   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6683     return false;
6684   bool IsNothrow = false;
6685   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6686     EvaluateIgnoredValue(Info, E->getArg(I));
6687     IsNothrow |= E->getType()->isNothrowT();
6688   }
6689 
6690   CharUnits ElemSize;
6691   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6692     return false;
6693   APInt Size, Remainder;
6694   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6695   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6696   if (Remainder != 0) {
6697     // This likely indicates a bug in the implementation of 'std::allocator'.
6698     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6699         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6700     return false;
6701   }
6702 
6703   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6704     if (IsNothrow) {
6705       Result.setNull(Info.Ctx, E->getType());
6706       return true;
6707     }
6708 
6709     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6710     return false;
6711   }
6712 
6713   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6714                                                      ArrayType::Normal, 0);
6715   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6716   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6717   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6718   return true;
6719 }
6720 
hasVirtualDestructor(QualType T)6721 static bool hasVirtualDestructor(QualType T) {
6722   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6723     if (CXXDestructorDecl *DD = RD->getDestructor())
6724       return DD->isVirtual();
6725   return false;
6726 }
6727 
getVirtualOperatorDelete(QualType T)6728 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6729   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6730     if (CXXDestructorDecl *DD = RD->getDestructor())
6731       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6732   return nullptr;
6733 }
6734 
6735 /// Check that the given object is a suitable pointer to a heap allocation that
6736 /// still exists and is of the right kind for the purpose of a deletion.
6737 ///
6738 /// On success, returns the heap allocation to deallocate. On failure, produces
6739 /// a diagnostic and returns std::nullopt.
CheckDeleteKind(EvalInfo & Info,const Expr * E,const LValue & Pointer,DynAlloc::Kind DeallocKind)6740 static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6741                                                  const LValue &Pointer,
6742                                                  DynAlloc::Kind DeallocKind) {
6743   auto PointerAsString = [&] {
6744     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6745   };
6746 
6747   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6748   if (!DA) {
6749     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6750         << PointerAsString();
6751     if (Pointer.Base)
6752       NoteLValueLocation(Info, Pointer.Base);
6753     return std::nullopt;
6754   }
6755 
6756   std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6757   if (!Alloc) {
6758     Info.FFDiag(E, diag::note_constexpr_double_delete);
6759     return std::nullopt;
6760   }
6761 
6762   QualType AllocType = Pointer.Base.getDynamicAllocType();
6763   if (DeallocKind != (*Alloc)->getKind()) {
6764     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6765         << DeallocKind << (*Alloc)->getKind() << AllocType;
6766     NoteLValueLocation(Info, Pointer.Base);
6767     return std::nullopt;
6768   }
6769 
6770   bool Subobject = false;
6771   if (DeallocKind == DynAlloc::New) {
6772     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6773                 Pointer.Designator.isOnePastTheEnd();
6774   } else {
6775     Subobject = Pointer.Designator.Entries.size() != 1 ||
6776                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6777   }
6778   if (Subobject) {
6779     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6780         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6781     return std::nullopt;
6782   }
6783 
6784   return Alloc;
6785 }
6786 
6787 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
HandleOperatorDeleteCall(EvalInfo & Info,const CallExpr * E)6788 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6789   if (Info.checkingPotentialConstantExpression() ||
6790       Info.SpeculativeEvaluationDepth)
6791     return false;
6792 
6793   // This is permitted only within a call to std::allocator<T>::deallocate.
6794   if (!Info.getStdAllocatorCaller("deallocate")) {
6795     Info.FFDiag(E->getExprLoc());
6796     return true;
6797   }
6798 
6799   LValue Pointer;
6800   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6801     return false;
6802   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6803     EvaluateIgnoredValue(Info, E->getArg(I));
6804 
6805   if (Pointer.Designator.Invalid)
6806     return false;
6807 
6808   // Deleting a null pointer would have no effect, but it's not permitted by
6809   // std::allocator<T>::deallocate's contract.
6810   if (Pointer.isNullPointer()) {
6811     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6812     return true;
6813   }
6814 
6815   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6816     return false;
6817 
6818   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6819   return true;
6820 }
6821 
6822 //===----------------------------------------------------------------------===//
6823 // Generic Evaluation
6824 //===----------------------------------------------------------------------===//
6825 namespace {
6826 
6827 class BitCastBuffer {
6828   // FIXME: We're going to need bit-level granularity when we support
6829   // bit-fields.
6830   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6831   // we don't support a host or target where that is the case. Still, we should
6832   // use a more generic type in case we ever do.
6833   SmallVector<std::optional<unsigned char>, 32> Bytes;
6834 
6835   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6836                 "Need at least 8 bit unsigned char");
6837 
6838   bool TargetIsLittleEndian;
6839 
6840 public:
BitCastBuffer(CharUnits Width,bool TargetIsLittleEndian)6841   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6842       : Bytes(Width.getQuantity()),
6843         TargetIsLittleEndian(TargetIsLittleEndian) {}
6844 
readObject(CharUnits Offset,CharUnits Width,SmallVectorImpl<unsigned char> & Output) const6845   [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
6846                                 SmallVectorImpl<unsigned char> &Output) const {
6847     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6848       // If a byte of an integer is uninitialized, then the whole integer is
6849       // uninitialized.
6850       if (!Bytes[I.getQuantity()])
6851         return false;
6852       Output.push_back(*Bytes[I.getQuantity()]);
6853     }
6854     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6855       std::reverse(Output.begin(), Output.end());
6856     return true;
6857   }
6858 
writeObject(CharUnits Offset,SmallVectorImpl<unsigned char> & Input)6859   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6860     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6861       std::reverse(Input.begin(), Input.end());
6862 
6863     size_t Index = 0;
6864     for (unsigned char Byte : Input) {
6865       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6866       Bytes[Offset.getQuantity() + Index] = Byte;
6867       ++Index;
6868     }
6869   }
6870 
size()6871   size_t size() { return Bytes.size(); }
6872 };
6873 
6874 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6875 /// target would represent the value at runtime.
6876 class APValueToBufferConverter {
6877   EvalInfo &Info;
6878   BitCastBuffer Buffer;
6879   const CastExpr *BCE;
6880 
APValueToBufferConverter(EvalInfo & Info,CharUnits ObjectWidth,const CastExpr * BCE)6881   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6882                            const CastExpr *BCE)
6883       : Info(Info),
6884         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6885         BCE(BCE) {}
6886 
visit(const APValue & Val,QualType Ty)6887   bool visit(const APValue &Val, QualType Ty) {
6888     return visit(Val, Ty, CharUnits::fromQuantity(0));
6889   }
6890 
6891   // Write out Val with type Ty into Buffer starting at Offset.
visit(const APValue & Val,QualType Ty,CharUnits Offset)6892   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6893     assert((size_t)Offset.getQuantity() <= Buffer.size());
6894 
6895     // As a special case, nullptr_t has an indeterminate value.
6896     if (Ty->isNullPtrType())
6897       return true;
6898 
6899     // Dig through Src to find the byte at SrcOffset.
6900     switch (Val.getKind()) {
6901     case APValue::Indeterminate:
6902     case APValue::None:
6903       return true;
6904 
6905     case APValue::Int:
6906       return visitInt(Val.getInt(), Ty, Offset);
6907     case APValue::Float:
6908       return visitFloat(Val.getFloat(), Ty, Offset);
6909     case APValue::Array:
6910       return visitArray(Val, Ty, Offset);
6911     case APValue::Struct:
6912       return visitRecord(Val, Ty, Offset);
6913 
6914     case APValue::ComplexInt:
6915     case APValue::ComplexFloat:
6916     case APValue::Vector:
6917     case APValue::FixedPoint:
6918       // FIXME: We should support these.
6919 
6920     case APValue::Union:
6921     case APValue::MemberPointer:
6922     case APValue::AddrLabelDiff: {
6923       Info.FFDiag(BCE->getBeginLoc(),
6924                   diag::note_constexpr_bit_cast_unsupported_type)
6925           << Ty;
6926       return false;
6927     }
6928 
6929     case APValue::LValue:
6930       llvm_unreachable("LValue subobject in bit_cast?");
6931     }
6932     llvm_unreachable("Unhandled APValue::ValueKind");
6933   }
6934 
visitRecord(const APValue & Val,QualType Ty,CharUnits Offset)6935   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6936     const RecordDecl *RD = Ty->getAsRecordDecl();
6937     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6938 
6939     // Visit the base classes.
6940     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6941       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6942         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6943         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6944 
6945         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6946                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6947           return false;
6948       }
6949     }
6950 
6951     // Visit the fields.
6952     unsigned FieldIdx = 0;
6953     for (FieldDecl *FD : RD->fields()) {
6954       if (FD->isBitField()) {
6955         Info.FFDiag(BCE->getBeginLoc(),
6956                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6957         return false;
6958       }
6959 
6960       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6961 
6962       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6963              "only bit-fields can have sub-char alignment");
6964       CharUnits FieldOffset =
6965           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6966       QualType FieldTy = FD->getType();
6967       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6968         return false;
6969       ++FieldIdx;
6970     }
6971 
6972     return true;
6973   }
6974 
visitArray(const APValue & Val,QualType Ty,CharUnits Offset)6975   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6976     const auto *CAT =
6977         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6978     if (!CAT)
6979       return false;
6980 
6981     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6982     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6983     unsigned ArraySize = Val.getArraySize();
6984     // First, initialize the initialized elements.
6985     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6986       const APValue &SubObj = Val.getArrayInitializedElt(I);
6987       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6988         return false;
6989     }
6990 
6991     // Next, initialize the rest of the array using the filler.
6992     if (Val.hasArrayFiller()) {
6993       const APValue &Filler = Val.getArrayFiller();
6994       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6995         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6996           return false;
6997       }
6998     }
6999 
7000     return true;
7001   }
7002 
visitInt(const APSInt & Val,QualType Ty,CharUnits Offset)7003   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7004     APSInt AdjustedVal = Val;
7005     unsigned Width = AdjustedVal.getBitWidth();
7006     if (Ty->isBooleanType()) {
7007       Width = Info.Ctx.getTypeSize(Ty);
7008       AdjustedVal = AdjustedVal.extend(Width);
7009     }
7010 
7011     SmallVector<unsigned char, 8> Bytes(Width / 8);
7012     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7013     Buffer.writeObject(Offset, Bytes);
7014     return true;
7015   }
7016 
visitFloat(const APFloat & Val,QualType Ty,CharUnits Offset)7017   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7018     APSInt AsInt(Val.bitcastToAPInt());
7019     return visitInt(AsInt, Ty, Offset);
7020   }
7021 
7022 public:
7023   static std::optional<BitCastBuffer>
convert(EvalInfo & Info,const APValue & Src,const CastExpr * BCE)7024   convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7025     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7026     APValueToBufferConverter Converter(Info, DstSize, BCE);
7027     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7028       return std::nullopt;
7029     return Converter.Buffer;
7030   }
7031 };
7032 
7033 /// Write an BitCastBuffer into an APValue.
7034 class BufferToAPValueConverter {
7035   EvalInfo &Info;
7036   const BitCastBuffer &Buffer;
7037   const CastExpr *BCE;
7038 
BufferToAPValueConverter(EvalInfo & Info,const BitCastBuffer & Buffer,const CastExpr * BCE)7039   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7040                            const CastExpr *BCE)
7041       : Info(Info), Buffer(Buffer), BCE(BCE) {}
7042 
7043   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7044   // with an invalid type, so anything left is a deficiency on our part (FIXME).
7045   // Ideally this will be unreachable.
unsupportedType(QualType Ty)7046   std::nullopt_t unsupportedType(QualType Ty) {
7047     Info.FFDiag(BCE->getBeginLoc(),
7048                 diag::note_constexpr_bit_cast_unsupported_type)
7049         << Ty;
7050     return std::nullopt;
7051   }
7052 
unrepresentableValue(QualType Ty,const APSInt & Val)7053   std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7054     Info.FFDiag(BCE->getBeginLoc(),
7055                 diag::note_constexpr_bit_cast_unrepresentable_value)
7056         << Ty << toString(Val, /*Radix=*/10);
7057     return std::nullopt;
7058   }
7059 
visit(const BuiltinType * T,CharUnits Offset,const EnumType * EnumSugar=nullptr)7060   std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7061                                const EnumType *EnumSugar = nullptr) {
7062     if (T->isNullPtrType()) {
7063       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7064       return APValue((Expr *)nullptr,
7065                      /*Offset=*/CharUnits::fromQuantity(NullValue),
7066                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7067     }
7068 
7069     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7070 
7071     // Work around floating point types that contain unused padding bytes. This
7072     // is really just `long double` on x86, which is the only fundamental type
7073     // with padding bytes.
7074     if (T->isRealFloatingType()) {
7075       const llvm::fltSemantics &Semantics =
7076           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7077       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7078       assert(NumBits % 8 == 0);
7079       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7080       if (NumBytes != SizeOf)
7081         SizeOf = NumBytes;
7082     }
7083 
7084     SmallVector<uint8_t, 8> Bytes;
7085     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7086       // If this is std::byte or unsigned char, then its okay to store an
7087       // indeterminate value.
7088       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7089       bool IsUChar =
7090           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7091                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7092       if (!IsStdByte && !IsUChar) {
7093         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7094         Info.FFDiag(BCE->getExprLoc(),
7095                     diag::note_constexpr_bit_cast_indet_dest)
7096             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7097         return std::nullopt;
7098       }
7099 
7100       return APValue::IndeterminateValue();
7101     }
7102 
7103     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7104     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7105 
7106     if (T->isIntegralOrEnumerationType()) {
7107       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7108 
7109       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7110       if (IntWidth != Val.getBitWidth()) {
7111         APSInt Truncated = Val.trunc(IntWidth);
7112         if (Truncated.extend(Val.getBitWidth()) != Val)
7113           return unrepresentableValue(QualType(T, 0), Val);
7114         Val = Truncated;
7115       }
7116 
7117       return APValue(Val);
7118     }
7119 
7120     if (T->isRealFloatingType()) {
7121       const llvm::fltSemantics &Semantics =
7122           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7123       return APValue(APFloat(Semantics, Val));
7124     }
7125 
7126     return unsupportedType(QualType(T, 0));
7127   }
7128 
visit(const RecordType * RTy,CharUnits Offset)7129   std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7130     const RecordDecl *RD = RTy->getAsRecordDecl();
7131     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7132 
7133     unsigned NumBases = 0;
7134     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7135       NumBases = CXXRD->getNumBases();
7136 
7137     APValue ResultVal(APValue::UninitStruct(), NumBases,
7138                       std::distance(RD->field_begin(), RD->field_end()));
7139 
7140     // Visit the base classes.
7141     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7142       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7143         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7144         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7145         if (BaseDecl->isEmpty() ||
7146             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7147           continue;
7148 
7149         std::optional<APValue> SubObj = visitType(
7150             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7151         if (!SubObj)
7152           return std::nullopt;
7153         ResultVal.getStructBase(I) = *SubObj;
7154       }
7155     }
7156 
7157     // Visit the fields.
7158     unsigned FieldIdx = 0;
7159     for (FieldDecl *FD : RD->fields()) {
7160       // FIXME: We don't currently support bit-fields. A lot of the logic for
7161       // this is in CodeGen, so we need to factor it around.
7162       if (FD->isBitField()) {
7163         Info.FFDiag(BCE->getBeginLoc(),
7164                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7165         return std::nullopt;
7166       }
7167 
7168       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7169       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7170 
7171       CharUnits FieldOffset =
7172           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7173           Offset;
7174       QualType FieldTy = FD->getType();
7175       std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7176       if (!SubObj)
7177         return std::nullopt;
7178       ResultVal.getStructField(FieldIdx) = *SubObj;
7179       ++FieldIdx;
7180     }
7181 
7182     return ResultVal;
7183   }
7184 
visit(const EnumType * Ty,CharUnits Offset)7185   std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7186     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7187     assert(!RepresentationType.isNull() &&
7188            "enum forward decl should be caught by Sema");
7189     const auto *AsBuiltin =
7190         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7191     // Recurse into the underlying type. Treat std::byte transparently as
7192     // unsigned char.
7193     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7194   }
7195 
visit(const ConstantArrayType * Ty,CharUnits Offset)7196   std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7197     size_t Size = Ty->getSize().getLimitedValue();
7198     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7199 
7200     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7201     for (size_t I = 0; I != Size; ++I) {
7202       std::optional<APValue> ElementValue =
7203           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7204       if (!ElementValue)
7205         return std::nullopt;
7206       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7207     }
7208 
7209     return ArrayValue;
7210   }
7211 
visit(const Type * Ty,CharUnits Offset)7212   std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7213     return unsupportedType(QualType(Ty, 0));
7214   }
7215 
visitType(QualType Ty,CharUnits Offset)7216   std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7217     QualType Can = Ty.getCanonicalType();
7218 
7219     switch (Can->getTypeClass()) {
7220 #define TYPE(Class, Base)                                                      \
7221   case Type::Class:                                                            \
7222     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7223 #define ABSTRACT_TYPE(Class, Base)
7224 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7225   case Type::Class:                                                            \
7226     llvm_unreachable("non-canonical type should be impossible!");
7227 #define DEPENDENT_TYPE(Class, Base)                                            \
7228   case Type::Class:                                                            \
7229     llvm_unreachable(                                                          \
7230         "dependent types aren't supported in the constant evaluator!");
7231 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7232   case Type::Class:                                                            \
7233     llvm_unreachable("either dependent or not canonical!");
7234 #include "clang/AST/TypeNodes.inc"
7235     }
7236     llvm_unreachable("Unhandled Type::TypeClass");
7237   }
7238 
7239 public:
7240   // Pull out a full value of type DstType.
convert(EvalInfo & Info,BitCastBuffer & Buffer,const CastExpr * BCE)7241   static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7242                                         const CastExpr *BCE) {
7243     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7244     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7245   }
7246 };
7247 
checkBitCastConstexprEligibilityType(SourceLocation Loc,QualType Ty,EvalInfo * Info,const ASTContext & Ctx,bool CheckingDest)7248 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7249                                                  QualType Ty, EvalInfo *Info,
7250                                                  const ASTContext &Ctx,
7251                                                  bool CheckingDest) {
7252   Ty = Ty.getCanonicalType();
7253 
7254   auto diag = [&](int Reason) {
7255     if (Info)
7256       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7257           << CheckingDest << (Reason == 4) << Reason;
7258     return false;
7259   };
7260   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7261     if (Info)
7262       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7263           << NoteTy << Construct << Ty;
7264     return false;
7265   };
7266 
7267   if (Ty->isUnionType())
7268     return diag(0);
7269   if (Ty->isPointerType())
7270     return diag(1);
7271   if (Ty->isMemberPointerType())
7272     return diag(2);
7273   if (Ty.isVolatileQualified())
7274     return diag(3);
7275 
7276   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7277     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7278       for (CXXBaseSpecifier &BS : CXXRD->bases())
7279         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7280                                                   CheckingDest))
7281           return note(1, BS.getType(), BS.getBeginLoc());
7282     }
7283     for (FieldDecl *FD : Record->fields()) {
7284       if (FD->getType()->isReferenceType())
7285         return diag(4);
7286       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7287                                                 CheckingDest))
7288         return note(0, FD->getType(), FD->getBeginLoc());
7289     }
7290   }
7291 
7292   if (Ty->isArrayType() &&
7293       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7294                                             Info, Ctx, CheckingDest))
7295     return false;
7296 
7297   return true;
7298 }
7299 
checkBitCastConstexprEligibility(EvalInfo * Info,const ASTContext & Ctx,const CastExpr * BCE)7300 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7301                                              const ASTContext &Ctx,
7302                                              const CastExpr *BCE) {
7303   bool DestOK = checkBitCastConstexprEligibilityType(
7304       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7305   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7306                                 BCE->getBeginLoc(),
7307                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7308   return SourceOK;
7309 }
7310 
handleLValueToRValueBitCast(EvalInfo & Info,APValue & DestValue,APValue & SourceValue,const CastExpr * BCE)7311 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7312                                         APValue &SourceValue,
7313                                         const CastExpr *BCE) {
7314   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7315          "no host or target supports non 8-bit chars");
7316   assert(SourceValue.isLValue() &&
7317          "LValueToRValueBitcast requires an lvalue operand!");
7318 
7319   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7320     return false;
7321 
7322   LValue SourceLValue;
7323   APValue SourceRValue;
7324   SourceLValue.setFrom(Info.Ctx, SourceValue);
7325   if (!handleLValueToRValueConversion(
7326           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7327           SourceRValue, /*WantObjectRepresentation=*/true))
7328     return false;
7329 
7330   // Read out SourceValue into a char buffer.
7331   std::optional<BitCastBuffer> Buffer =
7332       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7333   if (!Buffer)
7334     return false;
7335 
7336   // Write out the buffer into a new APValue.
7337   std::optional<APValue> MaybeDestValue =
7338       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7339   if (!MaybeDestValue)
7340     return false;
7341 
7342   DestValue = std::move(*MaybeDestValue);
7343   return true;
7344 }
7345 
7346 template <class Derived>
7347 class ExprEvaluatorBase
7348   : public ConstStmtVisitor<Derived, bool> {
7349 private:
getDerived()7350   Derived &getDerived() { return static_cast<Derived&>(*this); }
DerivedSuccess(const APValue & V,const Expr * E)7351   bool DerivedSuccess(const APValue &V, const Expr *E) {
7352     return getDerived().Success(V, E);
7353   }
DerivedZeroInitialization(const Expr * E)7354   bool DerivedZeroInitialization(const Expr *E) {
7355     return getDerived().ZeroInitialization(E);
7356   }
7357 
7358   // Check whether a conditional operator with a non-constant condition is a
7359   // potential constant expression. If neither arm is a potential constant
7360   // expression, then the conditional operator is not either.
7361   template<typename ConditionalOperator>
CheckPotentialConstantConditional(const ConditionalOperator * E)7362   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7363     assert(Info.checkingPotentialConstantExpression());
7364 
7365     // Speculatively evaluate both arms.
7366     SmallVector<PartialDiagnosticAt, 8> Diag;
7367     {
7368       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7369       StmtVisitorTy::Visit(E->getFalseExpr());
7370       if (Diag.empty())
7371         return;
7372     }
7373 
7374     {
7375       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7376       Diag.clear();
7377       StmtVisitorTy::Visit(E->getTrueExpr());
7378       if (Diag.empty())
7379         return;
7380     }
7381 
7382     Error(E, diag::note_constexpr_conditional_never_const);
7383   }
7384 
7385 
7386   template<typename ConditionalOperator>
HandleConditionalOperator(const ConditionalOperator * E)7387   bool HandleConditionalOperator(const ConditionalOperator *E) {
7388     bool BoolResult;
7389     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7390       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7391         CheckPotentialConstantConditional(E);
7392         return false;
7393       }
7394       if (Info.noteFailure()) {
7395         StmtVisitorTy::Visit(E->getTrueExpr());
7396         StmtVisitorTy::Visit(E->getFalseExpr());
7397       }
7398       return false;
7399     }
7400 
7401     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7402     return StmtVisitorTy::Visit(EvalExpr);
7403   }
7404 
7405 protected:
7406   EvalInfo &Info;
7407   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7408   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7409 
CCEDiag(const Expr * E,diag::kind D)7410   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7411     return Info.CCEDiag(E, D);
7412   }
7413 
ZeroInitialization(const Expr * E)7414   bool ZeroInitialization(const Expr *E) { return Error(E); }
7415 
IsConstantEvaluatedBuiltinCall(const CallExpr * E)7416   bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7417     unsigned BuiltinOp = E->getBuiltinCallee();
7418     return BuiltinOp != 0 &&
7419            Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
7420   }
7421 
7422 public:
ExprEvaluatorBase(EvalInfo & Info)7423   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7424 
getEvalInfo()7425   EvalInfo &getEvalInfo() { return Info; }
7426 
7427   /// Report an evaluation error. This should only be called when an error is
7428   /// first discovered. When propagating an error, just return false.
Error(const Expr * E,diag::kind D)7429   bool Error(const Expr *E, diag::kind D) {
7430     Info.FFDiag(E, D);
7431     return false;
7432   }
Error(const Expr * E)7433   bool Error(const Expr *E) {
7434     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7435   }
7436 
VisitStmt(const Stmt *)7437   bool VisitStmt(const Stmt *) {
7438     llvm_unreachable("Expression evaluator should not be called on stmts");
7439   }
VisitExpr(const Expr * E)7440   bool VisitExpr(const Expr *E) {
7441     return Error(E);
7442   }
7443 
VisitConstantExpr(const ConstantExpr * E)7444   bool VisitConstantExpr(const ConstantExpr *E) {
7445     if (E->hasAPValueResult())
7446       return DerivedSuccess(E->getAPValueResult(), E);
7447 
7448     return StmtVisitorTy::Visit(E->getSubExpr());
7449   }
7450 
VisitParenExpr(const ParenExpr * E)7451   bool VisitParenExpr(const ParenExpr *E)
7452     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitUnaryExtension(const UnaryOperator * E)7453   bool VisitUnaryExtension(const UnaryOperator *E)
7454     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitUnaryPlus(const UnaryOperator * E)7455   bool VisitUnaryPlus(const UnaryOperator *E)
7456     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitChooseExpr(const ChooseExpr * E)7457   bool VisitChooseExpr(const ChooseExpr *E)
7458     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
VisitGenericSelectionExpr(const GenericSelectionExpr * E)7459   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7460     { return StmtVisitorTy::Visit(E->getResultExpr()); }
VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr * E)7461   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7462     { return StmtVisitorTy::Visit(E->getReplacement()); }
VisitCXXDefaultArgExpr(const CXXDefaultArgExpr * E)7463   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7464     TempVersionRAII RAII(*Info.CurrentCall);
7465     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7466     return StmtVisitorTy::Visit(E->getExpr());
7467   }
VisitCXXDefaultInitExpr(const CXXDefaultInitExpr * E)7468   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7469     TempVersionRAII RAII(*Info.CurrentCall);
7470     // The initializer may not have been parsed yet, or might be erroneous.
7471     if (!E->getExpr())
7472       return Error(E);
7473     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7474     return StmtVisitorTy::Visit(E->getExpr());
7475   }
7476 
VisitExprWithCleanups(const ExprWithCleanups * E)7477   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7478     FullExpressionRAII Scope(Info);
7479     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7480   }
7481 
7482   // Temporaries are registered when created, so we don't care about
7483   // CXXBindTemporaryExpr.
VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr * E)7484   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7485     return StmtVisitorTy::Visit(E->getSubExpr());
7486   }
7487 
VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr * E)7488   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7489     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7490     return static_cast<Derived*>(this)->VisitCastExpr(E);
7491   }
VisitCXXDynamicCastExpr(const CXXDynamicCastExpr * E)7492   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7493     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7494       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7495     return static_cast<Derived*>(this)->VisitCastExpr(E);
7496   }
VisitBuiltinBitCastExpr(const BuiltinBitCastExpr * E)7497   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7498     return static_cast<Derived*>(this)->VisitCastExpr(E);
7499   }
7500 
VisitBinaryOperator(const BinaryOperator * E)7501   bool VisitBinaryOperator(const BinaryOperator *E) {
7502     switch (E->getOpcode()) {
7503     default:
7504       return Error(E);
7505 
7506     case BO_Comma:
7507       VisitIgnoredValue(E->getLHS());
7508       return StmtVisitorTy::Visit(E->getRHS());
7509 
7510     case BO_PtrMemD:
7511     case BO_PtrMemI: {
7512       LValue Obj;
7513       if (!HandleMemberPointerAccess(Info, E, Obj))
7514         return false;
7515       APValue Result;
7516       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7517         return false;
7518       return DerivedSuccess(Result, E);
7519     }
7520     }
7521   }
7522 
VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator * E)7523   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7524     return StmtVisitorTy::Visit(E->getSemanticForm());
7525   }
7526 
VisitBinaryConditionalOperator(const BinaryConditionalOperator * E)7527   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7528     // Evaluate and cache the common expression. We treat it as a temporary,
7529     // even though it's not quite the same thing.
7530     LValue CommonLV;
7531     if (!Evaluate(Info.CurrentCall->createTemporary(
7532                       E->getOpaqueValue(),
7533                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7534                       ScopeKind::FullExpression, CommonLV),
7535                   Info, E->getCommon()))
7536       return false;
7537 
7538     return HandleConditionalOperator(E);
7539   }
7540 
VisitConditionalOperator(const ConditionalOperator * E)7541   bool VisitConditionalOperator(const ConditionalOperator *E) {
7542     bool IsBcpCall = false;
7543     // If the condition (ignoring parens) is a __builtin_constant_p call,
7544     // the result is a constant expression if it can be folded without
7545     // side-effects. This is an important GNU extension. See GCC PR38377
7546     // for discussion.
7547     if (const CallExpr *CallCE =
7548           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7549       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7550         IsBcpCall = true;
7551 
7552     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7553     // constant expression; we can't check whether it's potentially foldable.
7554     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7555     // it would return 'false' in this mode.
7556     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7557       return false;
7558 
7559     FoldConstant Fold(Info, IsBcpCall);
7560     if (!HandleConditionalOperator(E)) {
7561       Fold.keepDiagnostics();
7562       return false;
7563     }
7564 
7565     return true;
7566   }
7567 
VisitOpaqueValueExpr(const OpaqueValueExpr * E)7568   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7569     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7570       return DerivedSuccess(*Value, E);
7571 
7572     const Expr *Source = E->getSourceExpr();
7573     if (!Source)
7574       return Error(E);
7575     if (Source == E) {
7576       assert(0 && "OpaqueValueExpr recursively refers to itself");
7577       return Error(E);
7578     }
7579     return StmtVisitorTy::Visit(Source);
7580   }
7581 
VisitPseudoObjectExpr(const PseudoObjectExpr * E)7582   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7583     for (const Expr *SemE : E->semantics()) {
7584       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7585         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7586         // result expression: there could be two different LValues that would
7587         // refer to the same object in that case, and we can't model that.
7588         if (SemE == E->getResultExpr())
7589           return Error(E);
7590 
7591         // Unique OVEs get evaluated if and when we encounter them when
7592         // emitting the rest of the semantic form, rather than eagerly.
7593         if (OVE->isUnique())
7594           continue;
7595 
7596         LValue LV;
7597         if (!Evaluate(Info.CurrentCall->createTemporary(
7598                           OVE, getStorageType(Info.Ctx, OVE),
7599                           ScopeKind::FullExpression, LV),
7600                       Info, OVE->getSourceExpr()))
7601           return false;
7602       } else if (SemE == E->getResultExpr()) {
7603         if (!StmtVisitorTy::Visit(SemE))
7604           return false;
7605       } else {
7606         if (!EvaluateIgnoredValue(Info, SemE))
7607           return false;
7608       }
7609     }
7610     return true;
7611   }
7612 
VisitCallExpr(const CallExpr * E)7613   bool VisitCallExpr(const CallExpr *E) {
7614     APValue Result;
7615     if (!handleCallExpr(E, Result, nullptr))
7616       return false;
7617     return DerivedSuccess(Result, E);
7618   }
7619 
handleCallExpr(const CallExpr * E,APValue & Result,const LValue * ResultSlot)7620   bool handleCallExpr(const CallExpr *E, APValue &Result,
7621                      const LValue *ResultSlot) {
7622     CallScopeRAII CallScope(Info);
7623 
7624     const Expr *Callee = E->getCallee()->IgnoreParens();
7625     QualType CalleeType = Callee->getType();
7626 
7627     const FunctionDecl *FD = nullptr;
7628     LValue *This = nullptr, ThisVal;
7629     auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7630     bool HasQualifier = false;
7631 
7632     CallRef Call;
7633 
7634     // Extract function decl and 'this' pointer from the callee.
7635     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7636       const CXXMethodDecl *Member = nullptr;
7637       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7638         // Explicit bound member calls, such as x.f() or p->g();
7639         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7640           return false;
7641         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7642         if (!Member)
7643           return Error(Callee);
7644         This = &ThisVal;
7645         HasQualifier = ME->hasQualifier();
7646       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7647         // Indirect bound member calls ('.*' or '->*').
7648         const ValueDecl *D =
7649             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7650         if (!D)
7651           return false;
7652         Member = dyn_cast<CXXMethodDecl>(D);
7653         if (!Member)
7654           return Error(Callee);
7655         This = &ThisVal;
7656       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7657         if (!Info.getLangOpts().CPlusPlus20)
7658           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7659         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7660                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7661       } else
7662         return Error(Callee);
7663       FD = Member;
7664     } else if (CalleeType->isFunctionPointerType()) {
7665       LValue CalleeLV;
7666       if (!EvaluatePointer(Callee, CalleeLV, Info))
7667         return false;
7668 
7669       if (!CalleeLV.getLValueOffset().isZero())
7670         return Error(Callee);
7671       FD = dyn_cast_or_null<FunctionDecl>(
7672           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7673       if (!FD)
7674         return Error(Callee);
7675       // Don't call function pointers which have been cast to some other type.
7676       // Per DR (no number yet), the caller and callee can differ in noexcept.
7677       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7678         CalleeType->getPointeeType(), FD->getType())) {
7679         return Error(E);
7680       }
7681 
7682       // For an (overloaded) assignment expression, evaluate the RHS before the
7683       // LHS.
7684       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7685       if (OCE && OCE->isAssignmentOp()) {
7686         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7687         Call = Info.CurrentCall->createCall(FD);
7688         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7689                           Info, FD, /*RightToLeft=*/true))
7690           return false;
7691       }
7692 
7693       // Overloaded operator calls to member functions are represented as normal
7694       // calls with '*this' as the first argument.
7695       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7696       if (MD && !MD->isStatic()) {
7697         // FIXME: When selecting an implicit conversion for an overloaded
7698         // operator delete, we sometimes try to evaluate calls to conversion
7699         // operators without a 'this' parameter!
7700         if (Args.empty())
7701           return Error(E);
7702 
7703         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7704           return false;
7705         This = &ThisVal;
7706 
7707         // If this is syntactically a simple assignment using a trivial
7708         // assignment operator, start the lifetimes of union members as needed,
7709         // per C++20 [class.union]5.
7710         if (Info.getLangOpts().CPlusPlus20 && OCE &&
7711             OCE->getOperator() == OO_Equal && MD->isTrivial() &&
7712             !HandleUnionActiveMemberChange(Info, Args[0], ThisVal))
7713           return false;
7714 
7715         Args = Args.slice(1);
7716       } else if (MD && MD->isLambdaStaticInvoker()) {
7717         // Map the static invoker for the lambda back to the call operator.
7718         // Conveniently, we don't have to slice out the 'this' argument (as is
7719         // being done for the non-static case), since a static member function
7720         // doesn't have an implicit argument passed in.
7721         const CXXRecordDecl *ClosureClass = MD->getParent();
7722         assert(
7723             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7724             "Number of captures must be zero for conversion to function-ptr");
7725 
7726         const CXXMethodDecl *LambdaCallOp =
7727             ClosureClass->getLambdaCallOperator();
7728 
7729         // Set 'FD', the function that will be called below, to the call
7730         // operator.  If the closure object represents a generic lambda, find
7731         // the corresponding specialization of the call operator.
7732 
7733         if (ClosureClass->isGenericLambda()) {
7734           assert(MD->isFunctionTemplateSpecialization() &&
7735                  "A generic lambda's static-invoker function must be a "
7736                  "template specialization");
7737           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7738           FunctionTemplateDecl *CallOpTemplate =
7739               LambdaCallOp->getDescribedFunctionTemplate();
7740           void *InsertPos = nullptr;
7741           FunctionDecl *CorrespondingCallOpSpecialization =
7742               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7743           assert(CorrespondingCallOpSpecialization &&
7744                  "We must always have a function call operator specialization "
7745                  "that corresponds to our static invoker specialization");
7746           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7747         } else
7748           FD = LambdaCallOp;
7749       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7750         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7751             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7752           LValue Ptr;
7753           if (!HandleOperatorNewCall(Info, E, Ptr))
7754             return false;
7755           Ptr.moveInto(Result);
7756           return CallScope.destroy();
7757         } else {
7758           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7759         }
7760       }
7761     } else
7762       return Error(E);
7763 
7764     // Evaluate the arguments now if we've not already done so.
7765     if (!Call) {
7766       Call = Info.CurrentCall->createCall(FD);
7767       if (!EvaluateArgs(Args, Call, Info, FD))
7768         return false;
7769     }
7770 
7771     SmallVector<QualType, 4> CovariantAdjustmentPath;
7772     if (This) {
7773       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7774       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7775         // Perform virtual dispatch, if necessary.
7776         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7777                                    CovariantAdjustmentPath);
7778         if (!FD)
7779           return false;
7780       } else {
7781         // Check that the 'this' pointer points to an object of the right type.
7782         // FIXME: If this is an assignment operator call, we may need to change
7783         // the active union member before we check this.
7784         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7785           return false;
7786       }
7787     }
7788 
7789     // Destructor calls are different enough that they have their own codepath.
7790     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7791       assert(This && "no 'this' pointer for destructor call");
7792       return HandleDestruction(Info, E, *This,
7793                                Info.Ctx.getRecordType(DD->getParent())) &&
7794              CallScope.destroy();
7795     }
7796 
7797     const FunctionDecl *Definition = nullptr;
7798     Stmt *Body = FD->getBody(Definition);
7799 
7800     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7801         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7802                             Body, Info, Result, ResultSlot))
7803       return false;
7804 
7805     if (!CovariantAdjustmentPath.empty() &&
7806         !HandleCovariantReturnAdjustment(Info, E, Result,
7807                                          CovariantAdjustmentPath))
7808       return false;
7809 
7810     return CallScope.destroy();
7811   }
7812 
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)7813   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7814     return StmtVisitorTy::Visit(E->getInitializer());
7815   }
VisitInitListExpr(const InitListExpr * E)7816   bool VisitInitListExpr(const InitListExpr *E) {
7817     if (E->getNumInits() == 0)
7818       return DerivedZeroInitialization(E);
7819     if (E->getNumInits() == 1)
7820       return StmtVisitorTy::Visit(E->getInit(0));
7821     return Error(E);
7822   }
VisitImplicitValueInitExpr(const ImplicitValueInitExpr * E)7823   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7824     return DerivedZeroInitialization(E);
7825   }
VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr * E)7826   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7827     return DerivedZeroInitialization(E);
7828   }
VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr * E)7829   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7830     return DerivedZeroInitialization(E);
7831   }
7832 
7833   /// A member expression where the object is a prvalue is itself a prvalue.
VisitMemberExpr(const MemberExpr * E)7834   bool VisitMemberExpr(const MemberExpr *E) {
7835     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7836            "missing temporary materialization conversion");
7837     assert(!E->isArrow() && "missing call to bound member function?");
7838 
7839     APValue Val;
7840     if (!Evaluate(Val, Info, E->getBase()))
7841       return false;
7842 
7843     QualType BaseTy = E->getBase()->getType();
7844 
7845     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7846     if (!FD) return Error(E);
7847     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7848     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7849            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7850 
7851     // Note: there is no lvalue base here. But this case should only ever
7852     // happen in C or in C++98, where we cannot be evaluating a constexpr
7853     // constructor, which is the only case the base matters.
7854     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7855     SubobjectDesignator Designator(BaseTy);
7856     Designator.addDeclUnchecked(FD);
7857 
7858     APValue Result;
7859     return extractSubobject(Info, E, Obj, Designator, Result) &&
7860            DerivedSuccess(Result, E);
7861   }
7862 
VisitExtVectorElementExpr(const ExtVectorElementExpr * E)7863   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7864     APValue Val;
7865     if (!Evaluate(Val, Info, E->getBase()))
7866       return false;
7867 
7868     if (Val.isVector()) {
7869       SmallVector<uint32_t, 4> Indices;
7870       E->getEncodedElementAccess(Indices);
7871       if (Indices.size() == 1) {
7872         // Return scalar.
7873         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7874       } else {
7875         // Construct new APValue vector.
7876         SmallVector<APValue, 4> Elts;
7877         for (unsigned I = 0; I < Indices.size(); ++I) {
7878           Elts.push_back(Val.getVectorElt(Indices[I]));
7879         }
7880         APValue VecResult(Elts.data(), Indices.size());
7881         return DerivedSuccess(VecResult, E);
7882       }
7883     }
7884 
7885     return false;
7886   }
7887 
VisitCastExpr(const CastExpr * E)7888   bool VisitCastExpr(const CastExpr *E) {
7889     switch (E->getCastKind()) {
7890     default:
7891       break;
7892 
7893     case CK_AtomicToNonAtomic: {
7894       APValue AtomicVal;
7895       // This does not need to be done in place even for class/array types:
7896       // atomic-to-non-atomic conversion implies copying the object
7897       // representation.
7898       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7899         return false;
7900       return DerivedSuccess(AtomicVal, E);
7901     }
7902 
7903     case CK_NoOp:
7904     case CK_UserDefinedConversion:
7905       return StmtVisitorTy::Visit(E->getSubExpr());
7906 
7907     case CK_LValueToRValue: {
7908       LValue LVal;
7909       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7910         return false;
7911       APValue RVal;
7912       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7913       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7914                                           LVal, RVal))
7915         return false;
7916       return DerivedSuccess(RVal, E);
7917     }
7918     case CK_LValueToRValueBitCast: {
7919       APValue DestValue, SourceValue;
7920       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7921         return false;
7922       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7923         return false;
7924       return DerivedSuccess(DestValue, E);
7925     }
7926 
7927     case CK_AddressSpaceConversion: {
7928       APValue Value;
7929       if (!Evaluate(Value, Info, E->getSubExpr()))
7930         return false;
7931       return DerivedSuccess(Value, E);
7932     }
7933     }
7934 
7935     return Error(E);
7936   }
7937 
VisitUnaryPostInc(const UnaryOperator * UO)7938   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7939     return VisitUnaryPostIncDec(UO);
7940   }
VisitUnaryPostDec(const UnaryOperator * UO)7941   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7942     return VisitUnaryPostIncDec(UO);
7943   }
VisitUnaryPostIncDec(const UnaryOperator * UO)7944   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7945     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7946       return Error(UO);
7947 
7948     LValue LVal;
7949     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7950       return false;
7951     APValue RVal;
7952     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7953                       UO->isIncrementOp(), &RVal))
7954       return false;
7955     return DerivedSuccess(RVal, UO);
7956   }
7957 
VisitStmtExpr(const StmtExpr * E)7958   bool VisitStmtExpr(const StmtExpr *E) {
7959     // We will have checked the full-expressions inside the statement expression
7960     // when they were completed, and don't need to check them again now.
7961     llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
7962                                           false);
7963 
7964     const CompoundStmt *CS = E->getSubStmt();
7965     if (CS->body_empty())
7966       return true;
7967 
7968     BlockScopeRAII Scope(Info);
7969     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7970                                            BE = CS->body_end();
7971          /**/; ++BI) {
7972       if (BI + 1 == BE) {
7973         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7974         if (!FinalExpr) {
7975           Info.FFDiag((*BI)->getBeginLoc(),
7976                       diag::note_constexpr_stmt_expr_unsupported);
7977           return false;
7978         }
7979         return this->Visit(FinalExpr) && Scope.destroy();
7980       }
7981 
7982       APValue ReturnValue;
7983       StmtResult Result = { ReturnValue, nullptr };
7984       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7985       if (ESR != ESR_Succeeded) {
7986         // FIXME: If the statement-expression terminated due to 'return',
7987         // 'break', or 'continue', it would be nice to propagate that to
7988         // the outer statement evaluation rather than bailing out.
7989         if (ESR != ESR_Failed)
7990           Info.FFDiag((*BI)->getBeginLoc(),
7991                       diag::note_constexpr_stmt_expr_unsupported);
7992         return false;
7993       }
7994     }
7995 
7996     llvm_unreachable("Return from function from the loop above.");
7997   }
7998 
7999   /// Visit a value which is evaluated, but whose value is ignored.
VisitIgnoredValue(const Expr * E)8000   void VisitIgnoredValue(const Expr *E) {
8001     EvaluateIgnoredValue(Info, E);
8002   }
8003 
8004   /// Potentially visit a MemberExpr's base expression.
VisitIgnoredBaseExpression(const Expr * E)8005   void VisitIgnoredBaseExpression(const Expr *E) {
8006     // While MSVC doesn't evaluate the base expression, it does diagnose the
8007     // presence of side-effecting behavior.
8008     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8009       return;
8010     VisitIgnoredValue(E);
8011   }
8012 };
8013 
8014 } // namespace
8015 
8016 //===----------------------------------------------------------------------===//
8017 // Common base class for lvalue and temporary evaluation.
8018 //===----------------------------------------------------------------------===//
8019 namespace {
8020 template<class Derived>
8021 class LValueExprEvaluatorBase
8022   : public ExprEvaluatorBase<Derived> {
8023 protected:
8024   LValue &Result;
8025   bool InvalidBaseOK;
8026   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8027   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8028 
Success(APValue::LValueBase B)8029   bool Success(APValue::LValueBase B) {
8030     Result.set(B);
8031     return true;
8032   }
8033 
evaluatePointer(const Expr * E,LValue & Result)8034   bool evaluatePointer(const Expr *E, LValue &Result) {
8035     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8036   }
8037 
8038 public:
LValueExprEvaluatorBase(EvalInfo & Info,LValue & Result,bool InvalidBaseOK)8039   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8040       : ExprEvaluatorBaseTy(Info), Result(Result),
8041         InvalidBaseOK(InvalidBaseOK) {}
8042 
Success(const APValue & V,const Expr * E)8043   bool Success(const APValue &V, const Expr *E) {
8044     Result.setFrom(this->Info.Ctx, V);
8045     return true;
8046   }
8047 
VisitMemberExpr(const MemberExpr * E)8048   bool VisitMemberExpr(const MemberExpr *E) {
8049     // Handle non-static data members.
8050     QualType BaseTy;
8051     bool EvalOK;
8052     if (E->isArrow()) {
8053       EvalOK = evaluatePointer(E->getBase(), Result);
8054       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8055     } else if (E->getBase()->isPRValue()) {
8056       assert(E->getBase()->getType()->isRecordType());
8057       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8058       BaseTy = E->getBase()->getType();
8059     } else {
8060       EvalOK = this->Visit(E->getBase());
8061       BaseTy = E->getBase()->getType();
8062     }
8063     if (!EvalOK) {
8064       if (!InvalidBaseOK)
8065         return false;
8066       Result.setInvalid(E);
8067       return true;
8068     }
8069 
8070     const ValueDecl *MD = E->getMemberDecl();
8071     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8072       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8073              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8074       (void)BaseTy;
8075       if (!HandleLValueMember(this->Info, E, Result, FD))
8076         return false;
8077     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8078       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8079         return false;
8080     } else
8081       return this->Error(E);
8082 
8083     if (MD->getType()->isReferenceType()) {
8084       APValue RefValue;
8085       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8086                                           RefValue))
8087         return false;
8088       return Success(RefValue, E);
8089     }
8090     return true;
8091   }
8092 
VisitBinaryOperator(const BinaryOperator * E)8093   bool VisitBinaryOperator(const BinaryOperator *E) {
8094     switch (E->getOpcode()) {
8095     default:
8096       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8097 
8098     case BO_PtrMemD:
8099     case BO_PtrMemI:
8100       return HandleMemberPointerAccess(this->Info, E, Result);
8101     }
8102   }
8103 
VisitCastExpr(const CastExpr * E)8104   bool VisitCastExpr(const CastExpr *E) {
8105     switch (E->getCastKind()) {
8106     default:
8107       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8108 
8109     case CK_DerivedToBase:
8110     case CK_UncheckedDerivedToBase:
8111       if (!this->Visit(E->getSubExpr()))
8112         return false;
8113 
8114       // Now figure out the necessary offset to add to the base LV to get from
8115       // the derived class to the base class.
8116       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8117                                   Result);
8118     }
8119   }
8120 };
8121 }
8122 
8123 //===----------------------------------------------------------------------===//
8124 // LValue Evaluation
8125 //
8126 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8127 // function designators (in C), decl references to void objects (in C), and
8128 // temporaries (if building with -Wno-address-of-temporary).
8129 //
8130 // LValue evaluation produces values comprising a base expression of one of the
8131 // following types:
8132 // - Declarations
8133 //  * VarDecl
8134 //  * FunctionDecl
8135 // - Literals
8136 //  * CompoundLiteralExpr in C (and in global scope in C++)
8137 //  * StringLiteral
8138 //  * PredefinedExpr
8139 //  * ObjCStringLiteralExpr
8140 //  * ObjCEncodeExpr
8141 //  * AddrLabelExpr
8142 //  * BlockExpr
8143 //  * CallExpr for a MakeStringConstant builtin
8144 // - typeid(T) expressions, as TypeInfoLValues
8145 // - Locals and temporaries
8146 //  * MaterializeTemporaryExpr
8147 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8148 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8149 //    from the AST (FIXME).
8150 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8151 //    CallIndex, for a lifetime-extended temporary.
8152 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8153 //    immediate invocation.
8154 // plus an offset in bytes.
8155 //===----------------------------------------------------------------------===//
8156 namespace {
8157 class LValueExprEvaluator
8158   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8159 public:
LValueExprEvaluator(EvalInfo & Info,LValue & Result,bool InvalidBaseOK)8160   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8161     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8162 
8163   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8164   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8165 
8166   bool VisitCallExpr(const CallExpr *E);
8167   bool VisitDeclRefExpr(const DeclRefExpr *E);
VisitPredefinedExpr(const PredefinedExpr * E)8168   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8169   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8170   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8171   bool VisitMemberExpr(const MemberExpr *E);
VisitStringLiteral(const StringLiteral * E)8172   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
VisitObjCEncodeExpr(const ObjCEncodeExpr * E)8173   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8174   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8175   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8176   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8177   bool VisitUnaryDeref(const UnaryOperator *E);
8178   bool VisitUnaryReal(const UnaryOperator *E);
8179   bool VisitUnaryImag(const UnaryOperator *E);
VisitUnaryPreInc(const UnaryOperator * UO)8180   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8181     return VisitUnaryPreIncDec(UO);
8182   }
VisitUnaryPreDec(const UnaryOperator * UO)8183   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8184     return VisitUnaryPreIncDec(UO);
8185   }
8186   bool VisitBinAssign(const BinaryOperator *BO);
8187   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8188 
VisitCastExpr(const CastExpr * E)8189   bool VisitCastExpr(const CastExpr *E) {
8190     switch (E->getCastKind()) {
8191     default:
8192       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8193 
8194     case CK_LValueBitCast:
8195       this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8196           << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8197       if (!Visit(E->getSubExpr()))
8198         return false;
8199       Result.Designator.setInvalid();
8200       return true;
8201 
8202     case CK_BaseToDerived:
8203       if (!Visit(E->getSubExpr()))
8204         return false;
8205       return HandleBaseToDerivedCast(Info, E, Result);
8206 
8207     case CK_Dynamic:
8208       if (!Visit(E->getSubExpr()))
8209         return false;
8210       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8211     }
8212   }
8213 };
8214 } // end anonymous namespace
8215 
8216 /// Evaluate an expression as an lvalue. This can be legitimately called on
8217 /// expressions which are not glvalues, in three cases:
8218 ///  * function designators in C, and
8219 ///  * "extern void" objects
8220 ///  * @selector() expressions in Objective-C
EvaluateLValue(const Expr * E,LValue & Result,EvalInfo & Info,bool InvalidBaseOK)8221 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8222                            bool InvalidBaseOK) {
8223   assert(!E->isValueDependent());
8224   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8225          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
8226   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8227 }
8228 
VisitDeclRefExpr(const DeclRefExpr * E)8229 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8230   const NamedDecl *D = E->getDecl();
8231   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
8232           UnnamedGlobalConstantDecl>(D))
8233     return Success(cast<ValueDecl>(D));
8234   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8235     return VisitVarDecl(E, VD);
8236   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8237     return Visit(BD->getBinding());
8238   return Error(E);
8239 }
8240 
8241 
VisitVarDecl(const Expr * E,const VarDecl * VD)8242 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8243 
8244   // If we are within a lambda's call operator, check whether the 'VD' referred
8245   // to within 'E' actually represents a lambda-capture that maps to a
8246   // data-member/field within the closure object, and if so, evaluate to the
8247   // field or what the field refers to.
8248   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8249       isa<DeclRefExpr>(E) &&
8250       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8251     // We don't always have a complete capture-map when checking or inferring if
8252     // the function call operator meets the requirements of a constexpr function
8253     // - but we don't need to evaluate the captures to determine constexprness
8254     // (dcl.constexpr C++17).
8255     if (Info.checkingPotentialConstantExpression())
8256       return false;
8257 
8258     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8259       // Start with 'Result' referring to the complete closure object...
8260       Result = *Info.CurrentCall->This;
8261       // ... then update it to refer to the field of the closure object
8262       // that represents the capture.
8263       if (!HandleLValueMember(Info, E, Result, FD))
8264         return false;
8265       // And if the field is of reference type, update 'Result' to refer to what
8266       // the field refers to.
8267       if (FD->getType()->isReferenceType()) {
8268         APValue RVal;
8269         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8270                                             RVal))
8271           return false;
8272         Result.setFrom(Info.Ctx, RVal);
8273       }
8274       return true;
8275     }
8276   }
8277 
8278   CallStackFrame *Frame = nullptr;
8279   unsigned Version = 0;
8280   if (VD->hasLocalStorage()) {
8281     // Only if a local variable was declared in the function currently being
8282     // evaluated, do we expect to be able to find its value in the current
8283     // frame. (Otherwise it was likely declared in an enclosing context and
8284     // could either have a valid evaluatable value (for e.g. a constexpr
8285     // variable) or be ill-formed (and trigger an appropriate evaluation
8286     // diagnostic)).
8287     CallStackFrame *CurrFrame = Info.CurrentCall;
8288     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8289       // Function parameters are stored in some caller's frame. (Usually the
8290       // immediate caller, but for an inherited constructor they may be more
8291       // distant.)
8292       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8293         if (CurrFrame->Arguments) {
8294           VD = CurrFrame->Arguments.getOrigParam(PVD);
8295           Frame =
8296               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8297           Version = CurrFrame->Arguments.Version;
8298         }
8299       } else {
8300         Frame = CurrFrame;
8301         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8302       }
8303     }
8304   }
8305 
8306   if (!VD->getType()->isReferenceType()) {
8307     if (Frame) {
8308       Result.set({VD, Frame->Index, Version});
8309       return true;
8310     }
8311     return Success(VD);
8312   }
8313 
8314   if (!Info.getLangOpts().CPlusPlus11) {
8315     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8316         << VD << VD->getType();
8317     Info.Note(VD->getLocation(), diag::note_declared_at);
8318   }
8319 
8320   APValue *V;
8321   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8322     return false;
8323   if (!V->hasValue()) {
8324     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8325     // adjust the diagnostic to say that.
8326     if (!Info.checkingPotentialConstantExpression())
8327       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8328     return false;
8329   }
8330   return Success(*V, E);
8331 }
8332 
VisitCallExpr(const CallExpr * E)8333 bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8334   if (!IsConstantEvaluatedBuiltinCall(E))
8335     return ExprEvaluatorBaseTy::VisitCallExpr(E);
8336 
8337   switch (E->getBuiltinCallee()) {
8338   default:
8339     return false;
8340   case Builtin::BIas_const:
8341   case Builtin::BIforward:
8342   case Builtin::BImove:
8343   case Builtin::BImove_if_noexcept:
8344     if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8345       return Visit(E->getArg(0));
8346     break;
8347   }
8348 
8349   return ExprEvaluatorBaseTy::VisitCallExpr(E);
8350 }
8351 
VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr * E)8352 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8353     const MaterializeTemporaryExpr *E) {
8354   // Walk through the expression to find the materialized temporary itself.
8355   SmallVector<const Expr *, 2> CommaLHSs;
8356   SmallVector<SubobjectAdjustment, 2> Adjustments;
8357   const Expr *Inner =
8358       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8359 
8360   // If we passed any comma operators, evaluate their LHSs.
8361   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8362     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8363       return false;
8364 
8365   // A materialized temporary with static storage duration can appear within the
8366   // result of a constant expression evaluation, so we need to preserve its
8367   // value for use outside this evaluation.
8368   APValue *Value;
8369   if (E->getStorageDuration() == SD_Static) {
8370     // FIXME: What about SD_Thread?
8371     Value = E->getOrCreateValue(true);
8372     *Value = APValue();
8373     Result.set(E);
8374   } else {
8375     Value = &Info.CurrentCall->createTemporary(
8376         E, E->getType(),
8377         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8378                                                      : ScopeKind::Block,
8379         Result);
8380   }
8381 
8382   QualType Type = Inner->getType();
8383 
8384   // Materialize the temporary itself.
8385   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8386     *Value = APValue();
8387     return false;
8388   }
8389 
8390   // Adjust our lvalue to refer to the desired subobject.
8391   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8392     --I;
8393     switch (Adjustments[I].Kind) {
8394     case SubobjectAdjustment::DerivedToBaseAdjustment:
8395       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8396                                 Type, Result))
8397         return false;
8398       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8399       break;
8400 
8401     case SubobjectAdjustment::FieldAdjustment:
8402       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8403         return false;
8404       Type = Adjustments[I].Field->getType();
8405       break;
8406 
8407     case SubobjectAdjustment::MemberPointerAdjustment:
8408       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8409                                      Adjustments[I].Ptr.RHS))
8410         return false;
8411       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8412       break;
8413     }
8414   }
8415 
8416   return true;
8417 }
8418 
8419 bool
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)8420 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8421   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8422          "lvalue compound literal in c++?");
8423   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8424   // only see this when folding in C, so there's no standard to follow here.
8425   return Success(E);
8426 }
8427 
VisitCXXTypeidExpr(const CXXTypeidExpr * E)8428 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8429   TypeInfoLValue TypeInfo;
8430 
8431   if (!E->isPotentiallyEvaluated()) {
8432     if (E->isTypeOperand())
8433       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8434     else
8435       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8436   } else {
8437     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8438       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8439         << E->getExprOperand()->getType()
8440         << E->getExprOperand()->getSourceRange();
8441     }
8442 
8443     if (!Visit(E->getExprOperand()))
8444       return false;
8445 
8446     std::optional<DynamicType> DynType =
8447         ComputeDynamicType(Info, E, Result, AK_TypeId);
8448     if (!DynType)
8449       return false;
8450 
8451     TypeInfo =
8452         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8453   }
8454 
8455   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8456 }
8457 
VisitCXXUuidofExpr(const CXXUuidofExpr * E)8458 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8459   return Success(E->getGuidDecl());
8460 }
8461 
VisitMemberExpr(const MemberExpr * E)8462 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8463   // Handle static data members.
8464   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8465     VisitIgnoredBaseExpression(E->getBase());
8466     return VisitVarDecl(E, VD);
8467   }
8468 
8469   // Handle static member functions.
8470   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8471     if (MD->isStatic()) {
8472       VisitIgnoredBaseExpression(E->getBase());
8473       return Success(MD);
8474     }
8475   }
8476 
8477   // Handle non-static data members.
8478   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8479 }
8480 
VisitArraySubscriptExpr(const ArraySubscriptExpr * E)8481 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8482   // FIXME: Deal with vectors as array subscript bases.
8483   if (E->getBase()->getType()->isVectorType() ||
8484       E->getBase()->getType()->isVLSTBuiltinType())
8485     return Error(E);
8486 
8487   APSInt Index;
8488   bool Success = true;
8489 
8490   // C++17's rules require us to evaluate the LHS first, regardless of which
8491   // side is the base.
8492   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8493     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8494                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8495       if (!Info.noteFailure())
8496         return false;
8497       Success = false;
8498     }
8499   }
8500 
8501   return Success &&
8502          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8503 }
8504 
VisitUnaryDeref(const UnaryOperator * E)8505 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8506   return evaluatePointer(E->getSubExpr(), Result);
8507 }
8508 
VisitUnaryReal(const UnaryOperator * E)8509 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8510   if (!Visit(E->getSubExpr()))
8511     return false;
8512   // __real is a no-op on scalar lvalues.
8513   if (E->getSubExpr()->getType()->isAnyComplexType())
8514     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8515   return true;
8516 }
8517 
VisitUnaryImag(const UnaryOperator * E)8518 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8519   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8520          "lvalue __imag__ on scalar?");
8521   if (!Visit(E->getSubExpr()))
8522     return false;
8523   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8524   return true;
8525 }
8526 
VisitUnaryPreIncDec(const UnaryOperator * UO)8527 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8528   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8529     return Error(UO);
8530 
8531   if (!this->Visit(UO->getSubExpr()))
8532     return false;
8533 
8534   return handleIncDec(
8535       this->Info, UO, Result, UO->getSubExpr()->getType(),
8536       UO->isIncrementOp(), nullptr);
8537 }
8538 
VisitCompoundAssignOperator(const CompoundAssignOperator * CAO)8539 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8540     const CompoundAssignOperator *CAO) {
8541   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8542     return Error(CAO);
8543 
8544   bool Success = true;
8545 
8546   // C++17 onwards require that we evaluate the RHS first.
8547   APValue RHS;
8548   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8549     if (!Info.noteFailure())
8550       return false;
8551     Success = false;
8552   }
8553 
8554   // The overall lvalue result is the result of evaluating the LHS.
8555   if (!this->Visit(CAO->getLHS()) || !Success)
8556     return false;
8557 
8558   return handleCompoundAssignment(
8559       this->Info, CAO,
8560       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8561       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8562 }
8563 
VisitBinAssign(const BinaryOperator * E)8564 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8565   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8566     return Error(E);
8567 
8568   bool Success = true;
8569 
8570   // C++17 onwards require that we evaluate the RHS first.
8571   APValue NewVal;
8572   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8573     if (!Info.noteFailure())
8574       return false;
8575     Success = false;
8576   }
8577 
8578   if (!this->Visit(E->getLHS()) || !Success)
8579     return false;
8580 
8581   if (Info.getLangOpts().CPlusPlus20 &&
8582       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8583     return false;
8584 
8585   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8586                           NewVal);
8587 }
8588 
8589 //===----------------------------------------------------------------------===//
8590 // Pointer Evaluation
8591 //===----------------------------------------------------------------------===//
8592 
8593 /// Attempts to compute the number of bytes available at the pointer
8594 /// returned by a function with the alloc_size attribute. Returns true if we
8595 /// were successful. Places an unsigned number into `Result`.
8596 ///
8597 /// This expects the given CallExpr to be a call to a function with an
8598 /// alloc_size attribute.
getBytesReturnedByAllocSizeCall(const ASTContext & Ctx,const CallExpr * Call,llvm::APInt & Result)8599 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8600                                             const CallExpr *Call,
8601                                             llvm::APInt &Result) {
8602   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8603 
8604   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8605   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8606   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8607   if (Call->getNumArgs() <= SizeArgNo)
8608     return false;
8609 
8610   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8611     Expr::EvalResult ExprResult;
8612     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8613       return false;
8614     Into = ExprResult.Val.getInt();
8615     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8616       return false;
8617     Into = Into.zext(BitsInSizeT);
8618     return true;
8619   };
8620 
8621   APSInt SizeOfElem;
8622   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8623     return false;
8624 
8625   if (!AllocSize->getNumElemsParam().isValid()) {
8626     Result = std::move(SizeOfElem);
8627     return true;
8628   }
8629 
8630   APSInt NumberOfElems;
8631   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8632   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8633     return false;
8634 
8635   bool Overflow;
8636   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8637   if (Overflow)
8638     return false;
8639 
8640   Result = std::move(BytesAvailable);
8641   return true;
8642 }
8643 
8644 /// Convenience function. LVal's base must be a call to an alloc_size
8645 /// function.
getBytesReturnedByAllocSizeCall(const ASTContext & Ctx,const LValue & LVal,llvm::APInt & Result)8646 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8647                                             const LValue &LVal,
8648                                             llvm::APInt &Result) {
8649   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8650          "Can't get the size of a non alloc_size function");
8651   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8652   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8653   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8654 }
8655 
8656 /// Attempts to evaluate the given LValueBase as the result of a call to
8657 /// a function with the alloc_size attribute. If it was possible to do so, this
8658 /// function will return true, make Result's Base point to said function call,
8659 /// and mark Result's Base as invalid.
evaluateLValueAsAllocSize(EvalInfo & Info,APValue::LValueBase Base,LValue & Result)8660 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8661                                       LValue &Result) {
8662   if (Base.isNull())
8663     return false;
8664 
8665   // Because we do no form of static analysis, we only support const variables.
8666   //
8667   // Additionally, we can't support parameters, nor can we support static
8668   // variables (in the latter case, use-before-assign isn't UB; in the former,
8669   // we have no clue what they'll be assigned to).
8670   const auto *VD =
8671       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8672   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8673     return false;
8674 
8675   const Expr *Init = VD->getAnyInitializer();
8676   if (!Init || Init->getType().isNull())
8677     return false;
8678 
8679   const Expr *E = Init->IgnoreParens();
8680   if (!tryUnwrapAllocSizeCall(E))
8681     return false;
8682 
8683   // Store E instead of E unwrapped so that the type of the LValue's base is
8684   // what the user wanted.
8685   Result.setInvalid(E);
8686 
8687   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8688   Result.addUnsizedArray(Info, E, Pointee);
8689   return true;
8690 }
8691 
8692 namespace {
8693 class PointerExprEvaluator
8694   : public ExprEvaluatorBase<PointerExprEvaluator> {
8695   LValue &Result;
8696   bool InvalidBaseOK;
8697 
Success(const Expr * E)8698   bool Success(const Expr *E) {
8699     Result.set(E);
8700     return true;
8701   }
8702 
evaluateLValue(const Expr * E,LValue & Result)8703   bool evaluateLValue(const Expr *E, LValue &Result) {
8704     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8705   }
8706 
evaluatePointer(const Expr * E,LValue & Result)8707   bool evaluatePointer(const Expr *E, LValue &Result) {
8708     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8709   }
8710 
8711   bool visitNonBuiltinCallExpr(const CallExpr *E);
8712 public:
8713 
PointerExprEvaluator(EvalInfo & info,LValue & Result,bool InvalidBaseOK)8714   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8715       : ExprEvaluatorBaseTy(info), Result(Result),
8716         InvalidBaseOK(InvalidBaseOK) {}
8717 
Success(const APValue & V,const Expr * E)8718   bool Success(const APValue &V, const Expr *E) {
8719     Result.setFrom(Info.Ctx, V);
8720     return true;
8721   }
ZeroInitialization(const Expr * E)8722   bool ZeroInitialization(const Expr *E) {
8723     Result.setNull(Info.Ctx, E->getType());
8724     return true;
8725   }
8726 
8727   bool VisitBinaryOperator(const BinaryOperator *E);
8728   bool VisitCastExpr(const CastExpr* E);
8729   bool VisitUnaryAddrOf(const UnaryOperator *E);
VisitObjCStringLiteral(const ObjCStringLiteral * E)8730   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8731       { return Success(E); }
VisitObjCBoxedExpr(const ObjCBoxedExpr * E)8732   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8733     if (E->isExpressibleAsConstantInitializer())
8734       return Success(E);
8735     if (Info.noteFailure())
8736       EvaluateIgnoredValue(Info, E->getSubExpr());
8737     return Error(E);
8738   }
VisitAddrLabelExpr(const AddrLabelExpr * E)8739   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8740       { return Success(E); }
8741   bool VisitCallExpr(const CallExpr *E);
8742   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
VisitBlockExpr(const BlockExpr * E)8743   bool VisitBlockExpr(const BlockExpr *E) {
8744     if (!E->getBlockDecl()->hasCaptures())
8745       return Success(E);
8746     return Error(E);
8747   }
VisitCXXThisExpr(const CXXThisExpr * E)8748   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8749     // Can't look at 'this' when checking a potential constant expression.
8750     if (Info.checkingPotentialConstantExpression())
8751       return false;
8752     if (!Info.CurrentCall->This) {
8753       if (Info.getLangOpts().CPlusPlus11)
8754         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8755       else
8756         Info.FFDiag(E);
8757       return false;
8758     }
8759     Result = *Info.CurrentCall->This;
8760     // If we are inside a lambda's call operator, the 'this' expression refers
8761     // to the enclosing '*this' object (either by value or reference) which is
8762     // either copied into the closure object's field that represents the '*this'
8763     // or refers to '*this'.
8764     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8765       // Ensure we actually have captured 'this'. (an error will have
8766       // been previously reported if not).
8767       if (!Info.CurrentCall->LambdaThisCaptureField)
8768         return false;
8769 
8770       // Update 'Result' to refer to the data member/field of the closure object
8771       // that represents the '*this' capture.
8772       if (!HandleLValueMember(Info, E, Result,
8773                              Info.CurrentCall->LambdaThisCaptureField))
8774         return false;
8775       // If we captured '*this' by reference, replace the field with its referent.
8776       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8777               ->isPointerType()) {
8778         APValue RVal;
8779         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8780                                             RVal))
8781           return false;
8782 
8783         Result.setFrom(Info.Ctx, RVal);
8784       }
8785     }
8786     return true;
8787   }
8788 
8789   bool VisitCXXNewExpr(const CXXNewExpr *E);
8790 
VisitSourceLocExpr(const SourceLocExpr * E)8791   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8792     assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
8793     APValue LValResult = E->EvaluateInContext(
8794         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8795     Result.setFrom(Info.Ctx, LValResult);
8796     return true;
8797   }
8798 
VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr * E)8799   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8800     std::string ResultStr = E->ComputeName(Info.Ctx);
8801 
8802     QualType CharTy = Info.Ctx.CharTy.withConst();
8803     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8804                ResultStr.size() + 1);
8805     QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8806                                                      ArrayType::Normal, 0);
8807 
8808     StringLiteral *SL =
8809         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ordinary,
8810                               /*Pascal*/ false, ArrayTy, E->getLocation());
8811 
8812     evaluateLValue(SL, Result);
8813     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8814     return true;
8815   }
8816 
8817   // FIXME: Missing: @protocol, @selector
8818 };
8819 } // end anonymous namespace
8820 
EvaluatePointer(const Expr * E,LValue & Result,EvalInfo & Info,bool InvalidBaseOK)8821 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8822                             bool InvalidBaseOK) {
8823   assert(!E->isValueDependent());
8824   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
8825   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8826 }
8827 
VisitBinaryOperator(const BinaryOperator * E)8828 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8829   if (E->getOpcode() != BO_Add &&
8830       E->getOpcode() != BO_Sub)
8831     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8832 
8833   const Expr *PExp = E->getLHS();
8834   const Expr *IExp = E->getRHS();
8835   if (IExp->getType()->isPointerType())
8836     std::swap(PExp, IExp);
8837 
8838   bool EvalPtrOK = evaluatePointer(PExp, Result);
8839   if (!EvalPtrOK && !Info.noteFailure())
8840     return false;
8841 
8842   llvm::APSInt Offset;
8843   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8844     return false;
8845 
8846   if (E->getOpcode() == BO_Sub)
8847     negateAsSigned(Offset);
8848 
8849   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8850   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8851 }
8852 
VisitUnaryAddrOf(const UnaryOperator * E)8853 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8854   return evaluateLValue(E->getSubExpr(), Result);
8855 }
8856 
8857 // Is the provided decl 'std::source_location::current'?
IsDeclSourceLocationCurrent(const FunctionDecl * FD)8858 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
8859   if (!FD)
8860     return false;
8861   const IdentifierInfo *FnII = FD->getIdentifier();
8862   if (!FnII || !FnII->isStr("current"))
8863     return false;
8864 
8865   const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
8866   if (!RD)
8867     return false;
8868 
8869   const IdentifierInfo *ClassII = RD->getIdentifier();
8870   return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
8871 }
8872 
VisitCastExpr(const CastExpr * E)8873 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8874   const Expr *SubExpr = E->getSubExpr();
8875 
8876   switch (E->getCastKind()) {
8877   default:
8878     break;
8879   case CK_BitCast:
8880   case CK_CPointerToObjCPointerCast:
8881   case CK_BlockPointerToObjCPointerCast:
8882   case CK_AnyPointerToBlockPointerCast:
8883   case CK_AddressSpaceConversion:
8884     if (!Visit(SubExpr))
8885       return false;
8886     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8887     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8888     // also static_casts, but we disallow them as a resolution to DR1312.
8889     if (!E->getType()->isVoidPointerType()) {
8890       // In some circumstances, we permit casting from void* to cv1 T*, when the
8891       // actual pointee object is actually a cv2 T.
8892       bool VoidPtrCastMaybeOK =
8893           !Result.InvalidBase && !Result.Designator.Invalid &&
8894           !Result.IsNullPtr &&
8895           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8896                                           E->getType()->getPointeeType());
8897       // 1. We'll allow it in std::allocator::allocate, and anything which that
8898       //    calls.
8899       // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
8900       //    <source_location> header. Fixed in GCC 12 and later (2022-04-??).
8901       //    We'll allow it in the body of std::source_location::current.  GCC's
8902       //    implementation had a parameter of type `void*`, and casts from
8903       //    that back to `const __impl*` in its body.
8904       if (VoidPtrCastMaybeOK &&
8905           (Info.getStdAllocatorCaller("allocate") ||
8906            IsDeclSourceLocationCurrent(Info.CurrentCall->Callee))) {
8907         // Permitted.
8908       } else {
8909         Result.Designator.setInvalid();
8910         if (SubExpr->getType()->isVoidPointerType())
8911           CCEDiag(E, diag::note_constexpr_invalid_cast)
8912               << 3 << SubExpr->getType();
8913         else
8914           CCEDiag(E, diag::note_constexpr_invalid_cast)
8915               << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8916       }
8917     }
8918     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8919       ZeroInitialization(E);
8920     return true;
8921 
8922   case CK_DerivedToBase:
8923   case CK_UncheckedDerivedToBase:
8924     if (!evaluatePointer(E->getSubExpr(), Result))
8925       return false;
8926     if (!Result.Base && Result.Offset.isZero())
8927       return true;
8928 
8929     // Now figure out the necessary offset to add to the base LV to get from
8930     // the derived class to the base class.
8931     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8932                                   castAs<PointerType>()->getPointeeType(),
8933                                 Result);
8934 
8935   case CK_BaseToDerived:
8936     if (!Visit(E->getSubExpr()))
8937       return false;
8938     if (!Result.Base && Result.Offset.isZero())
8939       return true;
8940     return HandleBaseToDerivedCast(Info, E, Result);
8941 
8942   case CK_Dynamic:
8943     if (!Visit(E->getSubExpr()))
8944       return false;
8945     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8946 
8947   case CK_NullToPointer:
8948     VisitIgnoredValue(E->getSubExpr());
8949     return ZeroInitialization(E);
8950 
8951   case CK_IntegralToPointer: {
8952     CCEDiag(E, diag::note_constexpr_invalid_cast)
8953         << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8954 
8955     APValue Value;
8956     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8957       break;
8958 
8959     if (Value.isInt()) {
8960       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8961       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8962       Result.Base = (Expr*)nullptr;
8963       Result.InvalidBase = false;
8964       Result.Offset = CharUnits::fromQuantity(N);
8965       Result.Designator.setInvalid();
8966       Result.IsNullPtr = false;
8967       return true;
8968     } else {
8969       // Cast is of an lvalue, no need to change value.
8970       Result.setFrom(Info.Ctx, Value);
8971       return true;
8972     }
8973   }
8974 
8975   case CK_ArrayToPointerDecay: {
8976     if (SubExpr->isGLValue()) {
8977       if (!evaluateLValue(SubExpr, Result))
8978         return false;
8979     } else {
8980       APValue &Value = Info.CurrentCall->createTemporary(
8981           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8982       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8983         return false;
8984     }
8985     // The result is a pointer to the first element of the array.
8986     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8987     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8988       Result.addArray(Info, E, CAT);
8989     else
8990       Result.addUnsizedArray(Info, E, AT->getElementType());
8991     return true;
8992   }
8993 
8994   case CK_FunctionToPointerDecay:
8995     return evaluateLValue(SubExpr, Result);
8996 
8997   case CK_LValueToRValue: {
8998     LValue LVal;
8999     if (!evaluateLValue(E->getSubExpr(), LVal))
9000       return false;
9001 
9002     APValue RVal;
9003     // Note, we use the subexpression's type in order to retain cv-qualifiers.
9004     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9005                                         LVal, RVal))
9006       return InvalidBaseOK &&
9007              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9008     return Success(RVal, E);
9009   }
9010   }
9011 
9012   return ExprEvaluatorBaseTy::VisitCastExpr(E);
9013 }
9014 
GetAlignOfType(EvalInfo & Info,QualType T,UnaryExprOrTypeTrait ExprKind)9015 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
9016                                 UnaryExprOrTypeTrait ExprKind) {
9017   // C++ [expr.alignof]p3:
9018   //     When alignof is applied to a reference type, the result is the
9019   //     alignment of the referenced type.
9020   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
9021     T = Ref->getPointeeType();
9022 
9023   if (T.getQualifiers().hasUnaligned())
9024     return CharUnits::One();
9025 
9026   const bool AlignOfReturnsPreferred =
9027       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9028 
9029   // __alignof is defined to return the preferred alignment.
9030   // Before 8, clang returned the preferred alignment for alignof and _Alignof
9031   // as well.
9032   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9033     return Info.Ctx.toCharUnitsFromBits(
9034       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
9035   // alignof and _Alignof are defined to return the ABI alignment.
9036   else if (ExprKind == UETT_AlignOf)
9037     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
9038   else
9039     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9040 }
9041 
GetAlignOfExpr(EvalInfo & Info,const Expr * E,UnaryExprOrTypeTrait ExprKind)9042 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
9043                                 UnaryExprOrTypeTrait ExprKind) {
9044   E = E->IgnoreParens();
9045 
9046   // The kinds of expressions that we have special-case logic here for
9047   // should be kept up to date with the special checks for those
9048   // expressions in Sema.
9049 
9050   // alignof decl is always accepted, even if it doesn't make sense: we default
9051   // to 1 in those cases.
9052   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9053     return Info.Ctx.getDeclAlign(DRE->getDecl(),
9054                                  /*RefAsPointee*/true);
9055 
9056   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9057     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
9058                                  /*RefAsPointee*/true);
9059 
9060   return GetAlignOfType(Info, E->getType(), ExprKind);
9061 }
9062 
getBaseAlignment(EvalInfo & Info,const LValue & Value)9063 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9064   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9065     return Info.Ctx.getDeclAlign(VD);
9066   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9067     return GetAlignOfExpr(Info, E, UETT_AlignOf);
9068   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
9069 }
9070 
9071 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9072 /// __builtin_is_aligned and __builtin_assume_aligned.
getAlignmentArgument(const Expr * E,QualType ForType,EvalInfo & Info,APSInt & Alignment)9073 static bool getAlignmentArgument(const Expr *E, QualType ForType,
9074                                  EvalInfo &Info, APSInt &Alignment) {
9075   if (!EvaluateInteger(E, Alignment, Info))
9076     return false;
9077   if (Alignment < 0 || !Alignment.isPowerOf2()) {
9078     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9079     return false;
9080   }
9081   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9082   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9083   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9084     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9085         << MaxValue << ForType << Alignment;
9086     return false;
9087   }
9088   // Ensure both alignment and source value have the same bit width so that we
9089   // don't assert when computing the resulting value.
9090   APSInt ExtAlignment =
9091       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9092   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9093          "Alignment should not be changed by ext/trunc");
9094   Alignment = ExtAlignment;
9095   assert(Alignment.getBitWidth() == SrcWidth);
9096   return true;
9097 }
9098 
9099 // To be clear: this happily visits unsupported builtins. Better name welcomed.
visitNonBuiltinCallExpr(const CallExpr * E)9100 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9101   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9102     return true;
9103 
9104   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9105     return false;
9106 
9107   Result.setInvalid(E);
9108   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9109   Result.addUnsizedArray(Info, E, PointeeTy);
9110   return true;
9111 }
9112 
VisitCallExpr(const CallExpr * E)9113 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9114   if (!IsConstantEvaluatedBuiltinCall(E))
9115     return visitNonBuiltinCallExpr(E);
9116   return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9117 }
9118 
9119 // Determine if T is a character type for which we guarantee that
9120 // sizeof(T) == 1.
isOneByteCharacterType(QualType T)9121 static bool isOneByteCharacterType(QualType T) {
9122   return T->isCharType() || T->isChar8Type();
9123 }
9124 
VisitBuiltinCallExpr(const CallExpr * E,unsigned BuiltinOp)9125 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9126                                                 unsigned BuiltinOp) {
9127   if (IsNoOpCall(E))
9128     return Success(E);
9129 
9130   switch (BuiltinOp) {
9131   case Builtin::BIaddressof:
9132   case Builtin::BI__addressof:
9133   case Builtin::BI__builtin_addressof:
9134     return evaluateLValue(E->getArg(0), Result);
9135   case Builtin::BI__builtin_assume_aligned: {
9136     // We need to be very careful here because: if the pointer does not have the
9137     // asserted alignment, then the behavior is undefined, and undefined
9138     // behavior is non-constant.
9139     if (!evaluatePointer(E->getArg(0), Result))
9140       return false;
9141 
9142     LValue OffsetResult(Result);
9143     APSInt Alignment;
9144     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9145                               Alignment))
9146       return false;
9147     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9148 
9149     if (E->getNumArgs() > 2) {
9150       APSInt Offset;
9151       if (!EvaluateInteger(E->getArg(2), Offset, Info))
9152         return false;
9153 
9154       int64_t AdditionalOffset = -Offset.getZExtValue();
9155       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9156     }
9157 
9158     // If there is a base object, then it must have the correct alignment.
9159     if (OffsetResult.Base) {
9160       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9161 
9162       if (BaseAlignment < Align) {
9163         Result.Designator.setInvalid();
9164         // FIXME: Add support to Diagnostic for long / long long.
9165         CCEDiag(E->getArg(0),
9166                 diag::note_constexpr_baa_insufficient_alignment) << 0
9167           << (unsigned)BaseAlignment.getQuantity()
9168           << (unsigned)Align.getQuantity();
9169         return false;
9170       }
9171     }
9172 
9173     // The offset must also have the correct alignment.
9174     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9175       Result.Designator.setInvalid();
9176 
9177       (OffsetResult.Base
9178            ? CCEDiag(E->getArg(0),
9179                      diag::note_constexpr_baa_insufficient_alignment) << 1
9180            : CCEDiag(E->getArg(0),
9181                      diag::note_constexpr_baa_value_insufficient_alignment))
9182         << (int)OffsetResult.Offset.getQuantity()
9183         << (unsigned)Align.getQuantity();
9184       return false;
9185     }
9186 
9187     return true;
9188   }
9189   case Builtin::BI__builtin_align_up:
9190   case Builtin::BI__builtin_align_down: {
9191     if (!evaluatePointer(E->getArg(0), Result))
9192       return false;
9193     APSInt Alignment;
9194     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9195                               Alignment))
9196       return false;
9197     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9198     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9199     // For align_up/align_down, we can return the same value if the alignment
9200     // is known to be greater or equal to the requested value.
9201     if (PtrAlign.getQuantity() >= Alignment)
9202       return true;
9203 
9204     // The alignment could be greater than the minimum at run-time, so we cannot
9205     // infer much about the resulting pointer value. One case is possible:
9206     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9207     // can infer the correct index if the requested alignment is smaller than
9208     // the base alignment so we can perform the computation on the offset.
9209     if (BaseAlignment.getQuantity() >= Alignment) {
9210       assert(Alignment.getBitWidth() <= 64 &&
9211              "Cannot handle > 64-bit address-space");
9212       uint64_t Alignment64 = Alignment.getZExtValue();
9213       CharUnits NewOffset = CharUnits::fromQuantity(
9214           BuiltinOp == Builtin::BI__builtin_align_down
9215               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9216               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9217       Result.adjustOffset(NewOffset - Result.Offset);
9218       // TODO: diagnose out-of-bounds values/only allow for arrays?
9219       return true;
9220     }
9221     // Otherwise, we cannot constant-evaluate the result.
9222     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9223         << Alignment;
9224     return false;
9225   }
9226   case Builtin::BI__builtin_operator_new:
9227     return HandleOperatorNewCall(Info, E, Result);
9228   case Builtin::BI__builtin_launder:
9229     return evaluatePointer(E->getArg(0), Result);
9230   case Builtin::BIstrchr:
9231   case Builtin::BIwcschr:
9232   case Builtin::BImemchr:
9233   case Builtin::BIwmemchr:
9234     if (Info.getLangOpts().CPlusPlus11)
9235       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9236           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9237           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9238     else
9239       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9240     [[fallthrough]];
9241   case Builtin::BI__builtin_strchr:
9242   case Builtin::BI__builtin_wcschr:
9243   case Builtin::BI__builtin_memchr:
9244   case Builtin::BI__builtin_char_memchr:
9245   case Builtin::BI__builtin_wmemchr: {
9246     if (!Visit(E->getArg(0)))
9247       return false;
9248     APSInt Desired;
9249     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9250       return false;
9251     uint64_t MaxLength = uint64_t(-1);
9252     if (BuiltinOp != Builtin::BIstrchr &&
9253         BuiltinOp != Builtin::BIwcschr &&
9254         BuiltinOp != Builtin::BI__builtin_strchr &&
9255         BuiltinOp != Builtin::BI__builtin_wcschr) {
9256       APSInt N;
9257       if (!EvaluateInteger(E->getArg(2), N, Info))
9258         return false;
9259       MaxLength = N.getExtValue();
9260     }
9261     // We cannot find the value if there are no candidates to match against.
9262     if (MaxLength == 0u)
9263       return ZeroInitialization(E);
9264     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9265         Result.Designator.Invalid)
9266       return false;
9267     QualType CharTy = Result.Designator.getType(Info.Ctx);
9268     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9269                      BuiltinOp == Builtin::BI__builtin_memchr;
9270     assert(IsRawByte ||
9271            Info.Ctx.hasSameUnqualifiedType(
9272                CharTy, E->getArg(0)->getType()->getPointeeType()));
9273     // Pointers to const void may point to objects of incomplete type.
9274     if (IsRawByte && CharTy->isIncompleteType()) {
9275       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9276       return false;
9277     }
9278     // Give up on byte-oriented matching against multibyte elements.
9279     // FIXME: We can compare the bytes in the correct order.
9280     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9281       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9282           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
9283           << CharTy;
9284       return false;
9285     }
9286     // Figure out what value we're actually looking for (after converting to
9287     // the corresponding unsigned type if necessary).
9288     uint64_t DesiredVal;
9289     bool StopAtNull = false;
9290     switch (BuiltinOp) {
9291     case Builtin::BIstrchr:
9292     case Builtin::BI__builtin_strchr:
9293       // strchr compares directly to the passed integer, and therefore
9294       // always fails if given an int that is not a char.
9295       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9296                                                   E->getArg(1)->getType(),
9297                                                   Desired),
9298                                Desired))
9299         return ZeroInitialization(E);
9300       StopAtNull = true;
9301       [[fallthrough]];
9302     case Builtin::BImemchr:
9303     case Builtin::BI__builtin_memchr:
9304     case Builtin::BI__builtin_char_memchr:
9305       // memchr compares by converting both sides to unsigned char. That's also
9306       // correct for strchr if we get this far (to cope with plain char being
9307       // unsigned in the strchr case).
9308       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9309       break;
9310 
9311     case Builtin::BIwcschr:
9312     case Builtin::BI__builtin_wcschr:
9313       StopAtNull = true;
9314       [[fallthrough]];
9315     case Builtin::BIwmemchr:
9316     case Builtin::BI__builtin_wmemchr:
9317       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9318       DesiredVal = Desired.getZExtValue();
9319       break;
9320     }
9321 
9322     for (; MaxLength; --MaxLength) {
9323       APValue Char;
9324       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9325           !Char.isInt())
9326         return false;
9327       if (Char.getInt().getZExtValue() == DesiredVal)
9328         return true;
9329       if (StopAtNull && !Char.getInt())
9330         break;
9331       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9332         return false;
9333     }
9334     // Not found: return nullptr.
9335     return ZeroInitialization(E);
9336   }
9337 
9338   case Builtin::BImemcpy:
9339   case Builtin::BImemmove:
9340   case Builtin::BIwmemcpy:
9341   case Builtin::BIwmemmove:
9342     if (Info.getLangOpts().CPlusPlus11)
9343       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9344           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9345           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9346     else
9347       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9348     [[fallthrough]];
9349   case Builtin::BI__builtin_memcpy:
9350   case Builtin::BI__builtin_memmove:
9351   case Builtin::BI__builtin_wmemcpy:
9352   case Builtin::BI__builtin_wmemmove: {
9353     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9354                  BuiltinOp == Builtin::BIwmemmove ||
9355                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9356                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9357     bool Move = BuiltinOp == Builtin::BImemmove ||
9358                 BuiltinOp == Builtin::BIwmemmove ||
9359                 BuiltinOp == Builtin::BI__builtin_memmove ||
9360                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9361 
9362     // The result of mem* is the first argument.
9363     if (!Visit(E->getArg(0)))
9364       return false;
9365     LValue Dest = Result;
9366 
9367     LValue Src;
9368     if (!EvaluatePointer(E->getArg(1), Src, Info))
9369       return false;
9370 
9371     APSInt N;
9372     if (!EvaluateInteger(E->getArg(2), N, Info))
9373       return false;
9374     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9375 
9376     // If the size is zero, we treat this as always being a valid no-op.
9377     // (Even if one of the src and dest pointers is null.)
9378     if (!N)
9379       return true;
9380 
9381     // Otherwise, if either of the operands is null, we can't proceed. Don't
9382     // try to determine the type of the copied objects, because there aren't
9383     // any.
9384     if (!Src.Base || !Dest.Base) {
9385       APValue Val;
9386       (!Src.Base ? Src : Dest).moveInto(Val);
9387       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9388           << Move << WChar << !!Src.Base
9389           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9390       return false;
9391     }
9392     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9393       return false;
9394 
9395     // We require that Src and Dest are both pointers to arrays of
9396     // trivially-copyable type. (For the wide version, the designator will be
9397     // invalid if the designated object is not a wchar_t.)
9398     QualType T = Dest.Designator.getType(Info.Ctx);
9399     QualType SrcT = Src.Designator.getType(Info.Ctx);
9400     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9401       // FIXME: Consider using our bit_cast implementation to support this.
9402       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9403       return false;
9404     }
9405     if (T->isIncompleteType()) {
9406       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9407       return false;
9408     }
9409     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9410       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9411       return false;
9412     }
9413 
9414     // Figure out how many T's we're copying.
9415     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9416     if (!WChar) {
9417       uint64_t Remainder;
9418       llvm::APInt OrigN = N;
9419       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9420       if (Remainder) {
9421         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9422             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9423             << (unsigned)TSize;
9424         return false;
9425       }
9426     }
9427 
9428     // Check that the copying will remain within the arrays, just so that we
9429     // can give a more meaningful diagnostic. This implicitly also checks that
9430     // N fits into 64 bits.
9431     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9432     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9433     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9434       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9435           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9436           << toString(N, 10, /*Signed*/false);
9437       return false;
9438     }
9439     uint64_t NElems = N.getZExtValue();
9440     uint64_t NBytes = NElems * TSize;
9441 
9442     // Check for overlap.
9443     int Direction = 1;
9444     if (HasSameBase(Src, Dest)) {
9445       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9446       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9447       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9448         // Dest is inside the source region.
9449         if (!Move) {
9450           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9451           return false;
9452         }
9453         // For memmove and friends, copy backwards.
9454         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9455             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9456           return false;
9457         Direction = -1;
9458       } else if (!Move && SrcOffset >= DestOffset &&
9459                  SrcOffset - DestOffset < NBytes) {
9460         // Src is inside the destination region for memcpy: invalid.
9461         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9462         return false;
9463       }
9464     }
9465 
9466     while (true) {
9467       APValue Val;
9468       // FIXME: Set WantObjectRepresentation to true if we're copying a
9469       // char-like type?
9470       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9471           !handleAssignment(Info, E, Dest, T, Val))
9472         return false;
9473       // Do not iterate past the last element; if we're copying backwards, that
9474       // might take us off the start of the array.
9475       if (--NElems == 0)
9476         return true;
9477       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9478           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9479         return false;
9480     }
9481   }
9482 
9483   default:
9484     return false;
9485   }
9486 }
9487 
9488 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9489                                      APValue &Result, const InitListExpr *ILE,
9490                                      QualType AllocType);
9491 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9492                                           APValue &Result,
9493                                           const CXXConstructExpr *CCE,
9494                                           QualType AllocType);
9495 
VisitCXXNewExpr(const CXXNewExpr * E)9496 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9497   if (!Info.getLangOpts().CPlusPlus20)
9498     Info.CCEDiag(E, diag::note_constexpr_new);
9499 
9500   // We cannot speculatively evaluate a delete expression.
9501   if (Info.SpeculativeEvaluationDepth)
9502     return false;
9503 
9504   FunctionDecl *OperatorNew = E->getOperatorNew();
9505 
9506   bool IsNothrow = false;
9507   bool IsPlacement = false;
9508   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9509       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9510     // FIXME Support array placement new.
9511     assert(E->getNumPlacementArgs() == 1);
9512     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9513       return false;
9514     if (Result.Designator.Invalid)
9515       return false;
9516     IsPlacement = true;
9517   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9518     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9519         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9520     return false;
9521   } else if (E->getNumPlacementArgs()) {
9522     // The only new-placement list we support is of the form (std::nothrow).
9523     //
9524     // FIXME: There is no restriction on this, but it's not clear that any
9525     // other form makes any sense. We get here for cases such as:
9526     //
9527     //   new (std::align_val_t{N}) X(int)
9528     //
9529     // (which should presumably be valid only if N is a multiple of
9530     // alignof(int), and in any case can't be deallocated unless N is
9531     // alignof(X) and X has new-extended alignment).
9532     if (E->getNumPlacementArgs() != 1 ||
9533         !E->getPlacementArg(0)->getType()->isNothrowT())
9534       return Error(E, diag::note_constexpr_new_placement);
9535 
9536     LValue Nothrow;
9537     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9538       return false;
9539     IsNothrow = true;
9540   }
9541 
9542   const Expr *Init = E->getInitializer();
9543   const InitListExpr *ResizedArrayILE = nullptr;
9544   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9545   bool ValueInit = false;
9546 
9547   QualType AllocType = E->getAllocatedType();
9548   if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
9549     const Expr *Stripped = *ArraySize;
9550     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9551          Stripped = ICE->getSubExpr())
9552       if (ICE->getCastKind() != CK_NoOp &&
9553           ICE->getCastKind() != CK_IntegralCast)
9554         break;
9555 
9556     llvm::APSInt ArrayBound;
9557     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9558       return false;
9559 
9560     // C++ [expr.new]p9:
9561     //   The expression is erroneous if:
9562     //   -- [...] its value before converting to size_t [or] applying the
9563     //      second standard conversion sequence is less than zero
9564     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9565       if (IsNothrow)
9566         return ZeroInitialization(E);
9567 
9568       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9569           << ArrayBound << (*ArraySize)->getSourceRange();
9570       return false;
9571     }
9572 
9573     //   -- its value is such that the size of the allocated object would
9574     //      exceed the implementation-defined limit
9575     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9576                                                 ArrayBound) >
9577         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9578       if (IsNothrow)
9579         return ZeroInitialization(E);
9580 
9581       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9582         << ArrayBound << (*ArraySize)->getSourceRange();
9583       return false;
9584     }
9585 
9586     //   -- the new-initializer is a braced-init-list and the number of
9587     //      array elements for which initializers are provided [...]
9588     //      exceeds the number of elements to initialize
9589     if (!Init) {
9590       // No initialization is performed.
9591     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9592                isa<ImplicitValueInitExpr>(Init)) {
9593       ValueInit = true;
9594     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9595       ResizedArrayCCE = CCE;
9596     } else {
9597       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9598       assert(CAT && "unexpected type for array initializer");
9599 
9600       unsigned Bits =
9601           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9602       llvm::APInt InitBound = CAT->getSize().zext(Bits);
9603       llvm::APInt AllocBound = ArrayBound.zext(Bits);
9604       if (InitBound.ugt(AllocBound)) {
9605         if (IsNothrow)
9606           return ZeroInitialization(E);
9607 
9608         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9609             << toString(AllocBound, 10, /*Signed=*/false)
9610             << toString(InitBound, 10, /*Signed=*/false)
9611             << (*ArraySize)->getSourceRange();
9612         return false;
9613       }
9614 
9615       // If the sizes differ, we must have an initializer list, and we need
9616       // special handling for this case when we initialize.
9617       if (InitBound != AllocBound)
9618         ResizedArrayILE = cast<InitListExpr>(Init);
9619     }
9620 
9621     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9622                                               ArrayType::Normal, 0);
9623   } else {
9624     assert(!AllocType->isArrayType() &&
9625            "array allocation with non-array new");
9626   }
9627 
9628   APValue *Val;
9629   if (IsPlacement) {
9630     AccessKinds AK = AK_Construct;
9631     struct FindObjectHandler {
9632       EvalInfo &Info;
9633       const Expr *E;
9634       QualType AllocType;
9635       const AccessKinds AccessKind;
9636       APValue *Value;
9637 
9638       typedef bool result_type;
9639       bool failed() { return false; }
9640       bool found(APValue &Subobj, QualType SubobjType) {
9641         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9642         // old name of the object to be used to name the new object.
9643         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9644           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9645             SubobjType << AllocType;
9646           return false;
9647         }
9648         Value = &Subobj;
9649         return true;
9650       }
9651       bool found(APSInt &Value, QualType SubobjType) {
9652         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9653         return false;
9654       }
9655       bool found(APFloat &Value, QualType SubobjType) {
9656         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9657         return false;
9658       }
9659     } Handler = {Info, E, AllocType, AK, nullptr};
9660 
9661     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9662     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9663       return false;
9664 
9665     Val = Handler.Value;
9666 
9667     // [basic.life]p1:
9668     //   The lifetime of an object o of type T ends when [...] the storage
9669     //   which the object occupies is [...] reused by an object that is not
9670     //   nested within o (6.6.2).
9671     *Val = APValue();
9672   } else {
9673     // Perform the allocation and obtain a pointer to the resulting object.
9674     Val = Info.createHeapAlloc(E, AllocType, Result);
9675     if (!Val)
9676       return false;
9677   }
9678 
9679   if (ValueInit) {
9680     ImplicitValueInitExpr VIE(AllocType);
9681     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9682       return false;
9683   } else if (ResizedArrayILE) {
9684     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9685                                   AllocType))
9686       return false;
9687   } else if (ResizedArrayCCE) {
9688     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9689                                        AllocType))
9690       return false;
9691   } else if (Init) {
9692     if (!EvaluateInPlace(*Val, Info, Result, Init))
9693       return false;
9694   } else if (!getDefaultInitValue(AllocType, *Val)) {
9695     return false;
9696   }
9697 
9698   // Array new returns a pointer to the first element, not a pointer to the
9699   // array.
9700   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9701     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9702 
9703   return true;
9704 }
9705 //===----------------------------------------------------------------------===//
9706 // Member Pointer Evaluation
9707 //===----------------------------------------------------------------------===//
9708 
9709 namespace {
9710 class MemberPointerExprEvaluator
9711   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9712   MemberPtr &Result;
9713 
Success(const ValueDecl * D)9714   bool Success(const ValueDecl *D) {
9715     Result = MemberPtr(D);
9716     return true;
9717   }
9718 public:
9719 
MemberPointerExprEvaluator(EvalInfo & Info,MemberPtr & Result)9720   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9721     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9722 
Success(const APValue & V,const Expr * E)9723   bool Success(const APValue &V, const Expr *E) {
9724     Result.setFrom(V);
9725     return true;
9726   }
ZeroInitialization(const Expr * E)9727   bool ZeroInitialization(const Expr *E) {
9728     return Success((const ValueDecl*)nullptr);
9729   }
9730 
9731   bool VisitCastExpr(const CastExpr *E);
9732   bool VisitUnaryAddrOf(const UnaryOperator *E);
9733 };
9734 } // end anonymous namespace
9735 
EvaluateMemberPointer(const Expr * E,MemberPtr & Result,EvalInfo & Info)9736 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9737                                   EvalInfo &Info) {
9738   assert(!E->isValueDependent());
9739   assert(E->isPRValue() && E->getType()->isMemberPointerType());
9740   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9741 }
9742 
VisitCastExpr(const CastExpr * E)9743 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9744   switch (E->getCastKind()) {
9745   default:
9746     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9747 
9748   case CK_NullToMemberPointer:
9749     VisitIgnoredValue(E->getSubExpr());
9750     return ZeroInitialization(E);
9751 
9752   case CK_BaseToDerivedMemberPointer: {
9753     if (!Visit(E->getSubExpr()))
9754       return false;
9755     if (E->path_empty())
9756       return true;
9757     // Base-to-derived member pointer casts store the path in derived-to-base
9758     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9759     // the wrong end of the derived->base arc, so stagger the path by one class.
9760     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9761     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9762          PathI != PathE; ++PathI) {
9763       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9764       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9765       if (!Result.castToDerived(Derived))
9766         return Error(E);
9767     }
9768     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9769     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9770       return Error(E);
9771     return true;
9772   }
9773 
9774   case CK_DerivedToBaseMemberPointer:
9775     if (!Visit(E->getSubExpr()))
9776       return false;
9777     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9778          PathE = E->path_end(); PathI != PathE; ++PathI) {
9779       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9780       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9781       if (!Result.castToBase(Base))
9782         return Error(E);
9783     }
9784     return true;
9785   }
9786 }
9787 
VisitUnaryAddrOf(const UnaryOperator * E)9788 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9789   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9790   // member can be formed.
9791   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9792 }
9793 
9794 //===----------------------------------------------------------------------===//
9795 // Record Evaluation
9796 //===----------------------------------------------------------------------===//
9797 
9798 namespace {
9799   class RecordExprEvaluator
9800   : public ExprEvaluatorBase<RecordExprEvaluator> {
9801     const LValue &This;
9802     APValue &Result;
9803   public:
9804 
RecordExprEvaluator(EvalInfo & info,const LValue & This,APValue & Result)9805     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9806       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9807 
Success(const APValue & V,const Expr * E)9808     bool Success(const APValue &V, const Expr *E) {
9809       Result = V;
9810       return true;
9811     }
ZeroInitialization(const Expr * E)9812     bool ZeroInitialization(const Expr *E) {
9813       return ZeroInitialization(E, E->getType());
9814     }
9815     bool ZeroInitialization(const Expr *E, QualType T);
9816 
VisitCallExpr(const CallExpr * E)9817     bool VisitCallExpr(const CallExpr *E) {
9818       return handleCallExpr(E, Result, &This);
9819     }
9820     bool VisitCastExpr(const CastExpr *E);
9821     bool VisitInitListExpr(const InitListExpr *E);
VisitCXXConstructExpr(const CXXConstructExpr * E)9822     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9823       return VisitCXXConstructExpr(E, E->getType());
9824     }
9825     bool VisitLambdaExpr(const LambdaExpr *E);
9826     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9827     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9828     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9829     bool VisitBinCmp(const BinaryOperator *E);
9830     bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
9831     bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
9832                                          ArrayRef<Expr *> Args);
9833   };
9834 }
9835 
9836 /// Perform zero-initialization on an object of non-union class type.
9837 /// C++11 [dcl.init]p5:
9838 ///  To zero-initialize an object or reference of type T means:
9839 ///    [...]
9840 ///    -- if T is a (possibly cv-qualified) non-union class type,
9841 ///       each non-static data member and each base-class subobject is
9842 ///       zero-initialized
HandleClassZeroInitialization(EvalInfo & Info,const Expr * E,const RecordDecl * RD,const LValue & This,APValue & Result)9843 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9844                                           const RecordDecl *RD,
9845                                           const LValue &This, APValue &Result) {
9846   assert(!RD->isUnion() && "Expected non-union class type");
9847   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9848   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9849                    std::distance(RD->field_begin(), RD->field_end()));
9850 
9851   if (RD->isInvalidDecl()) return false;
9852   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9853 
9854   if (CD) {
9855     unsigned Index = 0;
9856     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9857            End = CD->bases_end(); I != End; ++I, ++Index) {
9858       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9859       LValue Subobject = This;
9860       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9861         return false;
9862       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9863                                          Result.getStructBase(Index)))
9864         return false;
9865     }
9866   }
9867 
9868   for (const auto *I : RD->fields()) {
9869     // -- if T is a reference type, no initialization is performed.
9870     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9871       continue;
9872 
9873     LValue Subobject = This;
9874     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9875       return false;
9876 
9877     ImplicitValueInitExpr VIE(I->getType());
9878     if (!EvaluateInPlace(
9879           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9880       return false;
9881   }
9882 
9883   return true;
9884 }
9885 
ZeroInitialization(const Expr * E,QualType T)9886 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9887   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9888   if (RD->isInvalidDecl()) return false;
9889   if (RD->isUnion()) {
9890     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9891     // object's first non-static named data member is zero-initialized
9892     RecordDecl::field_iterator I = RD->field_begin();
9893     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9894       ++I;
9895     if (I == RD->field_end()) {
9896       Result = APValue((const FieldDecl*)nullptr);
9897       return true;
9898     }
9899 
9900     LValue Subobject = This;
9901     if (!HandleLValueMember(Info, E, Subobject, *I))
9902       return false;
9903     Result = APValue(*I);
9904     ImplicitValueInitExpr VIE(I->getType());
9905     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9906   }
9907 
9908   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9909     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9910     return false;
9911   }
9912 
9913   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9914 }
9915 
VisitCastExpr(const CastExpr * E)9916 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9917   switch (E->getCastKind()) {
9918   default:
9919     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9920 
9921   case CK_ConstructorConversion:
9922     return Visit(E->getSubExpr());
9923 
9924   case CK_DerivedToBase:
9925   case CK_UncheckedDerivedToBase: {
9926     APValue DerivedObject;
9927     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9928       return false;
9929     if (!DerivedObject.isStruct())
9930       return Error(E->getSubExpr());
9931 
9932     // Derived-to-base rvalue conversion: just slice off the derived part.
9933     APValue *Value = &DerivedObject;
9934     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9935     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9936          PathE = E->path_end(); PathI != PathE; ++PathI) {
9937       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9938       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9939       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9940       RD = Base;
9941     }
9942     Result = *Value;
9943     return true;
9944   }
9945   }
9946 }
9947 
VisitInitListExpr(const InitListExpr * E)9948 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9949   if (E->isTransparent())
9950     return Visit(E->getInit(0));
9951   return VisitCXXParenListOrInitListExpr(E, E->inits());
9952 }
9953 
VisitCXXParenListOrInitListExpr(const Expr * ExprToVisit,ArrayRef<Expr * > Args)9954 bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
9955     const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
9956   const RecordDecl *RD =
9957       ExprToVisit->getType()->castAs<RecordType>()->getDecl();
9958   if (RD->isInvalidDecl()) return false;
9959   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9960   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9961 
9962   EvalInfo::EvaluatingConstructorRAII EvalObj(
9963       Info,
9964       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9965       CXXRD && CXXRD->getNumBases());
9966 
9967   if (RD->isUnion()) {
9968     const FieldDecl *Field;
9969     if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
9970       Field = ILE->getInitializedFieldInUnion();
9971     } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
9972       Field = PLIE->getInitializedFieldInUnion();
9973     } else {
9974       llvm_unreachable(
9975           "Expression is neither an init list nor a C++ paren list");
9976     }
9977 
9978     Result = APValue(Field);
9979     if (!Field)
9980       return true;
9981 
9982     // If the initializer list for a union does not contain any elements, the
9983     // first element of the union is value-initialized.
9984     // FIXME: The element should be initialized from an initializer list.
9985     //        Is this difference ever observable for initializer lists which
9986     //        we don't build?
9987     ImplicitValueInitExpr VIE(Field->getType());
9988     const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
9989 
9990     LValue Subobject = This;
9991     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9992       return false;
9993 
9994     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9995     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9996                                   isa<CXXDefaultInitExpr>(InitExpr));
9997 
9998     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
9999       if (Field->isBitField())
10000         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10001                                      Field);
10002       return true;
10003     }
10004 
10005     return false;
10006   }
10007 
10008   if (!Result.hasValue())
10009     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10010                      std::distance(RD->field_begin(), RD->field_end()));
10011   unsigned ElementNo = 0;
10012   bool Success = true;
10013 
10014   // Initialize base classes.
10015   if (CXXRD && CXXRD->getNumBases()) {
10016     for (const auto &Base : CXXRD->bases()) {
10017       assert(ElementNo < Args.size() && "missing init for base class");
10018       const Expr *Init = Args[ElementNo];
10019 
10020       LValue Subobject = This;
10021       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10022         return false;
10023 
10024       APValue &FieldVal = Result.getStructBase(ElementNo);
10025       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10026         if (!Info.noteFailure())
10027           return false;
10028         Success = false;
10029       }
10030       ++ElementNo;
10031     }
10032 
10033     EvalObj.finishedConstructingBases();
10034   }
10035 
10036   // Initialize members.
10037   for (const auto *Field : RD->fields()) {
10038     // Anonymous bit-fields are not considered members of the class for
10039     // purposes of aggregate initialization.
10040     if (Field->isUnnamedBitfield())
10041       continue;
10042 
10043     LValue Subobject = This;
10044 
10045     bool HaveInit = ElementNo < Args.size();
10046 
10047     // FIXME: Diagnostics here should point to the end of the initializer
10048     // list, not the start.
10049     if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10050                             Subobject, Field, &Layout))
10051       return false;
10052 
10053     // Perform an implicit value-initialization for members beyond the end of
10054     // the initializer list.
10055     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10056     const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10057 
10058     if (Field->getType()->isIncompleteArrayType()) {
10059       if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10060         if (!CAT->getSize().isZero()) {
10061           // Bail out for now. This might sort of "work", but the rest of the
10062           // code isn't really prepared to handle it.
10063           Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10064           return false;
10065         }
10066       }
10067     }
10068 
10069     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10070     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10071                                   isa<CXXDefaultInitExpr>(Init));
10072 
10073     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10074     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10075         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10076                                                        FieldVal, Field))) {
10077       if (!Info.noteFailure())
10078         return false;
10079       Success = false;
10080     }
10081   }
10082 
10083   EvalObj.finishedConstructingFields();
10084 
10085   return Success;
10086 }
10087 
VisitCXXConstructExpr(const CXXConstructExpr * E,QualType T)10088 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10089                                                 QualType T) {
10090   // Note that E's type is not necessarily the type of our class here; we might
10091   // be initializing an array element instead.
10092   const CXXConstructorDecl *FD = E->getConstructor();
10093   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10094 
10095   bool ZeroInit = E->requiresZeroInitialization();
10096   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10097     // If we've already performed zero-initialization, we're already done.
10098     if (Result.hasValue())
10099       return true;
10100 
10101     if (ZeroInit)
10102       return ZeroInitialization(E, T);
10103 
10104     return getDefaultInitValue(T, Result);
10105   }
10106 
10107   const FunctionDecl *Definition = nullptr;
10108   auto Body = FD->getBody(Definition);
10109 
10110   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10111     return false;
10112 
10113   // Avoid materializing a temporary for an elidable copy/move constructor.
10114   if (E->isElidable() && !ZeroInit) {
10115     // FIXME: This only handles the simplest case, where the source object
10116     //        is passed directly as the first argument to the constructor.
10117     //        This should also handle stepping though implicit casts and
10118     //        and conversion sequences which involve two steps, with a
10119     //        conversion operator followed by a converting constructor.
10120     const Expr *SrcObj = E->getArg(0);
10121     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10122     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10123     if (const MaterializeTemporaryExpr *ME =
10124             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10125       return Visit(ME->getSubExpr());
10126   }
10127 
10128   if (ZeroInit && !ZeroInitialization(E, T))
10129     return false;
10130 
10131   auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
10132   return HandleConstructorCall(E, This, Args,
10133                                cast<CXXConstructorDecl>(Definition), Info,
10134                                Result);
10135 }
10136 
VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr * E)10137 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10138     const CXXInheritedCtorInitExpr *E) {
10139   if (!Info.CurrentCall) {
10140     assert(Info.checkingPotentialConstantExpression());
10141     return false;
10142   }
10143 
10144   const CXXConstructorDecl *FD = E->getConstructor();
10145   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10146     return false;
10147 
10148   const FunctionDecl *Definition = nullptr;
10149   auto Body = FD->getBody(Definition);
10150 
10151   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10152     return false;
10153 
10154   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10155                                cast<CXXConstructorDecl>(Definition), Info,
10156                                Result);
10157 }
10158 
VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr * E)10159 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10160     const CXXStdInitializerListExpr *E) {
10161   const ConstantArrayType *ArrayType =
10162       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10163 
10164   LValue Array;
10165   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10166     return false;
10167 
10168   // Get a pointer to the first element of the array.
10169   Array.addArray(Info, E, ArrayType);
10170 
10171   auto InvalidType = [&] {
10172     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10173       << E->getType();
10174     return false;
10175   };
10176 
10177   // FIXME: Perform the checks on the field types in SemaInit.
10178   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10179   RecordDecl::field_iterator Field = Record->field_begin();
10180   if (Field == Record->field_end())
10181     return InvalidType();
10182 
10183   // Start pointer.
10184   if (!Field->getType()->isPointerType() ||
10185       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10186                             ArrayType->getElementType()))
10187     return InvalidType();
10188 
10189   // FIXME: What if the initializer_list type has base classes, etc?
10190   Result = APValue(APValue::UninitStruct(), 0, 2);
10191   Array.moveInto(Result.getStructField(0));
10192 
10193   if (++Field == Record->field_end())
10194     return InvalidType();
10195 
10196   if (Field->getType()->isPointerType() &&
10197       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10198                            ArrayType->getElementType())) {
10199     // End pointer.
10200     if (!HandleLValueArrayAdjustment(Info, E, Array,
10201                                      ArrayType->getElementType(),
10202                                      ArrayType->getSize().getZExtValue()))
10203       return false;
10204     Array.moveInto(Result.getStructField(1));
10205   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10206     // Length.
10207     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10208   else
10209     return InvalidType();
10210 
10211   if (++Field != Record->field_end())
10212     return InvalidType();
10213 
10214   return true;
10215 }
10216 
VisitLambdaExpr(const LambdaExpr * E)10217 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10218   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10219   if (ClosureClass->isInvalidDecl())
10220     return false;
10221 
10222   const size_t NumFields =
10223       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10224 
10225   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10226                                             E->capture_init_end()) &&
10227          "The number of lambda capture initializers should equal the number of "
10228          "fields within the closure type");
10229 
10230   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10231   // Iterate through all the lambda's closure object's fields and initialize
10232   // them.
10233   auto *CaptureInitIt = E->capture_init_begin();
10234   bool Success = true;
10235   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10236   for (const auto *Field : ClosureClass->fields()) {
10237     assert(CaptureInitIt != E->capture_init_end());
10238     // Get the initializer for this field
10239     Expr *const CurFieldInit = *CaptureInitIt++;
10240 
10241     // If there is no initializer, either this is a VLA or an error has
10242     // occurred.
10243     if (!CurFieldInit)
10244       return Error(E);
10245 
10246     LValue Subobject = This;
10247 
10248     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10249       return false;
10250 
10251     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10252     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10253       if (!Info.keepEvaluatingAfterFailure())
10254         return false;
10255       Success = false;
10256     }
10257   }
10258   return Success;
10259 }
10260 
EvaluateRecord(const Expr * E,const LValue & This,APValue & Result,EvalInfo & Info)10261 static bool EvaluateRecord(const Expr *E, const LValue &This,
10262                            APValue &Result, EvalInfo &Info) {
10263   assert(!E->isValueDependent());
10264   assert(E->isPRValue() && E->getType()->isRecordType() &&
10265          "can't evaluate expression as a record rvalue");
10266   return RecordExprEvaluator(Info, This, Result).Visit(E);
10267 }
10268 
10269 //===----------------------------------------------------------------------===//
10270 // Temporary Evaluation
10271 //
10272 // Temporaries are represented in the AST as rvalues, but generally behave like
10273 // lvalues. The full-object of which the temporary is a subobject is implicitly
10274 // materialized so that a reference can bind to it.
10275 //===----------------------------------------------------------------------===//
10276 namespace {
10277 class TemporaryExprEvaluator
10278   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10279 public:
TemporaryExprEvaluator(EvalInfo & Info,LValue & Result)10280   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10281     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10282 
10283   /// Visit an expression which constructs the value of this temporary.
VisitConstructExpr(const Expr * E)10284   bool VisitConstructExpr(const Expr *E) {
10285     APValue &Value = Info.CurrentCall->createTemporary(
10286         E, E->getType(), ScopeKind::FullExpression, Result);
10287     return EvaluateInPlace(Value, Info, Result, E);
10288   }
10289 
VisitCastExpr(const CastExpr * E)10290   bool VisitCastExpr(const CastExpr *E) {
10291     switch (E->getCastKind()) {
10292     default:
10293       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10294 
10295     case CK_ConstructorConversion:
10296       return VisitConstructExpr(E->getSubExpr());
10297     }
10298   }
VisitInitListExpr(const InitListExpr * E)10299   bool VisitInitListExpr(const InitListExpr *E) {
10300     return VisitConstructExpr(E);
10301   }
VisitCXXConstructExpr(const CXXConstructExpr * E)10302   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10303     return VisitConstructExpr(E);
10304   }
VisitCallExpr(const CallExpr * E)10305   bool VisitCallExpr(const CallExpr *E) {
10306     return VisitConstructExpr(E);
10307   }
VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr * E)10308   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10309     return VisitConstructExpr(E);
10310   }
VisitLambdaExpr(const LambdaExpr * E)10311   bool VisitLambdaExpr(const LambdaExpr *E) {
10312     return VisitConstructExpr(E);
10313   }
10314 };
10315 } // end anonymous namespace
10316 
10317 /// Evaluate an expression of record type as a temporary.
EvaluateTemporary(const Expr * E,LValue & Result,EvalInfo & Info)10318 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10319   assert(!E->isValueDependent());
10320   assert(E->isPRValue() && E->getType()->isRecordType());
10321   return TemporaryExprEvaluator(Info, Result).Visit(E);
10322 }
10323 
10324 //===----------------------------------------------------------------------===//
10325 // Vector Evaluation
10326 //===----------------------------------------------------------------------===//
10327 
10328 namespace {
10329   class VectorExprEvaluator
10330   : public ExprEvaluatorBase<VectorExprEvaluator> {
10331     APValue &Result;
10332   public:
10333 
VectorExprEvaluator(EvalInfo & info,APValue & Result)10334     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10335       : ExprEvaluatorBaseTy(info), Result(Result) {}
10336 
Success(ArrayRef<APValue> V,const Expr * E)10337     bool Success(ArrayRef<APValue> V, const Expr *E) {
10338       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10339       // FIXME: remove this APValue copy.
10340       Result = APValue(V.data(), V.size());
10341       return true;
10342     }
Success(const APValue & V,const Expr * E)10343     bool Success(const APValue &V, const Expr *E) {
10344       assert(V.isVector());
10345       Result = V;
10346       return true;
10347     }
10348     bool ZeroInitialization(const Expr *E);
10349 
VisitUnaryReal(const UnaryOperator * E)10350     bool VisitUnaryReal(const UnaryOperator *E)
10351       { return Visit(E->getSubExpr()); }
10352     bool VisitCastExpr(const CastExpr* E);
10353     bool VisitInitListExpr(const InitListExpr *E);
10354     bool VisitUnaryImag(const UnaryOperator *E);
10355     bool VisitBinaryOperator(const BinaryOperator *E);
10356     bool VisitUnaryOperator(const UnaryOperator *E);
10357     // FIXME: Missing: conditional operator (for GNU
10358     //                 conditional select), shufflevector, ExtVectorElementExpr
10359   };
10360 } // end anonymous namespace
10361 
EvaluateVector(const Expr * E,APValue & Result,EvalInfo & Info)10362 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10363   assert(E->isPRValue() && E->getType()->isVectorType() &&
10364          "not a vector prvalue");
10365   return VectorExprEvaluator(Info, Result).Visit(E);
10366 }
10367 
VisitCastExpr(const CastExpr * E)10368 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10369   const VectorType *VTy = E->getType()->castAs<VectorType>();
10370   unsigned NElts = VTy->getNumElements();
10371 
10372   const Expr *SE = E->getSubExpr();
10373   QualType SETy = SE->getType();
10374 
10375   switch (E->getCastKind()) {
10376   case CK_VectorSplat: {
10377     APValue Val = APValue();
10378     if (SETy->isIntegerType()) {
10379       APSInt IntResult;
10380       if (!EvaluateInteger(SE, IntResult, Info))
10381         return false;
10382       Val = APValue(std::move(IntResult));
10383     } else if (SETy->isRealFloatingType()) {
10384       APFloat FloatResult(0.0);
10385       if (!EvaluateFloat(SE, FloatResult, Info))
10386         return false;
10387       Val = APValue(std::move(FloatResult));
10388     } else {
10389       return Error(E);
10390     }
10391 
10392     // Splat and create vector APValue.
10393     SmallVector<APValue, 4> Elts(NElts, Val);
10394     return Success(Elts, E);
10395   }
10396   case CK_BitCast: {
10397     // Evaluate the operand into an APInt we can extract from.
10398     llvm::APInt SValInt;
10399     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10400       return false;
10401     // Extract the elements
10402     QualType EltTy = VTy->getElementType();
10403     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10404     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10405     SmallVector<APValue, 4> Elts;
10406     if (EltTy->isRealFloatingType()) {
10407       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10408       unsigned FloatEltSize = EltSize;
10409       if (&Sem == &APFloat::x87DoubleExtended())
10410         FloatEltSize = 80;
10411       for (unsigned i = 0; i < NElts; i++) {
10412         llvm::APInt Elt;
10413         if (BigEndian)
10414           Elt = SValInt.rotl(i * EltSize + FloatEltSize).trunc(FloatEltSize);
10415         else
10416           Elt = SValInt.rotr(i * EltSize).trunc(FloatEltSize);
10417         Elts.push_back(APValue(APFloat(Sem, Elt)));
10418       }
10419     } else if (EltTy->isIntegerType()) {
10420       for (unsigned i = 0; i < NElts; i++) {
10421         llvm::APInt Elt;
10422         if (BigEndian)
10423           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10424         else
10425           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10426         Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10427       }
10428     } else {
10429       return Error(E);
10430     }
10431     return Success(Elts, E);
10432   }
10433   default:
10434     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10435   }
10436 }
10437 
10438 bool
VisitInitListExpr(const InitListExpr * E)10439 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10440   const VectorType *VT = E->getType()->castAs<VectorType>();
10441   unsigned NumInits = E->getNumInits();
10442   unsigned NumElements = VT->getNumElements();
10443 
10444   QualType EltTy = VT->getElementType();
10445   SmallVector<APValue, 4> Elements;
10446 
10447   // The number of initializers can be less than the number of
10448   // vector elements. For OpenCL, this can be due to nested vector
10449   // initialization. For GCC compatibility, missing trailing elements
10450   // should be initialized with zeroes.
10451   unsigned CountInits = 0, CountElts = 0;
10452   while (CountElts < NumElements) {
10453     // Handle nested vector initialization.
10454     if (CountInits < NumInits
10455         && E->getInit(CountInits)->getType()->isVectorType()) {
10456       APValue v;
10457       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10458         return Error(E);
10459       unsigned vlen = v.getVectorLength();
10460       for (unsigned j = 0; j < vlen; j++)
10461         Elements.push_back(v.getVectorElt(j));
10462       CountElts += vlen;
10463     } else if (EltTy->isIntegerType()) {
10464       llvm::APSInt sInt(32);
10465       if (CountInits < NumInits) {
10466         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10467           return false;
10468       } else // trailing integer zero.
10469         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10470       Elements.push_back(APValue(sInt));
10471       CountElts++;
10472     } else {
10473       llvm::APFloat f(0.0);
10474       if (CountInits < NumInits) {
10475         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10476           return false;
10477       } else // trailing float zero.
10478         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10479       Elements.push_back(APValue(f));
10480       CountElts++;
10481     }
10482     CountInits++;
10483   }
10484   return Success(Elements, E);
10485 }
10486 
10487 bool
ZeroInitialization(const Expr * E)10488 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10489   const auto *VT = E->getType()->castAs<VectorType>();
10490   QualType EltTy = VT->getElementType();
10491   APValue ZeroElement;
10492   if (EltTy->isIntegerType())
10493     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10494   else
10495     ZeroElement =
10496         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10497 
10498   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10499   return Success(Elements, E);
10500 }
10501 
VisitUnaryImag(const UnaryOperator * E)10502 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10503   VisitIgnoredValue(E->getSubExpr());
10504   return ZeroInitialization(E);
10505 }
10506 
VisitBinaryOperator(const BinaryOperator * E)10507 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10508   BinaryOperatorKind Op = E->getOpcode();
10509   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10510          "Operation not supported on vector types");
10511 
10512   if (Op == BO_Comma)
10513     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10514 
10515   Expr *LHS = E->getLHS();
10516   Expr *RHS = E->getRHS();
10517 
10518   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10519          "Must both be vector types");
10520   // Checking JUST the types are the same would be fine, except shifts don't
10521   // need to have their types be the same (since you always shift by an int).
10522   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10523              E->getType()->castAs<VectorType>()->getNumElements() &&
10524          RHS->getType()->castAs<VectorType>()->getNumElements() ==
10525              E->getType()->castAs<VectorType>()->getNumElements() &&
10526          "All operands must be the same size.");
10527 
10528   APValue LHSValue;
10529   APValue RHSValue;
10530   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10531   if (!LHSOK && !Info.noteFailure())
10532     return false;
10533   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10534     return false;
10535 
10536   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10537     return false;
10538 
10539   return Success(LHSValue, E);
10540 }
10541 
handleVectorUnaryOperator(ASTContext & Ctx,QualType ResultTy,UnaryOperatorKind Op,APValue Elt)10542 static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10543                                                         QualType ResultTy,
10544                                                         UnaryOperatorKind Op,
10545                                                         APValue Elt) {
10546   switch (Op) {
10547   case UO_Plus:
10548     // Nothing to do here.
10549     return Elt;
10550   case UO_Minus:
10551     if (Elt.getKind() == APValue::Int) {
10552       Elt.getInt().negate();
10553     } else {
10554       assert(Elt.getKind() == APValue::Float &&
10555              "Vector can only be int or float type");
10556       Elt.getFloat().changeSign();
10557     }
10558     return Elt;
10559   case UO_Not:
10560     // This is only valid for integral types anyway, so we don't have to handle
10561     // float here.
10562     assert(Elt.getKind() == APValue::Int &&
10563            "Vector operator ~ can only be int");
10564     Elt.getInt().flipAllBits();
10565     return Elt;
10566   case UO_LNot: {
10567     if (Elt.getKind() == APValue::Int) {
10568       Elt.getInt() = !Elt.getInt();
10569       // operator ! on vectors returns -1 for 'truth', so negate it.
10570       Elt.getInt().negate();
10571       return Elt;
10572     }
10573     assert(Elt.getKind() == APValue::Float &&
10574            "Vector can only be int or float type");
10575     // Float types result in an int of the same size, but -1 for true, or 0 for
10576     // false.
10577     APSInt EltResult{Ctx.getIntWidth(ResultTy),
10578                      ResultTy->isUnsignedIntegerType()};
10579     if (Elt.getFloat().isZero())
10580       EltResult.setAllBits();
10581     else
10582       EltResult.clearAllBits();
10583 
10584     return APValue{EltResult};
10585   }
10586   default:
10587     // FIXME: Implement the rest of the unary operators.
10588     return std::nullopt;
10589   }
10590 }
10591 
VisitUnaryOperator(const UnaryOperator * E)10592 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10593   Expr *SubExpr = E->getSubExpr();
10594   const auto *VD = SubExpr->getType()->castAs<VectorType>();
10595   // This result element type differs in the case of negating a floating point
10596   // vector, since the result type is the a vector of the equivilant sized
10597   // integer.
10598   const QualType ResultEltTy = VD->getElementType();
10599   UnaryOperatorKind Op = E->getOpcode();
10600 
10601   APValue SubExprValue;
10602   if (!Evaluate(SubExprValue, Info, SubExpr))
10603     return false;
10604 
10605   // FIXME: This vector evaluator someday needs to be changed to be LValue
10606   // aware/keep LValue information around, rather than dealing with just vector
10607   // types directly. Until then, we cannot handle cases where the operand to
10608   // these unary operators is an LValue. The only case I've been able to see
10609   // cause this is operator++ assigning to a member expression (only valid in
10610   // altivec compilations) in C mode, so this shouldn't limit us too much.
10611   if (SubExprValue.isLValue())
10612     return false;
10613 
10614   assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10615          "Vector length doesn't match type?");
10616 
10617   SmallVector<APValue, 4> ResultElements;
10618   for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10619     std::optional<APValue> Elt = handleVectorUnaryOperator(
10620         Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10621     if (!Elt)
10622       return false;
10623     ResultElements.push_back(*Elt);
10624   }
10625   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10626 }
10627 
10628 //===----------------------------------------------------------------------===//
10629 // Array Evaluation
10630 //===----------------------------------------------------------------------===//
10631 
10632 namespace {
10633   class ArrayExprEvaluator
10634   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10635     const LValue &This;
10636     APValue &Result;
10637   public:
10638 
ArrayExprEvaluator(EvalInfo & Info,const LValue & This,APValue & Result)10639     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10640       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10641 
Success(const APValue & V,const Expr * E)10642     bool Success(const APValue &V, const Expr *E) {
10643       assert(V.isArray() && "expected array");
10644       Result = V;
10645       return true;
10646     }
10647 
ZeroInitialization(const Expr * E)10648     bool ZeroInitialization(const Expr *E) {
10649       const ConstantArrayType *CAT =
10650           Info.Ctx.getAsConstantArrayType(E->getType());
10651       if (!CAT) {
10652         if (E->getType()->isIncompleteArrayType()) {
10653           // We can be asked to zero-initialize a flexible array member; this
10654           // is represented as an ImplicitValueInitExpr of incomplete array
10655           // type. In this case, the array has zero elements.
10656           Result = APValue(APValue::UninitArray(), 0, 0);
10657           return true;
10658         }
10659         // FIXME: We could handle VLAs here.
10660         return Error(E);
10661       }
10662 
10663       Result = APValue(APValue::UninitArray(), 0,
10664                        CAT->getSize().getZExtValue());
10665       if (!Result.hasArrayFiller())
10666         return true;
10667 
10668       // Zero-initialize all elements.
10669       LValue Subobject = This;
10670       Subobject.addArray(Info, E, CAT);
10671       ImplicitValueInitExpr VIE(CAT->getElementType());
10672       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10673     }
10674 
VisitCallExpr(const CallExpr * E)10675     bool VisitCallExpr(const CallExpr *E) {
10676       return handleCallExpr(E, Result, &This);
10677     }
10678     bool VisitInitListExpr(const InitListExpr *E,
10679                            QualType AllocType = QualType());
10680     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10681     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10682     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10683                                const LValue &Subobject,
10684                                APValue *Value, QualType Type);
VisitStringLiteral(const StringLiteral * E,QualType AllocType=QualType ())10685     bool VisitStringLiteral(const StringLiteral *E,
10686                             QualType AllocType = QualType()) {
10687       expandStringLiteral(Info, E, Result, AllocType);
10688       return true;
10689     }
10690     bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10691     bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10692                                          ArrayRef<Expr *> Args,
10693                                          const Expr *ArrayFiller,
10694                                          QualType AllocType = QualType());
10695   };
10696 } // end anonymous namespace
10697 
EvaluateArray(const Expr * E,const LValue & This,APValue & Result,EvalInfo & Info)10698 static bool EvaluateArray(const Expr *E, const LValue &This,
10699                           APValue &Result, EvalInfo &Info) {
10700   assert(!E->isValueDependent());
10701   assert(E->isPRValue() && E->getType()->isArrayType() &&
10702          "not an array prvalue");
10703   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10704 }
10705 
EvaluateArrayNewInitList(EvalInfo & Info,LValue & This,APValue & Result,const InitListExpr * ILE,QualType AllocType)10706 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10707                                      APValue &Result, const InitListExpr *ILE,
10708                                      QualType AllocType) {
10709   assert(!ILE->isValueDependent());
10710   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10711          "not an array prvalue");
10712   return ArrayExprEvaluator(Info, This, Result)
10713       .VisitInitListExpr(ILE, AllocType);
10714 }
10715 
EvaluateArrayNewConstructExpr(EvalInfo & Info,LValue & This,APValue & Result,const CXXConstructExpr * CCE,QualType AllocType)10716 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10717                                           APValue &Result,
10718                                           const CXXConstructExpr *CCE,
10719                                           QualType AllocType) {
10720   assert(!CCE->isValueDependent());
10721   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10722          "not an array prvalue");
10723   return ArrayExprEvaluator(Info, This, Result)
10724       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10725 }
10726 
10727 // Return true iff the given array filler may depend on the element index.
MaybeElementDependentArrayFiller(const Expr * FillerExpr)10728 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10729   // For now, just allow non-class value-initialization and initialization
10730   // lists comprised of them.
10731   if (isa<ImplicitValueInitExpr>(FillerExpr))
10732     return false;
10733   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10734     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10735       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10736         return true;
10737     }
10738 
10739     if (ILE->hasArrayFiller() &&
10740         MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
10741       return true;
10742 
10743     return false;
10744   }
10745   return true;
10746 }
10747 
VisitInitListExpr(const InitListExpr * E,QualType AllocType)10748 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10749                                            QualType AllocType) {
10750   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10751       AllocType.isNull() ? E->getType() : AllocType);
10752   if (!CAT)
10753     return Error(E);
10754 
10755   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10756   // an appropriately-typed string literal enclosed in braces.
10757   if (E->isStringLiteralInit()) {
10758     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10759     // FIXME: Support ObjCEncodeExpr here once we support it in
10760     // ArrayExprEvaluator generally.
10761     if (!SL)
10762       return Error(E);
10763     return VisitStringLiteral(SL, AllocType);
10764   }
10765   // Any other transparent list init will need proper handling of the
10766   // AllocType; we can't just recurse to the inner initializer.
10767   assert(!E->isTransparent() &&
10768          "transparent array list initialization is not string literal init?");
10769 
10770   return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
10771                                          AllocType);
10772 }
10773 
VisitCXXParenListOrInitListExpr(const Expr * ExprToVisit,ArrayRef<Expr * > Args,const Expr * ArrayFiller,QualType AllocType)10774 bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
10775     const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
10776     QualType AllocType) {
10777   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10778       AllocType.isNull() ? ExprToVisit->getType() : AllocType);
10779 
10780   bool Success = true;
10781 
10782   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10783          "zero-initialized array shouldn't have any initialized elts");
10784   APValue Filler;
10785   if (Result.isArray() && Result.hasArrayFiller())
10786     Filler = Result.getArrayFiller();
10787 
10788   unsigned NumEltsToInit = Args.size();
10789   unsigned NumElts = CAT->getSize().getZExtValue();
10790 
10791   // If the initializer might depend on the array index, run it for each
10792   // array element.
10793   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(ArrayFiller))
10794     NumEltsToInit = NumElts;
10795 
10796   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10797                           << NumEltsToInit << ".\n");
10798 
10799   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10800 
10801   // If the array was previously zero-initialized, preserve the
10802   // zero-initialized values.
10803   if (Filler.hasValue()) {
10804     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10805       Result.getArrayInitializedElt(I) = Filler;
10806     if (Result.hasArrayFiller())
10807       Result.getArrayFiller() = Filler;
10808   }
10809 
10810   LValue Subobject = This;
10811   Subobject.addArray(Info, ExprToVisit, CAT);
10812   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10813     const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
10814     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10815                          Info, Subobject, Init) ||
10816         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10817                                      CAT->getElementType(), 1)) {
10818       if (!Info.noteFailure())
10819         return false;
10820       Success = false;
10821     }
10822   }
10823 
10824   if (!Result.hasArrayFiller())
10825     return Success;
10826 
10827   // If we get here, we have a trivial filler, which we can just evaluate
10828   // once and splat over the rest of the array elements.
10829   assert(ArrayFiller && "no array filler for incomplete init list");
10830   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10831                          ArrayFiller) &&
10832          Success;
10833 }
10834 
VisitArrayInitLoopExpr(const ArrayInitLoopExpr * E)10835 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10836   LValue CommonLV;
10837   if (E->getCommonExpr() &&
10838       !Evaluate(Info.CurrentCall->createTemporary(
10839                     E->getCommonExpr(),
10840                     getStorageType(Info.Ctx, E->getCommonExpr()),
10841                     ScopeKind::FullExpression, CommonLV),
10842                 Info, E->getCommonExpr()->getSourceExpr()))
10843     return false;
10844 
10845   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10846 
10847   uint64_t Elements = CAT->getSize().getZExtValue();
10848   Result = APValue(APValue::UninitArray(), Elements, Elements);
10849 
10850   LValue Subobject = This;
10851   Subobject.addArray(Info, E, CAT);
10852 
10853   bool Success = true;
10854   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10855     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10856                          Info, Subobject, E->getSubExpr()) ||
10857         !HandleLValueArrayAdjustment(Info, E, Subobject,
10858                                      CAT->getElementType(), 1)) {
10859       if (!Info.noteFailure())
10860         return false;
10861       Success = false;
10862     }
10863   }
10864 
10865   return Success;
10866 }
10867 
VisitCXXConstructExpr(const CXXConstructExpr * E)10868 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10869   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10870 }
10871 
VisitCXXConstructExpr(const CXXConstructExpr * E,const LValue & Subobject,APValue * Value,QualType Type)10872 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10873                                                const LValue &Subobject,
10874                                                APValue *Value,
10875                                                QualType Type) {
10876   bool HadZeroInit = Value->hasValue();
10877 
10878   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10879     unsigned FinalSize = CAT->getSize().getZExtValue();
10880 
10881     // Preserve the array filler if we had prior zero-initialization.
10882     APValue Filler =
10883       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10884                                              : APValue();
10885 
10886     *Value = APValue(APValue::UninitArray(), 0, FinalSize);
10887     if (FinalSize == 0)
10888       return true;
10889 
10890     bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
10891         Info, E->getExprLoc(), E->getConstructor(),
10892         E->requiresZeroInitialization());
10893     LValue ArrayElt = Subobject;
10894     ArrayElt.addArray(Info, E, CAT);
10895     // We do the whole initialization in two passes, first for just one element,
10896     // then for the whole array. It's possible we may find out we can't do const
10897     // init in the first pass, in which case we avoid allocating a potentially
10898     // large array. We don't do more passes because expanding array requires
10899     // copying the data, which is wasteful.
10900     for (const unsigned N : {1u, FinalSize}) {
10901       unsigned OldElts = Value->getArrayInitializedElts();
10902       if (OldElts == N)
10903         break;
10904 
10905       // Expand the array to appropriate size.
10906       APValue NewValue(APValue::UninitArray(), N, FinalSize);
10907       for (unsigned I = 0; I < OldElts; ++I)
10908         NewValue.getArrayInitializedElt(I).swap(
10909             Value->getArrayInitializedElt(I));
10910       Value->swap(NewValue);
10911 
10912       if (HadZeroInit)
10913         for (unsigned I = OldElts; I < N; ++I)
10914           Value->getArrayInitializedElt(I) = Filler;
10915 
10916       if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
10917         // If we have a trivial constructor, only evaluate it once and copy
10918         // the result into all the array elements.
10919         APValue &FirstResult = Value->getArrayInitializedElt(0);
10920         for (unsigned I = OldElts; I < FinalSize; ++I)
10921           Value->getArrayInitializedElt(I) = FirstResult;
10922       } else {
10923         for (unsigned I = OldElts; I < N; ++I) {
10924           if (!VisitCXXConstructExpr(E, ArrayElt,
10925                                      &Value->getArrayInitializedElt(I),
10926                                      CAT->getElementType()) ||
10927               !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10928                                            CAT->getElementType(), 1))
10929             return false;
10930           // When checking for const initilization any diagnostic is considered
10931           // an error.
10932           if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
10933               !Info.keepEvaluatingAfterFailure())
10934             return false;
10935         }
10936       }
10937     }
10938 
10939     return true;
10940   }
10941 
10942   if (!Type->isRecordType())
10943     return Error(E);
10944 
10945   return RecordExprEvaluator(Info, Subobject, *Value)
10946              .VisitCXXConstructExpr(E, Type);
10947 }
10948 
VisitCXXParenListInitExpr(const CXXParenListInitExpr * E)10949 bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
10950     const CXXParenListInitExpr *E) {
10951   assert(dyn_cast<ConstantArrayType>(E->getType()) &&
10952          "Expression result is not a constant array type");
10953 
10954   return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
10955                                          E->getArrayFiller());
10956 }
10957 
10958 //===----------------------------------------------------------------------===//
10959 // Integer Evaluation
10960 //
10961 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10962 // types and back in constant folding. Integer values are thus represented
10963 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10964 //===----------------------------------------------------------------------===//
10965 
10966 namespace {
10967 class IntExprEvaluator
10968         : public ExprEvaluatorBase<IntExprEvaluator> {
10969   APValue &Result;
10970 public:
IntExprEvaluator(EvalInfo & info,APValue & result)10971   IntExprEvaluator(EvalInfo &info, APValue &result)
10972       : ExprEvaluatorBaseTy(info), Result(result) {}
10973 
Success(const llvm::APSInt & SI,const Expr * E,APValue & Result)10974   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10975     assert(E->getType()->isIntegralOrEnumerationType() &&
10976            "Invalid evaluation result.");
10977     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10978            "Invalid evaluation result.");
10979     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10980            "Invalid evaluation result.");
10981     Result = APValue(SI);
10982     return true;
10983   }
Success(const llvm::APSInt & SI,const Expr * E)10984   bool Success(const llvm::APSInt &SI, const Expr *E) {
10985     return Success(SI, E, Result);
10986   }
10987 
Success(const llvm::APInt & I,const Expr * E,APValue & Result)10988   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10989     assert(E->getType()->isIntegralOrEnumerationType() &&
10990            "Invalid evaluation result.");
10991     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10992            "Invalid evaluation result.");
10993     Result = APValue(APSInt(I));
10994     Result.getInt().setIsUnsigned(
10995                             E->getType()->isUnsignedIntegerOrEnumerationType());
10996     return true;
10997   }
Success(const llvm::APInt & I,const Expr * E)10998   bool Success(const llvm::APInt &I, const Expr *E) {
10999     return Success(I, E, Result);
11000   }
11001 
Success(uint64_t Value,const Expr * E,APValue & Result)11002   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11003     assert(E->getType()->isIntegralOrEnumerationType() &&
11004            "Invalid evaluation result.");
11005     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
11006     return true;
11007   }
Success(uint64_t Value,const Expr * E)11008   bool Success(uint64_t Value, const Expr *E) {
11009     return Success(Value, E, Result);
11010   }
11011 
Success(CharUnits Size,const Expr * E)11012   bool Success(CharUnits Size, const Expr *E) {
11013     return Success(Size.getQuantity(), E);
11014   }
11015 
Success(const APValue & V,const Expr * E)11016   bool Success(const APValue &V, const Expr *E) {
11017     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
11018       Result = V;
11019       return true;
11020     }
11021     return Success(V.getInt(), E);
11022   }
11023 
ZeroInitialization(const Expr * E)11024   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
11025 
11026   //===--------------------------------------------------------------------===//
11027   //                            Visitor Methods
11028   //===--------------------------------------------------------------------===//
11029 
VisitIntegerLiteral(const IntegerLiteral * E)11030   bool VisitIntegerLiteral(const IntegerLiteral *E) {
11031     return Success(E->getValue(), E);
11032   }
VisitCharacterLiteral(const CharacterLiteral * E)11033   bool VisitCharacterLiteral(const CharacterLiteral *E) {
11034     return Success(E->getValue(), E);
11035   }
11036 
11037   bool CheckReferencedDecl(const Expr *E, const Decl *D);
VisitDeclRefExpr(const DeclRefExpr * E)11038   bool VisitDeclRefExpr(const DeclRefExpr *E) {
11039     if (CheckReferencedDecl(E, E->getDecl()))
11040       return true;
11041 
11042     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
11043   }
VisitMemberExpr(const MemberExpr * E)11044   bool VisitMemberExpr(const MemberExpr *E) {
11045     if (CheckReferencedDecl(E, E->getMemberDecl())) {
11046       VisitIgnoredBaseExpression(E->getBase());
11047       return true;
11048     }
11049 
11050     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
11051   }
11052 
11053   bool VisitCallExpr(const CallExpr *E);
11054   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
11055   bool VisitBinaryOperator(const BinaryOperator *E);
11056   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
11057   bool VisitUnaryOperator(const UnaryOperator *E);
11058 
11059   bool VisitCastExpr(const CastExpr* E);
11060   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
11061 
VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr * E)11062   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
11063     return Success(E->getValue(), E);
11064   }
11065 
VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr * E)11066   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
11067     return Success(E->getValue(), E);
11068   }
11069 
VisitArrayInitIndexExpr(const ArrayInitIndexExpr * E)11070   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
11071     if (Info.ArrayInitIndex == uint64_t(-1)) {
11072       // We were asked to evaluate this subexpression independent of the
11073       // enclosing ArrayInitLoopExpr. We can't do that.
11074       Info.FFDiag(E);
11075       return false;
11076     }
11077     return Success(Info.ArrayInitIndex, E);
11078   }
11079 
11080   // Note, GNU defines __null as an integer, not a pointer.
VisitGNUNullExpr(const GNUNullExpr * E)11081   bool VisitGNUNullExpr(const GNUNullExpr *E) {
11082     return ZeroInitialization(E);
11083   }
11084 
VisitTypeTraitExpr(const TypeTraitExpr * E)11085   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11086     return Success(E->getValue(), E);
11087   }
11088 
VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr * E)11089   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11090     return Success(E->getValue(), E);
11091   }
11092 
VisitExpressionTraitExpr(const ExpressionTraitExpr * E)11093   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11094     return Success(E->getValue(), E);
11095   }
11096 
11097   bool VisitUnaryReal(const UnaryOperator *E);
11098   bool VisitUnaryImag(const UnaryOperator *E);
11099 
11100   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11101   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11102   bool VisitSourceLocExpr(const SourceLocExpr *E);
11103   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11104   bool VisitRequiresExpr(const RequiresExpr *E);
11105   // FIXME: Missing: array subscript of vector, member of vector
11106 };
11107 
11108 class FixedPointExprEvaluator
11109     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11110   APValue &Result;
11111 
11112  public:
FixedPointExprEvaluator(EvalInfo & info,APValue & result)11113   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11114       : ExprEvaluatorBaseTy(info), Result(result) {}
11115 
Success(const llvm::APInt & I,const Expr * E)11116   bool Success(const llvm::APInt &I, const Expr *E) {
11117     return Success(
11118         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11119   }
11120 
Success(uint64_t Value,const Expr * E)11121   bool Success(uint64_t Value, const Expr *E) {
11122     return Success(
11123         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11124   }
11125 
Success(const APValue & V,const Expr * E)11126   bool Success(const APValue &V, const Expr *E) {
11127     return Success(V.getFixedPoint(), E);
11128   }
11129 
Success(const APFixedPoint & V,const Expr * E)11130   bool Success(const APFixedPoint &V, const Expr *E) {
11131     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
11132     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11133            "Invalid evaluation result.");
11134     Result = APValue(V);
11135     return true;
11136   }
11137 
11138   //===--------------------------------------------------------------------===//
11139   //                            Visitor Methods
11140   //===--------------------------------------------------------------------===//
11141 
VisitFixedPointLiteral(const FixedPointLiteral * E)11142   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11143     return Success(E->getValue(), E);
11144   }
11145 
11146   bool VisitCastExpr(const CastExpr *E);
11147   bool VisitUnaryOperator(const UnaryOperator *E);
11148   bool VisitBinaryOperator(const BinaryOperator *E);
11149 };
11150 } // end anonymous namespace
11151 
11152 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11153 /// produce either the integer value or a pointer.
11154 ///
11155 /// GCC has a heinous extension which folds casts between pointer types and
11156 /// pointer-sized integral types. We support this by allowing the evaluation of
11157 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11158 /// Some simple arithmetic on such values is supported (they are treated much
11159 /// like char*).
EvaluateIntegerOrLValue(const Expr * E,APValue & Result,EvalInfo & Info)11160 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11161                                     EvalInfo &Info) {
11162   assert(!E->isValueDependent());
11163   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
11164   return IntExprEvaluator(Info, Result).Visit(E);
11165 }
11166 
EvaluateInteger(const Expr * E,APSInt & Result,EvalInfo & Info)11167 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11168   assert(!E->isValueDependent());
11169   APValue Val;
11170   if (!EvaluateIntegerOrLValue(E, Val, Info))
11171     return false;
11172   if (!Val.isInt()) {
11173     // FIXME: It would be better to produce the diagnostic for casting
11174     //        a pointer to an integer.
11175     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11176     return false;
11177   }
11178   Result = Val.getInt();
11179   return true;
11180 }
11181 
VisitSourceLocExpr(const SourceLocExpr * E)11182 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11183   APValue Evaluated = E->EvaluateInContext(
11184       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11185   return Success(Evaluated, E);
11186 }
11187 
EvaluateFixedPoint(const Expr * E,APFixedPoint & Result,EvalInfo & Info)11188 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11189                                EvalInfo &Info) {
11190   assert(!E->isValueDependent());
11191   if (E->getType()->isFixedPointType()) {
11192     APValue Val;
11193     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11194       return false;
11195     if (!Val.isFixedPoint())
11196       return false;
11197 
11198     Result = Val.getFixedPoint();
11199     return true;
11200   }
11201   return false;
11202 }
11203 
EvaluateFixedPointOrInteger(const Expr * E,APFixedPoint & Result,EvalInfo & Info)11204 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11205                                         EvalInfo &Info) {
11206   assert(!E->isValueDependent());
11207   if (E->getType()->isIntegerType()) {
11208     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11209     APSInt Val;
11210     if (!EvaluateInteger(E, Val, Info))
11211       return false;
11212     Result = APFixedPoint(Val, FXSema);
11213     return true;
11214   } else if (E->getType()->isFixedPointType()) {
11215     return EvaluateFixedPoint(E, Result, Info);
11216   }
11217   return false;
11218 }
11219 
11220 /// Check whether the given declaration can be directly converted to an integral
11221 /// rvalue. If not, no diagnostic is produced; there are other things we can
11222 /// try.
CheckReferencedDecl(const Expr * E,const Decl * D)11223 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11224   // Enums are integer constant exprs.
11225   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11226     // Check for signedness/width mismatches between E type and ECD value.
11227     bool SameSign = (ECD->getInitVal().isSigned()
11228                      == E->getType()->isSignedIntegerOrEnumerationType());
11229     bool SameWidth = (ECD->getInitVal().getBitWidth()
11230                       == Info.Ctx.getIntWidth(E->getType()));
11231     if (SameSign && SameWidth)
11232       return Success(ECD->getInitVal(), E);
11233     else {
11234       // Get rid of mismatch (otherwise Success assertions will fail)
11235       // by computing a new value matching the type of E.
11236       llvm::APSInt Val = ECD->getInitVal();
11237       if (!SameSign)
11238         Val.setIsSigned(!ECD->getInitVal().isSigned());
11239       if (!SameWidth)
11240         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11241       return Success(Val, E);
11242     }
11243   }
11244   return false;
11245 }
11246 
11247 /// Values returned by __builtin_classify_type, chosen to match the values
11248 /// produced by GCC's builtin.
11249 enum class GCCTypeClass {
11250   None = -1,
11251   Void = 0,
11252   Integer = 1,
11253   // GCC reserves 2 for character types, but instead classifies them as
11254   // integers.
11255   Enum = 3,
11256   Bool = 4,
11257   Pointer = 5,
11258   // GCC reserves 6 for references, but appears to never use it (because
11259   // expressions never have reference type, presumably).
11260   PointerToDataMember = 7,
11261   RealFloat = 8,
11262   Complex = 9,
11263   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
11264   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
11265   // GCC claims to reserve 11 for pointers to member functions, but *actually*
11266   // uses 12 for that purpose, same as for a class or struct. Maybe it
11267   // internally implements a pointer to member as a struct?  Who knows.
11268   PointerToMemberFunction = 12, // Not a bug, see above.
11269   ClassOrStruct = 12,
11270   Union = 13,
11271   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
11272   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
11273   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
11274   // literals.
11275 };
11276 
11277 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11278 /// as GCC.
11279 static GCCTypeClass
EvaluateBuiltinClassifyType(QualType T,const LangOptions & LangOpts)11280 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
11281   assert(!T->isDependentType() && "unexpected dependent type");
11282 
11283   QualType CanTy = T.getCanonicalType();
11284   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
11285 
11286   switch (CanTy->getTypeClass()) {
11287 #define TYPE(ID, BASE)
11288 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11289 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11290 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11291 #include "clang/AST/TypeNodes.inc"
11292   case Type::Auto:
11293   case Type::DeducedTemplateSpecialization:
11294       llvm_unreachable("unexpected non-canonical or dependent type");
11295 
11296   case Type::Builtin:
11297     switch (BT->getKind()) {
11298 #define BUILTIN_TYPE(ID, SINGLETON_ID)
11299 #define SIGNED_TYPE(ID, SINGLETON_ID) \
11300     case BuiltinType::ID: return GCCTypeClass::Integer;
11301 #define FLOATING_TYPE(ID, SINGLETON_ID) \
11302     case BuiltinType::ID: return GCCTypeClass::RealFloat;
11303 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11304     case BuiltinType::ID: break;
11305 #include "clang/AST/BuiltinTypes.def"
11306     case BuiltinType::Void:
11307       return GCCTypeClass::Void;
11308 
11309     case BuiltinType::Bool:
11310       return GCCTypeClass::Bool;
11311 
11312     case BuiltinType::Char_U:
11313     case BuiltinType::UChar:
11314     case BuiltinType::WChar_U:
11315     case BuiltinType::Char8:
11316     case BuiltinType::Char16:
11317     case BuiltinType::Char32:
11318     case BuiltinType::UShort:
11319     case BuiltinType::UInt:
11320     case BuiltinType::ULong:
11321     case BuiltinType::ULongLong:
11322     case BuiltinType::UInt128:
11323       return GCCTypeClass::Integer;
11324 
11325     case BuiltinType::UShortAccum:
11326     case BuiltinType::UAccum:
11327     case BuiltinType::ULongAccum:
11328     case BuiltinType::UShortFract:
11329     case BuiltinType::UFract:
11330     case BuiltinType::ULongFract:
11331     case BuiltinType::SatUShortAccum:
11332     case BuiltinType::SatUAccum:
11333     case BuiltinType::SatULongAccum:
11334     case BuiltinType::SatUShortFract:
11335     case BuiltinType::SatUFract:
11336     case BuiltinType::SatULongFract:
11337       return GCCTypeClass::None;
11338 
11339     case BuiltinType::NullPtr:
11340 
11341     case BuiltinType::ObjCId:
11342     case BuiltinType::ObjCClass:
11343     case BuiltinType::ObjCSel:
11344 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11345     case BuiltinType::Id:
11346 #include "clang/Basic/OpenCLImageTypes.def"
11347 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11348     case BuiltinType::Id:
11349 #include "clang/Basic/OpenCLExtensionTypes.def"
11350     case BuiltinType::OCLSampler:
11351     case BuiltinType::OCLEvent:
11352     case BuiltinType::OCLClkEvent:
11353     case BuiltinType::OCLQueue:
11354     case BuiltinType::OCLReserveID:
11355 #define SVE_TYPE(Name, Id, SingletonId) \
11356     case BuiltinType::Id:
11357 #include "clang/Basic/AArch64SVEACLETypes.def"
11358 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11359     case BuiltinType::Id:
11360 #include "clang/Basic/PPCTypes.def"
11361 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11362 #include "clang/Basic/RISCVVTypes.def"
11363       return GCCTypeClass::None;
11364 
11365     case BuiltinType::Dependent:
11366       llvm_unreachable("unexpected dependent type");
11367     };
11368     llvm_unreachable("unexpected placeholder type");
11369 
11370   case Type::Enum:
11371     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11372 
11373   case Type::Pointer:
11374   case Type::ConstantArray:
11375   case Type::VariableArray:
11376   case Type::IncompleteArray:
11377   case Type::FunctionNoProto:
11378   case Type::FunctionProto:
11379     return GCCTypeClass::Pointer;
11380 
11381   case Type::MemberPointer:
11382     return CanTy->isMemberDataPointerType()
11383                ? GCCTypeClass::PointerToDataMember
11384                : GCCTypeClass::PointerToMemberFunction;
11385 
11386   case Type::Complex:
11387     return GCCTypeClass::Complex;
11388 
11389   case Type::Record:
11390     return CanTy->isUnionType() ? GCCTypeClass::Union
11391                                 : GCCTypeClass::ClassOrStruct;
11392 
11393   case Type::Atomic:
11394     // GCC classifies _Atomic T the same as T.
11395     return EvaluateBuiltinClassifyType(
11396         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11397 
11398   case Type::BlockPointer:
11399   case Type::Vector:
11400   case Type::ExtVector:
11401   case Type::ConstantMatrix:
11402   case Type::ObjCObject:
11403   case Type::ObjCInterface:
11404   case Type::ObjCObjectPointer:
11405   case Type::Pipe:
11406   case Type::BitInt:
11407     // GCC classifies vectors as None. We follow its lead and classify all
11408     // other types that don't fit into the regular classification the same way.
11409     return GCCTypeClass::None;
11410 
11411   case Type::LValueReference:
11412   case Type::RValueReference:
11413     llvm_unreachable("invalid type for expression");
11414   }
11415 
11416   llvm_unreachable("unexpected type class");
11417 }
11418 
11419 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11420 /// as GCC.
11421 static GCCTypeClass
EvaluateBuiltinClassifyType(const CallExpr * E,const LangOptions & LangOpts)11422 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11423   // If no argument was supplied, default to None. This isn't
11424   // ideal, however it is what gcc does.
11425   if (E->getNumArgs() == 0)
11426     return GCCTypeClass::None;
11427 
11428   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11429   // being an ICE, but still folds it to a constant using the type of the first
11430   // argument.
11431   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11432 }
11433 
11434 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11435 /// __builtin_constant_p when applied to the given pointer.
11436 ///
11437 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11438 /// or it points to the first character of a string literal.
EvaluateBuiltinConstantPForLValue(const APValue & LV)11439 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11440   APValue::LValueBase Base = LV.getLValueBase();
11441   if (Base.isNull()) {
11442     // A null base is acceptable.
11443     return true;
11444   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11445     if (!isa<StringLiteral>(E))
11446       return false;
11447     return LV.getLValueOffset().isZero();
11448   } else if (Base.is<TypeInfoLValue>()) {
11449     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11450     // evaluate to true.
11451     return true;
11452   } else {
11453     // Any other base is not constant enough for GCC.
11454     return false;
11455   }
11456 }
11457 
11458 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11459 /// GCC as we can manage.
EvaluateBuiltinConstantP(EvalInfo & Info,const Expr * Arg)11460 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11461   // This evaluation is not permitted to have side-effects, so evaluate it in
11462   // a speculative evaluation context.
11463   SpeculativeEvaluationRAII SpeculativeEval(Info);
11464 
11465   // Constant-folding is always enabled for the operand of __builtin_constant_p
11466   // (even when the enclosing evaluation context otherwise requires a strict
11467   // language-specific constant expression).
11468   FoldConstant Fold(Info, true);
11469 
11470   QualType ArgType = Arg->getType();
11471 
11472   // __builtin_constant_p always has one operand. The rules which gcc follows
11473   // are not precisely documented, but are as follows:
11474   //
11475   //  - If the operand is of integral, floating, complex or enumeration type,
11476   //    and can be folded to a known value of that type, it returns 1.
11477   //  - If the operand can be folded to a pointer to the first character
11478   //    of a string literal (or such a pointer cast to an integral type)
11479   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11480   //
11481   // Otherwise, it returns 0.
11482   //
11483   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11484   // its support for this did not work prior to GCC 9 and is not yet well
11485   // understood.
11486   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11487       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11488       ArgType->isNullPtrType()) {
11489     APValue V;
11490     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11491       Fold.keepDiagnostics();
11492       return false;
11493     }
11494 
11495     // For a pointer (possibly cast to integer), there are special rules.
11496     if (V.getKind() == APValue::LValue)
11497       return EvaluateBuiltinConstantPForLValue(V);
11498 
11499     // Otherwise, any constant value is good enough.
11500     return V.hasValue();
11501   }
11502 
11503   // Anything else isn't considered to be sufficiently constant.
11504   return false;
11505 }
11506 
11507 /// Retrieves the "underlying object type" of the given expression,
11508 /// as used by __builtin_object_size.
getObjectType(APValue::LValueBase B)11509 static QualType getObjectType(APValue::LValueBase B) {
11510   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11511     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11512       return VD->getType();
11513   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11514     if (isa<CompoundLiteralExpr>(E))
11515       return E->getType();
11516   } else if (B.is<TypeInfoLValue>()) {
11517     return B.getTypeInfoType();
11518   } else if (B.is<DynamicAllocLValue>()) {
11519     return B.getDynamicAllocType();
11520   }
11521 
11522   return QualType();
11523 }
11524 
11525 /// A more selective version of E->IgnoreParenCasts for
11526 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11527 /// to change the type of E.
11528 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11529 ///
11530 /// Always returns an RValue with a pointer representation.
ignorePointerCastsAndParens(const Expr * E)11531 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11532   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11533 
11534   auto *NoParens = E->IgnoreParens();
11535   auto *Cast = dyn_cast<CastExpr>(NoParens);
11536   if (Cast == nullptr)
11537     return NoParens;
11538 
11539   // We only conservatively allow a few kinds of casts, because this code is
11540   // inherently a simple solution that seeks to support the common case.
11541   auto CastKind = Cast->getCastKind();
11542   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11543       CastKind != CK_AddressSpaceConversion)
11544     return NoParens;
11545 
11546   auto *SubExpr = Cast->getSubExpr();
11547   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11548     return NoParens;
11549   return ignorePointerCastsAndParens(SubExpr);
11550 }
11551 
11552 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11553 /// record layout. e.g.
11554 ///   struct { struct { int a, b; } fst, snd; } obj;
11555 ///   obj.fst   // no
11556 ///   obj.snd   // yes
11557 ///   obj.fst.a // no
11558 ///   obj.fst.b // no
11559 ///   obj.snd.a // no
11560 ///   obj.snd.b // yes
11561 ///
11562 /// Please note: this function is specialized for how __builtin_object_size
11563 /// views "objects".
11564 ///
11565 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11566 /// correct result, it will always return true.
isDesignatorAtObjectEnd(const ASTContext & Ctx,const LValue & LVal)11567 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11568   assert(!LVal.Designator.Invalid);
11569 
11570   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11571     const RecordDecl *Parent = FD->getParent();
11572     Invalid = Parent->isInvalidDecl();
11573     if (Invalid || Parent->isUnion())
11574       return true;
11575     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11576     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11577   };
11578 
11579   auto &Base = LVal.getLValueBase();
11580   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11581     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11582       bool Invalid;
11583       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11584         return Invalid;
11585     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11586       for (auto *FD : IFD->chain()) {
11587         bool Invalid;
11588         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11589           return Invalid;
11590       }
11591     }
11592   }
11593 
11594   unsigned I = 0;
11595   QualType BaseType = getType(Base);
11596   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11597     // If we don't know the array bound, conservatively assume we're looking at
11598     // the final array element.
11599     ++I;
11600     if (BaseType->isIncompleteArrayType())
11601       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11602     else
11603       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11604   }
11605 
11606   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11607     const auto &Entry = LVal.Designator.Entries[I];
11608     if (BaseType->isArrayType()) {
11609       // Because __builtin_object_size treats arrays as objects, we can ignore
11610       // the index iff this is the last array in the Designator.
11611       if (I + 1 == E)
11612         return true;
11613       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11614       uint64_t Index = Entry.getAsArrayIndex();
11615       if (Index + 1 != CAT->getSize())
11616         return false;
11617       BaseType = CAT->getElementType();
11618     } else if (BaseType->isAnyComplexType()) {
11619       const auto *CT = BaseType->castAs<ComplexType>();
11620       uint64_t Index = Entry.getAsArrayIndex();
11621       if (Index != 1)
11622         return false;
11623       BaseType = CT->getElementType();
11624     } else if (auto *FD = getAsField(Entry)) {
11625       bool Invalid;
11626       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11627         return Invalid;
11628       BaseType = FD->getType();
11629     } else {
11630       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11631       return false;
11632     }
11633   }
11634   return true;
11635 }
11636 
11637 /// Tests to see if the LValue has a user-specified designator (that isn't
11638 /// necessarily valid). Note that this always returns 'true' if the LValue has
11639 /// an unsized array as its first designator entry, because there's currently no
11640 /// way to tell if the user typed *foo or foo[0].
refersToCompleteObject(const LValue & LVal)11641 static bool refersToCompleteObject(const LValue &LVal) {
11642   if (LVal.Designator.Invalid)
11643     return false;
11644 
11645   if (!LVal.Designator.Entries.empty())
11646     return LVal.Designator.isMostDerivedAnUnsizedArray();
11647 
11648   if (!LVal.InvalidBase)
11649     return true;
11650 
11651   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11652   // the LValueBase.
11653   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11654   return !E || !isa<MemberExpr>(E);
11655 }
11656 
11657 /// Attempts to detect a user writing into a piece of memory that's impossible
11658 /// to figure out the size of by just using types.
isUserWritingOffTheEnd(const ASTContext & Ctx,const LValue & LVal)11659 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11660   const SubobjectDesignator &Designator = LVal.Designator;
11661   // Notes:
11662   // - Users can only write off of the end when we have an invalid base. Invalid
11663   //   bases imply we don't know where the memory came from.
11664   // - We used to be a bit more aggressive here; we'd only be conservative if
11665   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11666   //   broke some common standard library extensions (PR30346), but was
11667   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11668   //   with some sort of list. OTOH, it seems that GCC is always
11669   //   conservative with the last element in structs (if it's an array), so our
11670   //   current behavior is more compatible than an explicit list approach would
11671   //   be.
11672   auto isFlexibleArrayMember = [&] {
11673     using FAMKind = LangOptions::StrictFlexArraysLevelKind;
11674     FAMKind StrictFlexArraysLevel =
11675         Ctx.getLangOpts().getStrictFlexArraysLevel();
11676 
11677     if (Designator.isMostDerivedAnUnsizedArray())
11678       return true;
11679 
11680     if (StrictFlexArraysLevel == FAMKind::Default)
11681       return true;
11682 
11683     if (Designator.getMostDerivedArraySize() == 0 &&
11684         StrictFlexArraysLevel != FAMKind::IncompleteOnly)
11685       return true;
11686 
11687     if (Designator.getMostDerivedArraySize() == 1 &&
11688         StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
11689       return true;
11690 
11691     return false;
11692   };
11693 
11694   return LVal.InvalidBase &&
11695          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11696          Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
11697          isDesignatorAtObjectEnd(Ctx, LVal);
11698 }
11699 
11700 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11701 /// Fails if the conversion would cause loss of precision.
convertUnsignedAPIntToCharUnits(const llvm::APInt & Int,CharUnits & Result)11702 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11703                                             CharUnits &Result) {
11704   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11705   if (Int.ugt(CharUnitsMax))
11706     return false;
11707   Result = CharUnits::fromQuantity(Int.getZExtValue());
11708   return true;
11709 }
11710 
11711 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11712 /// determine how many bytes exist from the beginning of the object to either
11713 /// the end of the current subobject, or the end of the object itself, depending
11714 /// on what the LValue looks like + the value of Type.
11715 ///
11716 /// If this returns false, the value of Result is undefined.
determineEndOffset(EvalInfo & Info,SourceLocation ExprLoc,unsigned Type,const LValue & LVal,CharUnits & EndOffset)11717 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11718                                unsigned Type, const LValue &LVal,
11719                                CharUnits &EndOffset) {
11720   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11721 
11722   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11723     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11724       return false;
11725     return HandleSizeof(Info, ExprLoc, Ty, Result);
11726   };
11727 
11728   // We want to evaluate the size of the entire object. This is a valid fallback
11729   // for when Type=1 and the designator is invalid, because we're asked for an
11730   // upper-bound.
11731   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11732     // Type=3 wants a lower bound, so we can't fall back to this.
11733     if (Type == 3 && !DetermineForCompleteObject)
11734       return false;
11735 
11736     llvm::APInt APEndOffset;
11737     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11738         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11739       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11740 
11741     if (LVal.InvalidBase)
11742       return false;
11743 
11744     QualType BaseTy = getObjectType(LVal.getLValueBase());
11745     return CheckedHandleSizeof(BaseTy, EndOffset);
11746   }
11747 
11748   // We want to evaluate the size of a subobject.
11749   const SubobjectDesignator &Designator = LVal.Designator;
11750 
11751   // The following is a moderately common idiom in C:
11752   //
11753   // struct Foo { int a; char c[1]; };
11754   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11755   // strcpy(&F->c[0], Bar);
11756   //
11757   // In order to not break too much legacy code, we need to support it.
11758   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11759     // If we can resolve this to an alloc_size call, we can hand that back,
11760     // because we know for certain how many bytes there are to write to.
11761     llvm::APInt APEndOffset;
11762     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11763         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11764       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11765 
11766     // If we cannot determine the size of the initial allocation, then we can't
11767     // given an accurate upper-bound. However, we are still able to give
11768     // conservative lower-bounds for Type=3.
11769     if (Type == 1)
11770       return false;
11771   }
11772 
11773   CharUnits BytesPerElem;
11774   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11775     return false;
11776 
11777   // According to the GCC documentation, we want the size of the subobject
11778   // denoted by the pointer. But that's not quite right -- what we actually
11779   // want is the size of the immediately-enclosing array, if there is one.
11780   int64_t ElemsRemaining;
11781   if (Designator.MostDerivedIsArrayElement &&
11782       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11783     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11784     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11785     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11786   } else {
11787     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11788   }
11789 
11790   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11791   return true;
11792 }
11793 
11794 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11795 /// returns true and stores the result in @p Size.
11796 ///
11797 /// If @p WasError is non-null, this will report whether the failure to evaluate
11798 /// is to be treated as an Error in IntExprEvaluator.
tryEvaluateBuiltinObjectSize(const Expr * E,unsigned Type,EvalInfo & Info,uint64_t & Size)11799 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11800                                          EvalInfo &Info, uint64_t &Size) {
11801   // Determine the denoted object.
11802   LValue LVal;
11803   {
11804     // The operand of __builtin_object_size is never evaluated for side-effects.
11805     // If there are any, but we can determine the pointed-to object anyway, then
11806     // ignore the side-effects.
11807     SpeculativeEvaluationRAII SpeculativeEval(Info);
11808     IgnoreSideEffectsRAII Fold(Info);
11809 
11810     if (E->isGLValue()) {
11811       // It's possible for us to be given GLValues if we're called via
11812       // Expr::tryEvaluateObjectSize.
11813       APValue RVal;
11814       if (!EvaluateAsRValue(Info, E, RVal))
11815         return false;
11816       LVal.setFrom(Info.Ctx, RVal);
11817     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11818                                 /*InvalidBaseOK=*/true))
11819       return false;
11820   }
11821 
11822   // If we point to before the start of the object, there are no accessible
11823   // bytes.
11824   if (LVal.getLValueOffset().isNegative()) {
11825     Size = 0;
11826     return true;
11827   }
11828 
11829   CharUnits EndOffset;
11830   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11831     return false;
11832 
11833   // If we've fallen outside of the end offset, just pretend there's nothing to
11834   // write to/read from.
11835   if (EndOffset <= LVal.getLValueOffset())
11836     Size = 0;
11837   else
11838     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11839   return true;
11840 }
11841 
VisitCallExpr(const CallExpr * E)11842 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11843   if (!IsConstantEvaluatedBuiltinCall(E))
11844     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11845   return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
11846 }
11847 
getBuiltinAlignArguments(const CallExpr * E,EvalInfo & Info,APValue & Val,APSInt & Alignment)11848 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11849                                      APValue &Val, APSInt &Alignment) {
11850   QualType SrcTy = E->getArg(0)->getType();
11851   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11852     return false;
11853   // Even though we are evaluating integer expressions we could get a pointer
11854   // argument for the __builtin_is_aligned() case.
11855   if (SrcTy->isPointerType()) {
11856     LValue Ptr;
11857     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11858       return false;
11859     Ptr.moveInto(Val);
11860   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11861     Info.FFDiag(E->getArg(0));
11862     return false;
11863   } else {
11864     APSInt SrcInt;
11865     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11866       return false;
11867     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11868            "Bit widths must be the same");
11869     Val = APValue(SrcInt);
11870   }
11871   assert(Val.hasValue());
11872   return true;
11873 }
11874 
VisitBuiltinCallExpr(const CallExpr * E,unsigned BuiltinOp)11875 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11876                                             unsigned BuiltinOp) {
11877   switch (BuiltinOp) {
11878   default:
11879     return false;
11880 
11881   case Builtin::BI__builtin_dynamic_object_size:
11882   case Builtin::BI__builtin_object_size: {
11883     // The type was checked when we built the expression.
11884     unsigned Type =
11885         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11886     assert(Type <= 3 && "unexpected type");
11887 
11888     uint64_t Size;
11889     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11890       return Success(Size, E);
11891 
11892     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11893       return Success((Type & 2) ? 0 : -1, E);
11894 
11895     // Expression had no side effects, but we couldn't statically determine the
11896     // size of the referenced object.
11897     switch (Info.EvalMode) {
11898     case EvalInfo::EM_ConstantExpression:
11899     case EvalInfo::EM_ConstantFold:
11900     case EvalInfo::EM_IgnoreSideEffects:
11901       // Leave it to IR generation.
11902       return Error(E);
11903     case EvalInfo::EM_ConstantExpressionUnevaluated:
11904       // Reduce it to a constant now.
11905       return Success((Type & 2) ? 0 : -1, E);
11906     }
11907 
11908     llvm_unreachable("unexpected EvalMode");
11909   }
11910 
11911   case Builtin::BI__builtin_os_log_format_buffer_size: {
11912     analyze_os_log::OSLogBufferLayout Layout;
11913     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11914     return Success(Layout.size().getQuantity(), E);
11915   }
11916 
11917   case Builtin::BI__builtin_is_aligned: {
11918     APValue Src;
11919     APSInt Alignment;
11920     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11921       return false;
11922     if (Src.isLValue()) {
11923       // If we evaluated a pointer, check the minimum known alignment.
11924       LValue Ptr;
11925       Ptr.setFrom(Info.Ctx, Src);
11926       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11927       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11928       // We can return true if the known alignment at the computed offset is
11929       // greater than the requested alignment.
11930       assert(PtrAlign.isPowerOfTwo());
11931       assert(Alignment.isPowerOf2());
11932       if (PtrAlign.getQuantity() >= Alignment)
11933         return Success(1, E);
11934       // If the alignment is not known to be sufficient, some cases could still
11935       // be aligned at run time. However, if the requested alignment is less or
11936       // equal to the base alignment and the offset is not aligned, we know that
11937       // the run-time value can never be aligned.
11938       if (BaseAlignment.getQuantity() >= Alignment &&
11939           PtrAlign.getQuantity() < Alignment)
11940         return Success(0, E);
11941       // Otherwise we can't infer whether the value is sufficiently aligned.
11942       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11943       //  in cases where we can't fully evaluate the pointer.
11944       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11945           << Alignment;
11946       return false;
11947     }
11948     assert(Src.isInt());
11949     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11950   }
11951   case Builtin::BI__builtin_align_up: {
11952     APValue Src;
11953     APSInt Alignment;
11954     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11955       return false;
11956     if (!Src.isInt())
11957       return Error(E);
11958     APSInt AlignedVal =
11959         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11960                Src.getInt().isUnsigned());
11961     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11962     return Success(AlignedVal, E);
11963   }
11964   case Builtin::BI__builtin_align_down: {
11965     APValue Src;
11966     APSInt Alignment;
11967     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11968       return false;
11969     if (!Src.isInt())
11970       return Error(E);
11971     APSInt AlignedVal =
11972         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11973     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11974     return Success(AlignedVal, E);
11975   }
11976 
11977   case Builtin::BI__builtin_bitreverse8:
11978   case Builtin::BI__builtin_bitreverse16:
11979   case Builtin::BI__builtin_bitreverse32:
11980   case Builtin::BI__builtin_bitreverse64: {
11981     APSInt Val;
11982     if (!EvaluateInteger(E->getArg(0), Val, Info))
11983       return false;
11984 
11985     return Success(Val.reverseBits(), E);
11986   }
11987 
11988   case Builtin::BI__builtin_bswap16:
11989   case Builtin::BI__builtin_bswap32:
11990   case Builtin::BI__builtin_bswap64: {
11991     APSInt Val;
11992     if (!EvaluateInteger(E->getArg(0), Val, Info))
11993       return false;
11994 
11995     return Success(Val.byteSwap(), E);
11996   }
11997 
11998   case Builtin::BI__builtin_classify_type:
11999     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
12000 
12001   case Builtin::BI__builtin_clrsb:
12002   case Builtin::BI__builtin_clrsbl:
12003   case Builtin::BI__builtin_clrsbll: {
12004     APSInt Val;
12005     if (!EvaluateInteger(E->getArg(0), Val, Info))
12006       return false;
12007 
12008     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
12009   }
12010 
12011   case Builtin::BI__builtin_clz:
12012   case Builtin::BI__builtin_clzl:
12013   case Builtin::BI__builtin_clzll:
12014   case Builtin::BI__builtin_clzs: {
12015     APSInt Val;
12016     if (!EvaluateInteger(E->getArg(0), Val, Info))
12017       return false;
12018     if (!Val)
12019       return Error(E);
12020 
12021     return Success(Val.countLeadingZeros(), E);
12022   }
12023 
12024   case Builtin::BI__builtin_constant_p: {
12025     const Expr *Arg = E->getArg(0);
12026     if (EvaluateBuiltinConstantP(Info, Arg))
12027       return Success(true, E);
12028     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
12029       // Outside a constant context, eagerly evaluate to false in the presence
12030       // of side-effects in order to avoid -Wunsequenced false-positives in
12031       // a branch on __builtin_constant_p(expr).
12032       return Success(false, E);
12033     }
12034     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12035     return false;
12036   }
12037 
12038   case Builtin::BI__builtin_is_constant_evaluated: {
12039     const auto *Callee = Info.CurrentCall->getCallee();
12040     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
12041         (Info.CallStackDepth == 1 ||
12042          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
12043           Callee->getIdentifier() &&
12044           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
12045       // FIXME: Find a better way to avoid duplicated diagnostics.
12046       if (Info.EvalStatus.Diag)
12047         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
12048                                                : Info.CurrentCall->CallLoc,
12049                     diag::warn_is_constant_evaluated_always_true_constexpr)
12050             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
12051                                          : "std::is_constant_evaluated");
12052     }
12053 
12054     return Success(Info.InConstantContext, E);
12055   }
12056 
12057   case Builtin::BI__builtin_ctz:
12058   case Builtin::BI__builtin_ctzl:
12059   case Builtin::BI__builtin_ctzll:
12060   case Builtin::BI__builtin_ctzs: {
12061     APSInt Val;
12062     if (!EvaluateInteger(E->getArg(0), Val, Info))
12063       return false;
12064     if (!Val)
12065       return Error(E);
12066 
12067     return Success(Val.countTrailingZeros(), E);
12068   }
12069 
12070   case Builtin::BI__builtin_eh_return_data_regno: {
12071     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12072     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
12073     return Success(Operand, E);
12074   }
12075 
12076   case Builtin::BI__builtin_expect:
12077   case Builtin::BI__builtin_expect_with_probability:
12078     return Visit(E->getArg(0));
12079 
12080   case Builtin::BI__builtin_ffs:
12081   case Builtin::BI__builtin_ffsl:
12082   case Builtin::BI__builtin_ffsll: {
12083     APSInt Val;
12084     if (!EvaluateInteger(E->getArg(0), Val, Info))
12085       return false;
12086 
12087     unsigned N = Val.countTrailingZeros();
12088     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
12089   }
12090 
12091   case Builtin::BI__builtin_fpclassify: {
12092     APFloat Val(0.0);
12093     if (!EvaluateFloat(E->getArg(5), Val, Info))
12094       return false;
12095     unsigned Arg;
12096     switch (Val.getCategory()) {
12097     case APFloat::fcNaN: Arg = 0; break;
12098     case APFloat::fcInfinity: Arg = 1; break;
12099     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
12100     case APFloat::fcZero: Arg = 4; break;
12101     }
12102     return Visit(E->getArg(Arg));
12103   }
12104 
12105   case Builtin::BI__builtin_isinf_sign: {
12106     APFloat Val(0.0);
12107     return EvaluateFloat(E->getArg(0), Val, Info) &&
12108            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
12109   }
12110 
12111   case Builtin::BI__builtin_isinf: {
12112     APFloat Val(0.0);
12113     return EvaluateFloat(E->getArg(0), Val, Info) &&
12114            Success(Val.isInfinity() ? 1 : 0, E);
12115   }
12116 
12117   case Builtin::BI__builtin_isfinite: {
12118     APFloat Val(0.0);
12119     return EvaluateFloat(E->getArg(0), Val, Info) &&
12120            Success(Val.isFinite() ? 1 : 0, E);
12121   }
12122 
12123   case Builtin::BI__builtin_isnan: {
12124     APFloat Val(0.0);
12125     return EvaluateFloat(E->getArg(0), Val, Info) &&
12126            Success(Val.isNaN() ? 1 : 0, E);
12127   }
12128 
12129   case Builtin::BI__builtin_isnormal: {
12130     APFloat Val(0.0);
12131     return EvaluateFloat(E->getArg(0), Val, Info) &&
12132            Success(Val.isNormal() ? 1 : 0, E);
12133   }
12134 
12135   case Builtin::BI__builtin_parity:
12136   case Builtin::BI__builtin_parityl:
12137   case Builtin::BI__builtin_parityll: {
12138     APSInt Val;
12139     if (!EvaluateInteger(E->getArg(0), Val, Info))
12140       return false;
12141 
12142     return Success(Val.countPopulation() % 2, E);
12143   }
12144 
12145   case Builtin::BI__builtin_popcount:
12146   case Builtin::BI__builtin_popcountl:
12147   case Builtin::BI__builtin_popcountll: {
12148     APSInt Val;
12149     if (!EvaluateInteger(E->getArg(0), Val, Info))
12150       return false;
12151 
12152     return Success(Val.countPopulation(), E);
12153   }
12154 
12155   case Builtin::BI__builtin_rotateleft8:
12156   case Builtin::BI__builtin_rotateleft16:
12157   case Builtin::BI__builtin_rotateleft32:
12158   case Builtin::BI__builtin_rotateleft64:
12159   case Builtin::BI_rotl8: // Microsoft variants of rotate right
12160   case Builtin::BI_rotl16:
12161   case Builtin::BI_rotl:
12162   case Builtin::BI_lrotl:
12163   case Builtin::BI_rotl64: {
12164     APSInt Val, Amt;
12165     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12166         !EvaluateInteger(E->getArg(1), Amt, Info))
12167       return false;
12168 
12169     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
12170   }
12171 
12172   case Builtin::BI__builtin_rotateright8:
12173   case Builtin::BI__builtin_rotateright16:
12174   case Builtin::BI__builtin_rotateright32:
12175   case Builtin::BI__builtin_rotateright64:
12176   case Builtin::BI_rotr8: // Microsoft variants of rotate right
12177   case Builtin::BI_rotr16:
12178   case Builtin::BI_rotr:
12179   case Builtin::BI_lrotr:
12180   case Builtin::BI_rotr64: {
12181     APSInt Val, Amt;
12182     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12183         !EvaluateInteger(E->getArg(1), Amt, Info))
12184       return false;
12185 
12186     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
12187   }
12188 
12189   case Builtin::BIstrlen:
12190   case Builtin::BIwcslen:
12191     // A call to strlen is not a constant expression.
12192     if (Info.getLangOpts().CPlusPlus11)
12193       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12194           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12195           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12196     else
12197       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12198     [[fallthrough]];
12199   case Builtin::BI__builtin_strlen:
12200   case Builtin::BI__builtin_wcslen: {
12201     // As an extension, we support __builtin_strlen() as a constant expression,
12202     // and support folding strlen() to a constant.
12203     uint64_t StrLen;
12204     if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12205       return Success(StrLen, E);
12206     return false;
12207   }
12208 
12209   case Builtin::BIstrcmp:
12210   case Builtin::BIwcscmp:
12211   case Builtin::BIstrncmp:
12212   case Builtin::BIwcsncmp:
12213   case Builtin::BImemcmp:
12214   case Builtin::BIbcmp:
12215   case Builtin::BIwmemcmp:
12216     // A call to strlen is not a constant expression.
12217     if (Info.getLangOpts().CPlusPlus11)
12218       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12219           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12220           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12221     else
12222       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12223     [[fallthrough]];
12224   case Builtin::BI__builtin_strcmp:
12225   case Builtin::BI__builtin_wcscmp:
12226   case Builtin::BI__builtin_strncmp:
12227   case Builtin::BI__builtin_wcsncmp:
12228   case Builtin::BI__builtin_memcmp:
12229   case Builtin::BI__builtin_bcmp:
12230   case Builtin::BI__builtin_wmemcmp: {
12231     LValue String1, String2;
12232     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12233         !EvaluatePointer(E->getArg(1), String2, Info))
12234       return false;
12235 
12236     uint64_t MaxLength = uint64_t(-1);
12237     if (BuiltinOp != Builtin::BIstrcmp &&
12238         BuiltinOp != Builtin::BIwcscmp &&
12239         BuiltinOp != Builtin::BI__builtin_strcmp &&
12240         BuiltinOp != Builtin::BI__builtin_wcscmp) {
12241       APSInt N;
12242       if (!EvaluateInteger(E->getArg(2), N, Info))
12243         return false;
12244       MaxLength = N.getExtValue();
12245     }
12246 
12247     // Empty substrings compare equal by definition.
12248     if (MaxLength == 0u)
12249       return Success(0, E);
12250 
12251     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12252         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12253         String1.Designator.Invalid || String2.Designator.Invalid)
12254       return false;
12255 
12256     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12257     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12258 
12259     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12260                      BuiltinOp == Builtin::BIbcmp ||
12261                      BuiltinOp == Builtin::BI__builtin_memcmp ||
12262                      BuiltinOp == Builtin::BI__builtin_bcmp;
12263 
12264     assert(IsRawByte ||
12265            (Info.Ctx.hasSameUnqualifiedType(
12266                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12267             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12268 
12269     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12270     // 'char8_t', but no other types.
12271     if (IsRawByte &&
12272         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12273       // FIXME: Consider using our bit_cast implementation to support this.
12274       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12275           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
12276           << CharTy1 << CharTy2;
12277       return false;
12278     }
12279 
12280     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12281       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12282              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12283              Char1.isInt() && Char2.isInt();
12284     };
12285     const auto &AdvanceElems = [&] {
12286       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12287              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12288     };
12289 
12290     bool StopAtNull =
12291         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12292          BuiltinOp != Builtin::BIwmemcmp &&
12293          BuiltinOp != Builtin::BI__builtin_memcmp &&
12294          BuiltinOp != Builtin::BI__builtin_bcmp &&
12295          BuiltinOp != Builtin::BI__builtin_wmemcmp);
12296     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12297                   BuiltinOp == Builtin::BIwcsncmp ||
12298                   BuiltinOp == Builtin::BIwmemcmp ||
12299                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
12300                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12301                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
12302 
12303     for (; MaxLength; --MaxLength) {
12304       APValue Char1, Char2;
12305       if (!ReadCurElems(Char1, Char2))
12306         return false;
12307       if (Char1.getInt().ne(Char2.getInt())) {
12308         if (IsWide) // wmemcmp compares with wchar_t signedness.
12309           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12310         // memcmp always compares unsigned chars.
12311         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12312       }
12313       if (StopAtNull && !Char1.getInt())
12314         return Success(0, E);
12315       assert(!(StopAtNull && !Char2.getInt()));
12316       if (!AdvanceElems())
12317         return false;
12318     }
12319     // We hit the strncmp / memcmp limit.
12320     return Success(0, E);
12321   }
12322 
12323   case Builtin::BI__atomic_always_lock_free:
12324   case Builtin::BI__atomic_is_lock_free:
12325   case Builtin::BI__c11_atomic_is_lock_free: {
12326     APSInt SizeVal;
12327     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12328       return false;
12329 
12330     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12331     // of two less than or equal to the maximum inline atomic width, we know it
12332     // is lock-free.  If the size isn't a power of two, or greater than the
12333     // maximum alignment where we promote atomics, we know it is not lock-free
12334     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
12335     // the answer can only be determined at runtime; for example, 16-byte
12336     // atomics have lock-free implementations on some, but not all,
12337     // x86-64 processors.
12338 
12339     // Check power-of-two.
12340     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12341     if (Size.isPowerOfTwo()) {
12342       // Check against inlining width.
12343       unsigned InlineWidthBits =
12344           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12345       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12346         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12347             Size == CharUnits::One() ||
12348             E->getArg(1)->isNullPointerConstant(Info.Ctx,
12349                                                 Expr::NPC_NeverValueDependent))
12350           // OK, we will inline appropriately-aligned operations of this size,
12351           // and _Atomic(T) is appropriately-aligned.
12352           return Success(1, E);
12353 
12354         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12355           castAs<PointerType>()->getPointeeType();
12356         if (!PointeeType->isIncompleteType() &&
12357             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12358           // OK, we will inline operations on this object.
12359           return Success(1, E);
12360         }
12361       }
12362     }
12363 
12364     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12365         Success(0, E) : Error(E);
12366   }
12367   case Builtin::BI__builtin_add_overflow:
12368   case Builtin::BI__builtin_sub_overflow:
12369   case Builtin::BI__builtin_mul_overflow:
12370   case Builtin::BI__builtin_sadd_overflow:
12371   case Builtin::BI__builtin_uadd_overflow:
12372   case Builtin::BI__builtin_uaddl_overflow:
12373   case Builtin::BI__builtin_uaddll_overflow:
12374   case Builtin::BI__builtin_usub_overflow:
12375   case Builtin::BI__builtin_usubl_overflow:
12376   case Builtin::BI__builtin_usubll_overflow:
12377   case Builtin::BI__builtin_umul_overflow:
12378   case Builtin::BI__builtin_umull_overflow:
12379   case Builtin::BI__builtin_umulll_overflow:
12380   case Builtin::BI__builtin_saddl_overflow:
12381   case Builtin::BI__builtin_saddll_overflow:
12382   case Builtin::BI__builtin_ssub_overflow:
12383   case Builtin::BI__builtin_ssubl_overflow:
12384   case Builtin::BI__builtin_ssubll_overflow:
12385   case Builtin::BI__builtin_smul_overflow:
12386   case Builtin::BI__builtin_smull_overflow:
12387   case Builtin::BI__builtin_smulll_overflow: {
12388     LValue ResultLValue;
12389     APSInt LHS, RHS;
12390 
12391     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12392     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12393         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12394         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12395       return false;
12396 
12397     APSInt Result;
12398     bool DidOverflow = false;
12399 
12400     // If the types don't have to match, enlarge all 3 to the largest of them.
12401     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12402         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12403         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12404       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12405                       ResultType->isSignedIntegerOrEnumerationType();
12406       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12407                       ResultType->isSignedIntegerOrEnumerationType();
12408       uint64_t LHSSize = LHS.getBitWidth();
12409       uint64_t RHSSize = RHS.getBitWidth();
12410       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12411       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12412 
12413       // Add an additional bit if the signedness isn't uniformly agreed to. We
12414       // could do this ONLY if there is a signed and an unsigned that both have
12415       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12416       // caught in the shrink-to-result later anyway.
12417       if (IsSigned && !AllSigned)
12418         ++MaxBits;
12419 
12420       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12421       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12422       Result = APSInt(MaxBits, !IsSigned);
12423     }
12424 
12425     // Find largest int.
12426     switch (BuiltinOp) {
12427     default:
12428       llvm_unreachable("Invalid value for BuiltinOp");
12429     case Builtin::BI__builtin_add_overflow:
12430     case Builtin::BI__builtin_sadd_overflow:
12431     case Builtin::BI__builtin_saddl_overflow:
12432     case Builtin::BI__builtin_saddll_overflow:
12433     case Builtin::BI__builtin_uadd_overflow:
12434     case Builtin::BI__builtin_uaddl_overflow:
12435     case Builtin::BI__builtin_uaddll_overflow:
12436       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12437                               : LHS.uadd_ov(RHS, DidOverflow);
12438       break;
12439     case Builtin::BI__builtin_sub_overflow:
12440     case Builtin::BI__builtin_ssub_overflow:
12441     case Builtin::BI__builtin_ssubl_overflow:
12442     case Builtin::BI__builtin_ssubll_overflow:
12443     case Builtin::BI__builtin_usub_overflow:
12444     case Builtin::BI__builtin_usubl_overflow:
12445     case Builtin::BI__builtin_usubll_overflow:
12446       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12447                               : LHS.usub_ov(RHS, DidOverflow);
12448       break;
12449     case Builtin::BI__builtin_mul_overflow:
12450     case Builtin::BI__builtin_smul_overflow:
12451     case Builtin::BI__builtin_smull_overflow:
12452     case Builtin::BI__builtin_smulll_overflow:
12453     case Builtin::BI__builtin_umul_overflow:
12454     case Builtin::BI__builtin_umull_overflow:
12455     case Builtin::BI__builtin_umulll_overflow:
12456       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12457                               : LHS.umul_ov(RHS, DidOverflow);
12458       break;
12459     }
12460 
12461     // In the case where multiple sizes are allowed, truncate and see if
12462     // the values are the same.
12463     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12464         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12465         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12466       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12467       // since it will give us the behavior of a TruncOrSelf in the case where
12468       // its parameter <= its size.  We previously set Result to be at least the
12469       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12470       // will work exactly like TruncOrSelf.
12471       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12472       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12473 
12474       if (!APSInt::isSameValue(Temp, Result))
12475         DidOverflow = true;
12476       Result = Temp;
12477     }
12478 
12479     APValue APV{Result};
12480     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12481       return false;
12482     return Success(DidOverflow, E);
12483   }
12484   }
12485 }
12486 
12487 /// Determine whether this is a pointer past the end of the complete
12488 /// object referred to by the lvalue.
isOnePastTheEndOfCompleteObject(const ASTContext & Ctx,const LValue & LV)12489 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12490                                             const LValue &LV) {
12491   // A null pointer can be viewed as being "past the end" but we don't
12492   // choose to look at it that way here.
12493   if (!LV.getLValueBase())
12494     return false;
12495 
12496   // If the designator is valid and refers to a subobject, we're not pointing
12497   // past the end.
12498   if (!LV.getLValueDesignator().Invalid &&
12499       !LV.getLValueDesignator().isOnePastTheEnd())
12500     return false;
12501 
12502   // A pointer to an incomplete type might be past-the-end if the type's size is
12503   // zero.  We cannot tell because the type is incomplete.
12504   QualType Ty = getType(LV.getLValueBase());
12505   if (Ty->isIncompleteType())
12506     return true;
12507 
12508   // We're a past-the-end pointer if we point to the byte after the object,
12509   // no matter what our type or path is.
12510   auto Size = Ctx.getTypeSizeInChars(Ty);
12511   return LV.getLValueOffset() == Size;
12512 }
12513 
12514 namespace {
12515 
12516 /// Data recursive integer evaluator of certain binary operators.
12517 ///
12518 /// We use a data recursive algorithm for binary operators so that we are able
12519 /// to handle extreme cases of chained binary operators without causing stack
12520 /// overflow.
12521 class DataRecursiveIntBinOpEvaluator {
12522   struct EvalResult {
12523     APValue Val;
12524     bool Failed;
12525 
EvalResult__anond52d8a672a11::DataRecursiveIntBinOpEvaluator::EvalResult12526     EvalResult() : Failed(false) { }
12527 
swap__anond52d8a672a11::DataRecursiveIntBinOpEvaluator::EvalResult12528     void swap(EvalResult &RHS) {
12529       Val.swap(RHS.Val);
12530       Failed = RHS.Failed;
12531       RHS.Failed = false;
12532     }
12533   };
12534 
12535   struct Job {
12536     const Expr *E;
12537     EvalResult LHSResult; // meaningful only for binary operator expression.
12538     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12539 
12540     Job() = default;
12541     Job(Job &&) = default;
12542 
startSpeculativeEval__anond52d8a672a11::DataRecursiveIntBinOpEvaluator::Job12543     void startSpeculativeEval(EvalInfo &Info) {
12544       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12545     }
12546 
12547   private:
12548     SpeculativeEvaluationRAII SpecEvalRAII;
12549   };
12550 
12551   SmallVector<Job, 16> Queue;
12552 
12553   IntExprEvaluator &IntEval;
12554   EvalInfo &Info;
12555   APValue &FinalResult;
12556 
12557 public:
DataRecursiveIntBinOpEvaluator(IntExprEvaluator & IntEval,APValue & Result)12558   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12559     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12560 
12561   /// True if \param E is a binary operator that we are going to handle
12562   /// data recursively.
12563   /// We handle binary operators that are comma, logical, or that have operands
12564   /// with integral or enumeration type.
shouldEnqueue(const BinaryOperator * E)12565   static bool shouldEnqueue(const BinaryOperator *E) {
12566     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12567            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12568             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12569             E->getRHS()->getType()->isIntegralOrEnumerationType());
12570   }
12571 
Traverse(const BinaryOperator * E)12572   bool Traverse(const BinaryOperator *E) {
12573     enqueue(E);
12574     EvalResult PrevResult;
12575     while (!Queue.empty())
12576       process(PrevResult);
12577 
12578     if (PrevResult.Failed) return false;
12579 
12580     FinalResult.swap(PrevResult.Val);
12581     return true;
12582   }
12583 
12584 private:
Success(uint64_t Value,const Expr * E,APValue & Result)12585   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12586     return IntEval.Success(Value, E, Result);
12587   }
Success(const APSInt & Value,const Expr * E,APValue & Result)12588   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12589     return IntEval.Success(Value, E, Result);
12590   }
Error(const Expr * E)12591   bool Error(const Expr *E) {
12592     return IntEval.Error(E);
12593   }
Error(const Expr * E,diag::kind D)12594   bool Error(const Expr *E, diag::kind D) {
12595     return IntEval.Error(E, D);
12596   }
12597 
CCEDiag(const Expr * E,diag::kind D)12598   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12599     return Info.CCEDiag(E, D);
12600   }
12601 
12602   // Returns true if visiting the RHS is necessary, false otherwise.
12603   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12604                          bool &SuppressRHSDiags);
12605 
12606   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12607                   const BinaryOperator *E, APValue &Result);
12608 
EvaluateExpr(const Expr * E,EvalResult & Result)12609   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12610     Result.Failed = !Evaluate(Result.Val, Info, E);
12611     if (Result.Failed)
12612       Result.Val = APValue();
12613   }
12614 
12615   void process(EvalResult &Result);
12616 
enqueue(const Expr * E)12617   void enqueue(const Expr *E) {
12618     E = E->IgnoreParens();
12619     Queue.resize(Queue.size()+1);
12620     Queue.back().E = E;
12621     Queue.back().Kind = Job::AnyExprKind;
12622   }
12623 };
12624 
12625 }
12626 
12627 bool DataRecursiveIntBinOpEvaluator::
VisitBinOpLHSOnly(EvalResult & LHSResult,const BinaryOperator * E,bool & SuppressRHSDiags)12628        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12629                          bool &SuppressRHSDiags) {
12630   if (E->getOpcode() == BO_Comma) {
12631     // Ignore LHS but note if we could not evaluate it.
12632     if (LHSResult.Failed)
12633       return Info.noteSideEffect();
12634     return true;
12635   }
12636 
12637   if (E->isLogicalOp()) {
12638     bool LHSAsBool;
12639     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12640       // We were able to evaluate the LHS, see if we can get away with not
12641       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12642       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12643         Success(LHSAsBool, E, LHSResult.Val);
12644         return false; // Ignore RHS
12645       }
12646     } else {
12647       LHSResult.Failed = true;
12648 
12649       // Since we weren't able to evaluate the left hand side, it
12650       // might have had side effects.
12651       if (!Info.noteSideEffect())
12652         return false;
12653 
12654       // We can't evaluate the LHS; however, sometimes the result
12655       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12656       // Don't ignore RHS and suppress diagnostics from this arm.
12657       SuppressRHSDiags = true;
12658     }
12659 
12660     return true;
12661   }
12662 
12663   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12664          E->getRHS()->getType()->isIntegralOrEnumerationType());
12665 
12666   if (LHSResult.Failed && !Info.noteFailure())
12667     return false; // Ignore RHS;
12668 
12669   return true;
12670 }
12671 
addOrSubLValueAsInteger(APValue & LVal,const APSInt & Index,bool IsSub)12672 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12673                                     bool IsSub) {
12674   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12675   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12676   // offsets.
12677   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12678   CharUnits &Offset = LVal.getLValueOffset();
12679   uint64_t Offset64 = Offset.getQuantity();
12680   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12681   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12682                                          : Offset64 + Index64);
12683 }
12684 
12685 bool DataRecursiveIntBinOpEvaluator::
VisitBinOp(const EvalResult & LHSResult,const EvalResult & RHSResult,const BinaryOperator * E,APValue & Result)12686        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12687                   const BinaryOperator *E, APValue &Result) {
12688   if (E->getOpcode() == BO_Comma) {
12689     if (RHSResult.Failed)
12690       return false;
12691     Result = RHSResult.Val;
12692     return true;
12693   }
12694 
12695   if (E->isLogicalOp()) {
12696     bool lhsResult, rhsResult;
12697     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12698     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12699 
12700     if (LHSIsOK) {
12701       if (RHSIsOK) {
12702         if (E->getOpcode() == BO_LOr)
12703           return Success(lhsResult || rhsResult, E, Result);
12704         else
12705           return Success(lhsResult && rhsResult, E, Result);
12706       }
12707     } else {
12708       if (RHSIsOK) {
12709         // We can't evaluate the LHS; however, sometimes the result
12710         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12711         if (rhsResult == (E->getOpcode() == BO_LOr))
12712           return Success(rhsResult, E, Result);
12713       }
12714     }
12715 
12716     return false;
12717   }
12718 
12719   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12720          E->getRHS()->getType()->isIntegralOrEnumerationType());
12721 
12722   if (LHSResult.Failed || RHSResult.Failed)
12723     return false;
12724 
12725   const APValue &LHSVal = LHSResult.Val;
12726   const APValue &RHSVal = RHSResult.Val;
12727 
12728   // Handle cases like (unsigned long)&a + 4.
12729   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12730     Result = LHSVal;
12731     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12732     return true;
12733   }
12734 
12735   // Handle cases like 4 + (unsigned long)&a
12736   if (E->getOpcode() == BO_Add &&
12737       RHSVal.isLValue() && LHSVal.isInt()) {
12738     Result = RHSVal;
12739     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12740     return true;
12741   }
12742 
12743   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12744     // Handle (intptr_t)&&A - (intptr_t)&&B.
12745     if (!LHSVal.getLValueOffset().isZero() ||
12746         !RHSVal.getLValueOffset().isZero())
12747       return false;
12748     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12749     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12750     if (!LHSExpr || !RHSExpr)
12751       return false;
12752     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12753     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12754     if (!LHSAddrExpr || !RHSAddrExpr)
12755       return false;
12756     // Make sure both labels come from the same function.
12757     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12758         RHSAddrExpr->getLabel()->getDeclContext())
12759       return false;
12760     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12761     return true;
12762   }
12763 
12764   // All the remaining cases expect both operands to be an integer
12765   if (!LHSVal.isInt() || !RHSVal.isInt())
12766     return Error(E);
12767 
12768   // Set up the width and signedness manually, in case it can't be deduced
12769   // from the operation we're performing.
12770   // FIXME: Don't do this in the cases where we can deduce it.
12771   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12772                E->getType()->isUnsignedIntegerOrEnumerationType());
12773   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12774                          RHSVal.getInt(), Value))
12775     return false;
12776   return Success(Value, E, Result);
12777 }
12778 
process(EvalResult & Result)12779 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12780   Job &job = Queue.back();
12781 
12782   switch (job.Kind) {
12783     case Job::AnyExprKind: {
12784       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12785         if (shouldEnqueue(Bop)) {
12786           job.Kind = Job::BinOpKind;
12787           enqueue(Bop->getLHS());
12788           return;
12789         }
12790       }
12791 
12792       EvaluateExpr(job.E, Result);
12793       Queue.pop_back();
12794       return;
12795     }
12796 
12797     case Job::BinOpKind: {
12798       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12799       bool SuppressRHSDiags = false;
12800       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12801         Queue.pop_back();
12802         return;
12803       }
12804       if (SuppressRHSDiags)
12805         job.startSpeculativeEval(Info);
12806       job.LHSResult.swap(Result);
12807       job.Kind = Job::BinOpVisitedLHSKind;
12808       enqueue(Bop->getRHS());
12809       return;
12810     }
12811 
12812     case Job::BinOpVisitedLHSKind: {
12813       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12814       EvalResult RHS;
12815       RHS.swap(Result);
12816       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12817       Queue.pop_back();
12818       return;
12819     }
12820   }
12821 
12822   llvm_unreachable("Invalid Job::Kind!");
12823 }
12824 
12825 namespace {
12826 enum class CmpResult {
12827   Unequal,
12828   Less,
12829   Equal,
12830   Greater,
12831   Unordered,
12832 };
12833 }
12834 
12835 template <class SuccessCB, class AfterCB>
12836 static bool
EvaluateComparisonBinaryOperator(EvalInfo & Info,const BinaryOperator * E,SuccessCB && Success,AfterCB && DoAfter)12837 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12838                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12839   assert(!E->isValueDependent());
12840   assert(E->isComparisonOp() && "expected comparison operator");
12841   assert((E->getOpcode() == BO_Cmp ||
12842           E->getType()->isIntegralOrEnumerationType()) &&
12843          "unsupported binary expression evaluation");
12844   auto Error = [&](const Expr *E) {
12845     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12846     return false;
12847   };
12848 
12849   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12850   bool IsEquality = E->isEqualityOp();
12851 
12852   QualType LHSTy = E->getLHS()->getType();
12853   QualType RHSTy = E->getRHS()->getType();
12854 
12855   if (LHSTy->isIntegralOrEnumerationType() &&
12856       RHSTy->isIntegralOrEnumerationType()) {
12857     APSInt LHS, RHS;
12858     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12859     if (!LHSOK && !Info.noteFailure())
12860       return false;
12861     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12862       return false;
12863     if (LHS < RHS)
12864       return Success(CmpResult::Less, E);
12865     if (LHS > RHS)
12866       return Success(CmpResult::Greater, E);
12867     return Success(CmpResult::Equal, E);
12868   }
12869 
12870   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12871     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12872     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12873 
12874     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12875     if (!LHSOK && !Info.noteFailure())
12876       return false;
12877     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12878       return false;
12879     if (LHSFX < RHSFX)
12880       return Success(CmpResult::Less, E);
12881     if (LHSFX > RHSFX)
12882       return Success(CmpResult::Greater, E);
12883     return Success(CmpResult::Equal, E);
12884   }
12885 
12886   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12887     ComplexValue LHS, RHS;
12888     bool LHSOK;
12889     if (E->isAssignmentOp()) {
12890       LValue LV;
12891       EvaluateLValue(E->getLHS(), LV, Info);
12892       LHSOK = false;
12893     } else if (LHSTy->isRealFloatingType()) {
12894       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12895       if (LHSOK) {
12896         LHS.makeComplexFloat();
12897         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12898       }
12899     } else {
12900       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12901     }
12902     if (!LHSOK && !Info.noteFailure())
12903       return false;
12904 
12905     if (E->getRHS()->getType()->isRealFloatingType()) {
12906       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12907         return false;
12908       RHS.makeComplexFloat();
12909       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12910     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12911       return false;
12912 
12913     if (LHS.isComplexFloat()) {
12914       APFloat::cmpResult CR_r =
12915         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12916       APFloat::cmpResult CR_i =
12917         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12918       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12919       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12920     } else {
12921       assert(IsEquality && "invalid complex comparison");
12922       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12923                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12924       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12925     }
12926   }
12927 
12928   if (LHSTy->isRealFloatingType() &&
12929       RHSTy->isRealFloatingType()) {
12930     APFloat RHS(0.0), LHS(0.0);
12931 
12932     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12933     if (!LHSOK && !Info.noteFailure())
12934       return false;
12935 
12936     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12937       return false;
12938 
12939     assert(E->isComparisonOp() && "Invalid binary operator!");
12940     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12941     if (!Info.InConstantContext &&
12942         APFloatCmpResult == APFloat::cmpUnordered &&
12943         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12944       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12945       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12946       return false;
12947     }
12948     auto GetCmpRes = [&]() {
12949       switch (APFloatCmpResult) {
12950       case APFloat::cmpEqual:
12951         return CmpResult::Equal;
12952       case APFloat::cmpLessThan:
12953         return CmpResult::Less;
12954       case APFloat::cmpGreaterThan:
12955         return CmpResult::Greater;
12956       case APFloat::cmpUnordered:
12957         return CmpResult::Unordered;
12958       }
12959       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12960     };
12961     return Success(GetCmpRes(), E);
12962   }
12963 
12964   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12965     LValue LHSValue, RHSValue;
12966 
12967     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12968     if (!LHSOK && !Info.noteFailure())
12969       return false;
12970 
12971     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12972       return false;
12973 
12974     // Reject differing bases from the normal codepath; we special-case
12975     // comparisons to null.
12976     if (!HasSameBase(LHSValue, RHSValue)) {
12977       auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
12978         std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
12979         std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
12980         Info.FFDiag(E, DiagID)
12981             << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
12982         return false;
12983       };
12984       // Inequalities and subtractions between unrelated pointers have
12985       // unspecified or undefined behavior.
12986       if (!IsEquality)
12987         return DiagComparison(
12988             diag::note_constexpr_pointer_comparison_unspecified);
12989       // A constant address may compare equal to the address of a symbol.
12990       // The one exception is that address of an object cannot compare equal
12991       // to a null pointer constant.
12992       // TODO: Should we restrict this to actual null pointers, and exclude the
12993       // case of zero cast to pointer type?
12994       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12995           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12996         return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
12997                               !RHSValue.Base);
12998       // It's implementation-defined whether distinct literals will have
12999       // distinct addresses. In clang, the result of such a comparison is
13000       // unspecified, so it is not a constant expression. However, we do know
13001       // that the address of a literal will be non-null.
13002       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
13003           LHSValue.Base && RHSValue.Base)
13004         return DiagComparison(diag::note_constexpr_literal_comparison);
13005       // We can't tell whether weak symbols will end up pointing to the same
13006       // object.
13007       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
13008         return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
13009                               !IsWeakLValue(LHSValue));
13010       // We can't compare the address of the start of one object with the
13011       // past-the-end address of another object, per C++ DR1652.
13012       if (LHSValue.Base && LHSValue.Offset.isZero() &&
13013           isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
13014         return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13015                               true);
13016       if (RHSValue.Base && RHSValue.Offset.isZero() &&
13017            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
13018         return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13019                               false);
13020       // We can't tell whether an object is at the same address as another
13021       // zero sized object.
13022       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
13023           (LHSValue.Base && isZeroSized(RHSValue)))
13024         return DiagComparison(
13025             diag::note_constexpr_pointer_comparison_zero_sized);
13026       return Success(CmpResult::Unequal, E);
13027     }
13028 
13029     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13030     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13031 
13032     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13033     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13034 
13035     // C++11 [expr.rel]p3:
13036     //   Pointers to void (after pointer conversions) can be compared, with a
13037     //   result defined as follows: If both pointers represent the same
13038     //   address or are both the null pointer value, the result is true if the
13039     //   operator is <= or >= and false otherwise; otherwise the result is
13040     //   unspecified.
13041     // We interpret this as applying to pointers to *cv* void.
13042     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
13043       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
13044 
13045     // C++11 [expr.rel]p2:
13046     // - If two pointers point to non-static data members of the same object,
13047     //   or to subobjects or array elements fo such members, recursively, the
13048     //   pointer to the later declared member compares greater provided the
13049     //   two members have the same access control and provided their class is
13050     //   not a union.
13051     //   [...]
13052     // - Otherwise pointer comparisons are unspecified.
13053     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
13054       bool WasArrayIndex;
13055       unsigned Mismatch = FindDesignatorMismatch(
13056           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
13057       // At the point where the designators diverge, the comparison has a
13058       // specified value if:
13059       //  - we are comparing array indices
13060       //  - we are comparing fields of a union, or fields with the same access
13061       // Otherwise, the result is unspecified and thus the comparison is not a
13062       // constant expression.
13063       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
13064           Mismatch < RHSDesignator.Entries.size()) {
13065         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
13066         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
13067         if (!LF && !RF)
13068           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
13069         else if (!LF)
13070           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13071               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
13072               << RF->getParent() << RF;
13073         else if (!RF)
13074           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13075               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
13076               << LF->getParent() << LF;
13077         else if (!LF->getParent()->isUnion() &&
13078                  LF->getAccess() != RF->getAccess())
13079           Info.CCEDiag(E,
13080                        diag::note_constexpr_pointer_comparison_differing_access)
13081               << LF << LF->getAccess() << RF << RF->getAccess()
13082               << LF->getParent();
13083       }
13084     }
13085 
13086     // The comparison here must be unsigned, and performed with the same
13087     // width as the pointer.
13088     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
13089     uint64_t CompareLHS = LHSOffset.getQuantity();
13090     uint64_t CompareRHS = RHSOffset.getQuantity();
13091     assert(PtrSize <= 64 && "Unexpected pointer width");
13092     uint64_t Mask = ~0ULL >> (64 - PtrSize);
13093     CompareLHS &= Mask;
13094     CompareRHS &= Mask;
13095 
13096     // If there is a base and this is a relational operator, we can only
13097     // compare pointers within the object in question; otherwise, the result
13098     // depends on where the object is located in memory.
13099     if (!LHSValue.Base.isNull() && IsRelational) {
13100       QualType BaseTy = getType(LHSValue.Base);
13101       if (BaseTy->isIncompleteType())
13102         return Error(E);
13103       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
13104       uint64_t OffsetLimit = Size.getQuantity();
13105       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
13106         return Error(E);
13107     }
13108 
13109     if (CompareLHS < CompareRHS)
13110       return Success(CmpResult::Less, E);
13111     if (CompareLHS > CompareRHS)
13112       return Success(CmpResult::Greater, E);
13113     return Success(CmpResult::Equal, E);
13114   }
13115 
13116   if (LHSTy->isMemberPointerType()) {
13117     assert(IsEquality && "unexpected member pointer operation");
13118     assert(RHSTy->isMemberPointerType() && "invalid comparison");
13119 
13120     MemberPtr LHSValue, RHSValue;
13121 
13122     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
13123     if (!LHSOK && !Info.noteFailure())
13124       return false;
13125 
13126     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13127       return false;
13128 
13129     // If either operand is a pointer to a weak function, the comparison is not
13130     // constant.
13131     if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
13132       Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13133           << LHSValue.getDecl();
13134       return true;
13135     }
13136     if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
13137       Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13138           << RHSValue.getDecl();
13139       return true;
13140     }
13141 
13142     // C++11 [expr.eq]p2:
13143     //   If both operands are null, they compare equal. Otherwise if only one is
13144     //   null, they compare unequal.
13145     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
13146       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
13147       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13148     }
13149 
13150     //   Otherwise if either is a pointer to a virtual member function, the
13151     //   result is unspecified.
13152     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
13153       if (MD->isVirtual())
13154         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13155     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
13156       if (MD->isVirtual())
13157         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13158 
13159     //   Otherwise they compare equal if and only if they would refer to the
13160     //   same member of the same most derived object or the same subobject if
13161     //   they were dereferenced with a hypothetical object of the associated
13162     //   class type.
13163     bool Equal = LHSValue == RHSValue;
13164     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13165   }
13166 
13167   if (LHSTy->isNullPtrType()) {
13168     assert(E->isComparisonOp() && "unexpected nullptr operation");
13169     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
13170     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
13171     // are compared, the result is true of the operator is <=, >= or ==, and
13172     // false otherwise.
13173     return Success(CmpResult::Equal, E);
13174   }
13175 
13176   return DoAfter();
13177 }
13178 
VisitBinCmp(const BinaryOperator * E)13179 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
13180   if (!CheckLiteralType(Info, E))
13181     return false;
13182 
13183   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13184     ComparisonCategoryResult CCR;
13185     switch (CR) {
13186     case CmpResult::Unequal:
13187       llvm_unreachable("should never produce Unequal for three-way comparison");
13188     case CmpResult::Less:
13189       CCR = ComparisonCategoryResult::Less;
13190       break;
13191     case CmpResult::Equal:
13192       CCR = ComparisonCategoryResult::Equal;
13193       break;
13194     case CmpResult::Greater:
13195       CCR = ComparisonCategoryResult::Greater;
13196       break;
13197     case CmpResult::Unordered:
13198       CCR = ComparisonCategoryResult::Unordered;
13199       break;
13200     }
13201     // Evaluation succeeded. Lookup the information for the comparison category
13202     // type and fetch the VarDecl for the result.
13203     const ComparisonCategoryInfo &CmpInfo =
13204         Info.Ctx.CompCategories.getInfoForType(E->getType());
13205     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
13206     // Check and evaluate the result as a constant expression.
13207     LValue LV;
13208     LV.set(VD);
13209     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13210       return false;
13211     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
13212                                    ConstantExprKind::Normal);
13213   };
13214   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13215     return ExprEvaluatorBaseTy::VisitBinCmp(E);
13216   });
13217 }
13218 
VisitCXXParenListInitExpr(const CXXParenListInitExpr * E)13219 bool RecordExprEvaluator::VisitCXXParenListInitExpr(
13220     const CXXParenListInitExpr *E) {
13221   return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
13222 }
13223 
VisitBinaryOperator(const BinaryOperator * E)13224 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13225   // We don't support assignment in C. C++ assignments don't get here because
13226   // assignment is an lvalue in C++.
13227   if (E->isAssignmentOp()) {
13228     Error(E);
13229     if (!Info.noteFailure())
13230       return false;
13231   }
13232 
13233   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
13234     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
13235 
13236   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
13237           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
13238          "DataRecursiveIntBinOpEvaluator should have handled integral types");
13239 
13240   if (E->isComparisonOp()) {
13241     // Evaluate builtin binary comparisons by evaluating them as three-way
13242     // comparisons and then translating the result.
13243     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13244       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
13245              "should only produce Unequal for equality comparisons");
13246       bool IsEqual   = CR == CmpResult::Equal,
13247            IsLess    = CR == CmpResult::Less,
13248            IsGreater = CR == CmpResult::Greater;
13249       auto Op = E->getOpcode();
13250       switch (Op) {
13251       default:
13252         llvm_unreachable("unsupported binary operator");
13253       case BO_EQ:
13254       case BO_NE:
13255         return Success(IsEqual == (Op == BO_EQ), E);
13256       case BO_LT:
13257         return Success(IsLess, E);
13258       case BO_GT:
13259         return Success(IsGreater, E);
13260       case BO_LE:
13261         return Success(IsEqual || IsLess, E);
13262       case BO_GE:
13263         return Success(IsEqual || IsGreater, E);
13264       }
13265     };
13266     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13267       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13268     });
13269   }
13270 
13271   QualType LHSTy = E->getLHS()->getType();
13272   QualType RHSTy = E->getRHS()->getType();
13273 
13274   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13275       E->getOpcode() == BO_Sub) {
13276     LValue LHSValue, RHSValue;
13277 
13278     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13279     if (!LHSOK && !Info.noteFailure())
13280       return false;
13281 
13282     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13283       return false;
13284 
13285     // Reject differing bases from the normal codepath; we special-case
13286     // comparisons to null.
13287     if (!HasSameBase(LHSValue, RHSValue)) {
13288       // Handle &&A - &&B.
13289       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13290         return Error(E);
13291       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13292       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13293       if (!LHSExpr || !RHSExpr)
13294         return Error(E);
13295       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13296       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13297       if (!LHSAddrExpr || !RHSAddrExpr)
13298         return Error(E);
13299       // Make sure both labels come from the same function.
13300       if (LHSAddrExpr->getLabel()->getDeclContext() !=
13301           RHSAddrExpr->getLabel()->getDeclContext())
13302         return Error(E);
13303       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13304     }
13305     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13306     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13307 
13308     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13309     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13310 
13311     // C++11 [expr.add]p6:
13312     //   Unless both pointers point to elements of the same array object, or
13313     //   one past the last element of the array object, the behavior is
13314     //   undefined.
13315     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13316         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13317                                 RHSDesignator))
13318       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13319 
13320     QualType Type = E->getLHS()->getType();
13321     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13322 
13323     CharUnits ElementSize;
13324     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13325       return false;
13326 
13327     // As an extension, a type may have zero size (empty struct or union in
13328     // C, array of zero length). Pointer subtraction in such cases has
13329     // undefined behavior, so is not constant.
13330     if (ElementSize.isZero()) {
13331       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13332           << ElementType;
13333       return false;
13334     }
13335 
13336     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13337     // and produce incorrect results when it overflows. Such behavior
13338     // appears to be non-conforming, but is common, so perhaps we should
13339     // assume the standard intended for such cases to be undefined behavior
13340     // and check for them.
13341 
13342     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13343     // overflow in the final conversion to ptrdiff_t.
13344     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13345     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13346     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13347                     false);
13348     APSInt TrueResult = (LHS - RHS) / ElemSize;
13349     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13350 
13351     if (Result.extend(65) != TrueResult &&
13352         !HandleOverflow(Info, E, TrueResult, E->getType()))
13353       return false;
13354     return Success(Result, E);
13355   }
13356 
13357   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13358 }
13359 
13360 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13361 /// a result as the expression's type.
VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr * E)13362 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13363                                     const UnaryExprOrTypeTraitExpr *E) {
13364   switch(E->getKind()) {
13365   case UETT_PreferredAlignOf:
13366   case UETT_AlignOf: {
13367     if (E->isArgumentType())
13368       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13369                      E);
13370     else
13371       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13372                      E);
13373   }
13374 
13375   case UETT_VecStep: {
13376     QualType Ty = E->getTypeOfArgument();
13377 
13378     if (Ty->isVectorType()) {
13379       unsigned n = Ty->castAs<VectorType>()->getNumElements();
13380 
13381       // The vec_step built-in functions that take a 3-component
13382       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13383       if (n == 3)
13384         n = 4;
13385 
13386       return Success(n, E);
13387     } else
13388       return Success(1, E);
13389   }
13390 
13391   case UETT_SizeOf: {
13392     QualType SrcTy = E->getTypeOfArgument();
13393     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13394     //   the result is the size of the referenced type."
13395     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13396       SrcTy = Ref->getPointeeType();
13397 
13398     CharUnits Sizeof;
13399     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13400       return false;
13401     return Success(Sizeof, E);
13402   }
13403   case UETT_OpenMPRequiredSimdAlign:
13404     assert(E->isArgumentType());
13405     return Success(
13406         Info.Ctx.toCharUnitsFromBits(
13407                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13408             .getQuantity(),
13409         E);
13410   }
13411 
13412   llvm_unreachable("unknown expr/type trait");
13413 }
13414 
VisitOffsetOfExpr(const OffsetOfExpr * OOE)13415 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13416   CharUnits Result;
13417   unsigned n = OOE->getNumComponents();
13418   if (n == 0)
13419     return Error(OOE);
13420   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13421   for (unsigned i = 0; i != n; ++i) {
13422     OffsetOfNode ON = OOE->getComponent(i);
13423     switch (ON.getKind()) {
13424     case OffsetOfNode::Array: {
13425       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13426       APSInt IdxResult;
13427       if (!EvaluateInteger(Idx, IdxResult, Info))
13428         return false;
13429       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13430       if (!AT)
13431         return Error(OOE);
13432       CurrentType = AT->getElementType();
13433       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13434       Result += IdxResult.getSExtValue() * ElementSize;
13435       break;
13436     }
13437 
13438     case OffsetOfNode::Field: {
13439       FieldDecl *MemberDecl = ON.getField();
13440       const RecordType *RT = CurrentType->getAs<RecordType>();
13441       if (!RT)
13442         return Error(OOE);
13443       RecordDecl *RD = RT->getDecl();
13444       if (RD->isInvalidDecl()) return false;
13445       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13446       unsigned i = MemberDecl->getFieldIndex();
13447       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13448       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13449       CurrentType = MemberDecl->getType().getNonReferenceType();
13450       break;
13451     }
13452 
13453     case OffsetOfNode::Identifier:
13454       llvm_unreachable("dependent __builtin_offsetof");
13455 
13456     case OffsetOfNode::Base: {
13457       CXXBaseSpecifier *BaseSpec = ON.getBase();
13458       if (BaseSpec->isVirtual())
13459         return Error(OOE);
13460 
13461       // Find the layout of the class whose base we are looking into.
13462       const RecordType *RT = CurrentType->getAs<RecordType>();
13463       if (!RT)
13464         return Error(OOE);
13465       RecordDecl *RD = RT->getDecl();
13466       if (RD->isInvalidDecl()) return false;
13467       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13468 
13469       // Find the base class itself.
13470       CurrentType = BaseSpec->getType();
13471       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13472       if (!BaseRT)
13473         return Error(OOE);
13474 
13475       // Add the offset to the base.
13476       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13477       break;
13478     }
13479     }
13480   }
13481   return Success(Result, OOE);
13482 }
13483 
VisitUnaryOperator(const UnaryOperator * E)13484 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13485   switch (E->getOpcode()) {
13486   default:
13487     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13488     // See C99 6.6p3.
13489     return Error(E);
13490   case UO_Extension:
13491     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13492     // If so, we could clear the diagnostic ID.
13493     return Visit(E->getSubExpr());
13494   case UO_Plus:
13495     // The result is just the value.
13496     return Visit(E->getSubExpr());
13497   case UO_Minus: {
13498     if (!Visit(E->getSubExpr()))
13499       return false;
13500     if (!Result.isInt()) return Error(E);
13501     const APSInt &Value = Result.getInt();
13502     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13503         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13504                         E->getType()))
13505       return false;
13506     return Success(-Value, E);
13507   }
13508   case UO_Not: {
13509     if (!Visit(E->getSubExpr()))
13510       return false;
13511     if (!Result.isInt()) return Error(E);
13512     return Success(~Result.getInt(), E);
13513   }
13514   case UO_LNot: {
13515     bool bres;
13516     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13517       return false;
13518     return Success(!bres, E);
13519   }
13520   }
13521 }
13522 
13523 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13524 /// result type is integer.
VisitCastExpr(const CastExpr * E)13525 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13526   const Expr *SubExpr = E->getSubExpr();
13527   QualType DestType = E->getType();
13528   QualType SrcType = SubExpr->getType();
13529 
13530   switch (E->getCastKind()) {
13531   case CK_BaseToDerived:
13532   case CK_DerivedToBase:
13533   case CK_UncheckedDerivedToBase:
13534   case CK_Dynamic:
13535   case CK_ToUnion:
13536   case CK_ArrayToPointerDecay:
13537   case CK_FunctionToPointerDecay:
13538   case CK_NullToPointer:
13539   case CK_NullToMemberPointer:
13540   case CK_BaseToDerivedMemberPointer:
13541   case CK_DerivedToBaseMemberPointer:
13542   case CK_ReinterpretMemberPointer:
13543   case CK_ConstructorConversion:
13544   case CK_IntegralToPointer:
13545   case CK_ToVoid:
13546   case CK_VectorSplat:
13547   case CK_IntegralToFloating:
13548   case CK_FloatingCast:
13549   case CK_CPointerToObjCPointerCast:
13550   case CK_BlockPointerToObjCPointerCast:
13551   case CK_AnyPointerToBlockPointerCast:
13552   case CK_ObjCObjectLValueCast:
13553   case CK_FloatingRealToComplex:
13554   case CK_FloatingComplexToReal:
13555   case CK_FloatingComplexCast:
13556   case CK_FloatingComplexToIntegralComplex:
13557   case CK_IntegralRealToComplex:
13558   case CK_IntegralComplexCast:
13559   case CK_IntegralComplexToFloatingComplex:
13560   case CK_BuiltinFnToFnPtr:
13561   case CK_ZeroToOCLOpaqueType:
13562   case CK_NonAtomicToAtomic:
13563   case CK_AddressSpaceConversion:
13564   case CK_IntToOCLSampler:
13565   case CK_FloatingToFixedPoint:
13566   case CK_FixedPointToFloating:
13567   case CK_FixedPointCast:
13568   case CK_IntegralToFixedPoint:
13569   case CK_MatrixCast:
13570     llvm_unreachable("invalid cast kind for integral value");
13571 
13572   case CK_BitCast:
13573   case CK_Dependent:
13574   case CK_LValueBitCast:
13575   case CK_ARCProduceObject:
13576   case CK_ARCConsumeObject:
13577   case CK_ARCReclaimReturnedObject:
13578   case CK_ARCExtendBlockObject:
13579   case CK_CopyAndAutoreleaseBlockObject:
13580     return Error(E);
13581 
13582   case CK_UserDefinedConversion:
13583   case CK_LValueToRValue:
13584   case CK_AtomicToNonAtomic:
13585   case CK_NoOp:
13586   case CK_LValueToRValueBitCast:
13587     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13588 
13589   case CK_MemberPointerToBoolean:
13590   case CK_PointerToBoolean:
13591   case CK_IntegralToBoolean:
13592   case CK_FloatingToBoolean:
13593   case CK_BooleanToSignedIntegral:
13594   case CK_FloatingComplexToBoolean:
13595   case CK_IntegralComplexToBoolean: {
13596     bool BoolResult;
13597     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13598       return false;
13599     uint64_t IntResult = BoolResult;
13600     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13601       IntResult = (uint64_t)-1;
13602     return Success(IntResult, E);
13603   }
13604 
13605   case CK_FixedPointToIntegral: {
13606     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13607     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13608       return false;
13609     bool Overflowed;
13610     llvm::APSInt Result = Src.convertToInt(
13611         Info.Ctx.getIntWidth(DestType),
13612         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13613     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13614       return false;
13615     return Success(Result, E);
13616   }
13617 
13618   case CK_FixedPointToBoolean: {
13619     // Unsigned padding does not affect this.
13620     APValue Val;
13621     if (!Evaluate(Val, Info, SubExpr))
13622       return false;
13623     return Success(Val.getFixedPoint().getBoolValue(), E);
13624   }
13625 
13626   case CK_IntegralCast: {
13627     if (!Visit(SubExpr))
13628       return false;
13629 
13630     if (!Result.isInt()) {
13631       // Allow casts of address-of-label differences if they are no-ops
13632       // or narrowing.  (The narrowing case isn't actually guaranteed to
13633       // be constant-evaluatable except in some narrow cases which are hard
13634       // to detect here.  We let it through on the assumption the user knows
13635       // what they are doing.)
13636       if (Result.isAddrLabelDiff())
13637         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13638       // Only allow casts of lvalues if they are lossless.
13639       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13640     }
13641 
13642     if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
13643         Info.EvalMode == EvalInfo::EM_ConstantExpression &&
13644         DestType->isEnumeralType()) {
13645 
13646       bool ConstexprVar = true;
13647 
13648       // We know if we are here that we are in a context that we might require
13649       // a constant expression or a context that requires a constant
13650       // value. But if we are initializing a value we don't know if it is a
13651       // constexpr variable or not. We can check the EvaluatingDecl to determine
13652       // if it constexpr or not. If not then we don't want to emit a diagnostic.
13653       if (const auto *VD = dyn_cast_or_null<VarDecl>(
13654               Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
13655         ConstexprVar = VD->isConstexpr();
13656 
13657       const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());
13658       const EnumDecl *ED = ET->getDecl();
13659       // Check that the value is within the range of the enumeration values.
13660       //
13661       // This corressponds to [expr.static.cast]p10 which says:
13662       // A value of integral or enumeration type can be explicitly converted
13663       // to a complete enumeration type ... If the enumeration type does not
13664       // have a fixed underlying type, the value is unchanged if the original
13665       // value is within the range of the enumeration values ([dcl.enum]), and
13666       // otherwise, the behavior is undefined.
13667       //
13668       // This was resolved as part of DR2338 which has CD5 status.
13669       if (!ED->isFixed()) {
13670         llvm::APInt Min;
13671         llvm::APInt Max;
13672 
13673         ED->getValueRange(Max, Min);
13674         --Max;
13675 
13676         if (ED->getNumNegativeBits() && ConstexprVar &&
13677             (Max.slt(Result.getInt().getSExtValue()) ||
13678              Min.sgt(Result.getInt().getSExtValue())))
13679           Info.Ctx.getDiagnostics().Report(
13680               E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
13681               << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
13682               << Max.getSExtValue();
13683         else if (!ED->getNumNegativeBits() && ConstexprVar &&
13684                  Max.ult(Result.getInt().getZExtValue()))
13685           Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13686                                        diag::warn_constexpr_unscoped_enum_out_of_range)
13687 	    << llvm::toString(Result.getInt(),10) << Min.getZExtValue() << Max.getZExtValue();
13688       }
13689     }
13690 
13691     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13692                                       Result.getInt()), E);
13693   }
13694 
13695   case CK_PointerToIntegral: {
13696     CCEDiag(E, diag::note_constexpr_invalid_cast)
13697         << 2 << Info.Ctx.getLangOpts().CPlusPlus;
13698 
13699     LValue LV;
13700     if (!EvaluatePointer(SubExpr, LV, Info))
13701       return false;
13702 
13703     if (LV.getLValueBase()) {
13704       // Only allow based lvalue casts if they are lossless.
13705       // FIXME: Allow a larger integer size than the pointer size, and allow
13706       // narrowing back down to pointer width in subsequent integral casts.
13707       // FIXME: Check integer type's active bits, not its type size.
13708       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13709         return Error(E);
13710 
13711       LV.Designator.setInvalid();
13712       LV.moveInto(Result);
13713       return true;
13714     }
13715 
13716     APSInt AsInt;
13717     APValue V;
13718     LV.moveInto(V);
13719     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13720       llvm_unreachable("Can't cast this!");
13721 
13722     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13723   }
13724 
13725   case CK_IntegralComplexToReal: {
13726     ComplexValue C;
13727     if (!EvaluateComplex(SubExpr, C, Info))
13728       return false;
13729     return Success(C.getComplexIntReal(), E);
13730   }
13731 
13732   case CK_FloatingToIntegral: {
13733     APFloat F(0.0);
13734     if (!EvaluateFloat(SubExpr, F, Info))
13735       return false;
13736 
13737     APSInt Value;
13738     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13739       return false;
13740     return Success(Value, E);
13741   }
13742   }
13743 
13744   llvm_unreachable("unknown cast resulting in integral value");
13745 }
13746 
VisitUnaryReal(const UnaryOperator * E)13747 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13748   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13749     ComplexValue LV;
13750     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13751       return false;
13752     if (!LV.isComplexInt())
13753       return Error(E);
13754     return Success(LV.getComplexIntReal(), E);
13755   }
13756 
13757   return Visit(E->getSubExpr());
13758 }
13759 
VisitUnaryImag(const UnaryOperator * E)13760 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13761   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13762     ComplexValue LV;
13763     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13764       return false;
13765     if (!LV.isComplexInt())
13766       return Error(E);
13767     return Success(LV.getComplexIntImag(), E);
13768   }
13769 
13770   VisitIgnoredValue(E->getSubExpr());
13771   return Success(0, E);
13772 }
13773 
VisitSizeOfPackExpr(const SizeOfPackExpr * E)13774 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13775   return Success(E->getPackLength(), E);
13776 }
13777 
VisitCXXNoexceptExpr(const CXXNoexceptExpr * E)13778 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13779   return Success(E->getValue(), E);
13780 }
13781 
VisitConceptSpecializationExpr(const ConceptSpecializationExpr * E)13782 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13783        const ConceptSpecializationExpr *E) {
13784   return Success(E->isSatisfied(), E);
13785 }
13786 
VisitRequiresExpr(const RequiresExpr * E)13787 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13788   return Success(E->isSatisfied(), E);
13789 }
13790 
VisitUnaryOperator(const UnaryOperator * E)13791 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13792   switch (E->getOpcode()) {
13793     default:
13794       // Invalid unary operators
13795       return Error(E);
13796     case UO_Plus:
13797       // The result is just the value.
13798       return Visit(E->getSubExpr());
13799     case UO_Minus: {
13800       if (!Visit(E->getSubExpr())) return false;
13801       if (!Result.isFixedPoint())
13802         return Error(E);
13803       bool Overflowed;
13804       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13805       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13806         return false;
13807       return Success(Negated, E);
13808     }
13809     case UO_LNot: {
13810       bool bres;
13811       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13812         return false;
13813       return Success(!bres, E);
13814     }
13815   }
13816 }
13817 
VisitCastExpr(const CastExpr * E)13818 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13819   const Expr *SubExpr = E->getSubExpr();
13820   QualType DestType = E->getType();
13821   assert(DestType->isFixedPointType() &&
13822          "Expected destination type to be a fixed point type");
13823   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13824 
13825   switch (E->getCastKind()) {
13826   case CK_FixedPointCast: {
13827     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13828     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13829       return false;
13830     bool Overflowed;
13831     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13832     if (Overflowed) {
13833       if (Info.checkingForUndefinedBehavior())
13834         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13835                                          diag::warn_fixedpoint_constant_overflow)
13836           << Result.toString() << E->getType();
13837       if (!HandleOverflow(Info, E, Result, E->getType()))
13838         return false;
13839     }
13840     return Success(Result, E);
13841   }
13842   case CK_IntegralToFixedPoint: {
13843     APSInt Src;
13844     if (!EvaluateInteger(SubExpr, Src, Info))
13845       return false;
13846 
13847     bool Overflowed;
13848     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13849         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13850 
13851     if (Overflowed) {
13852       if (Info.checkingForUndefinedBehavior())
13853         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13854                                          diag::warn_fixedpoint_constant_overflow)
13855           << IntResult.toString() << E->getType();
13856       if (!HandleOverflow(Info, E, IntResult, E->getType()))
13857         return false;
13858     }
13859 
13860     return Success(IntResult, E);
13861   }
13862   case CK_FloatingToFixedPoint: {
13863     APFloat Src(0.0);
13864     if (!EvaluateFloat(SubExpr, Src, Info))
13865       return false;
13866 
13867     bool Overflowed;
13868     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13869         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13870 
13871     if (Overflowed) {
13872       if (Info.checkingForUndefinedBehavior())
13873         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13874                                          diag::warn_fixedpoint_constant_overflow)
13875           << Result.toString() << E->getType();
13876       if (!HandleOverflow(Info, E, Result, E->getType()))
13877         return false;
13878     }
13879 
13880     return Success(Result, E);
13881   }
13882   case CK_NoOp:
13883   case CK_LValueToRValue:
13884     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13885   default:
13886     return Error(E);
13887   }
13888 }
13889 
VisitBinaryOperator(const BinaryOperator * E)13890 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13891   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13892     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13893 
13894   const Expr *LHS = E->getLHS();
13895   const Expr *RHS = E->getRHS();
13896   FixedPointSemantics ResultFXSema =
13897       Info.Ctx.getFixedPointSemantics(E->getType());
13898 
13899   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13900   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13901     return false;
13902   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13903   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13904     return false;
13905 
13906   bool OpOverflow = false, ConversionOverflow = false;
13907   APFixedPoint Result(LHSFX.getSemantics());
13908   switch (E->getOpcode()) {
13909   case BO_Add: {
13910     Result = LHSFX.add(RHSFX, &OpOverflow)
13911                   .convert(ResultFXSema, &ConversionOverflow);
13912     break;
13913   }
13914   case BO_Sub: {
13915     Result = LHSFX.sub(RHSFX, &OpOverflow)
13916                   .convert(ResultFXSema, &ConversionOverflow);
13917     break;
13918   }
13919   case BO_Mul: {
13920     Result = LHSFX.mul(RHSFX, &OpOverflow)
13921                   .convert(ResultFXSema, &ConversionOverflow);
13922     break;
13923   }
13924   case BO_Div: {
13925     if (RHSFX.getValue() == 0) {
13926       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13927       return false;
13928     }
13929     Result = LHSFX.div(RHSFX, &OpOverflow)
13930                   .convert(ResultFXSema, &ConversionOverflow);
13931     break;
13932   }
13933   case BO_Shl:
13934   case BO_Shr: {
13935     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13936     llvm::APSInt RHSVal = RHSFX.getValue();
13937 
13938     unsigned ShiftBW =
13939         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13940     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13941     // Embedded-C 4.1.6.2.2:
13942     //   The right operand must be nonnegative and less than the total number
13943     //   of (nonpadding) bits of the fixed-point operand ...
13944     if (RHSVal.isNegative())
13945       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13946     else if (Amt != RHSVal)
13947       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13948           << RHSVal << E->getType() << ShiftBW;
13949 
13950     if (E->getOpcode() == BO_Shl)
13951       Result = LHSFX.shl(Amt, &OpOverflow);
13952     else
13953       Result = LHSFX.shr(Amt, &OpOverflow);
13954     break;
13955   }
13956   default:
13957     return false;
13958   }
13959   if (OpOverflow || ConversionOverflow) {
13960     if (Info.checkingForUndefinedBehavior())
13961       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13962                                        diag::warn_fixedpoint_constant_overflow)
13963         << Result.toString() << E->getType();
13964     if (!HandleOverflow(Info, E, Result, E->getType()))
13965       return false;
13966   }
13967   return Success(Result, E);
13968 }
13969 
13970 //===----------------------------------------------------------------------===//
13971 // Float Evaluation
13972 //===----------------------------------------------------------------------===//
13973 
13974 namespace {
13975 class FloatExprEvaluator
13976   : public ExprEvaluatorBase<FloatExprEvaluator> {
13977   APFloat &Result;
13978 public:
FloatExprEvaluator(EvalInfo & info,APFloat & result)13979   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13980     : ExprEvaluatorBaseTy(info), Result(result) {}
13981 
Success(const APValue & V,const Expr * e)13982   bool Success(const APValue &V, const Expr *e) {
13983     Result = V.getFloat();
13984     return true;
13985   }
13986 
ZeroInitialization(const Expr * E)13987   bool ZeroInitialization(const Expr *E) {
13988     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13989     return true;
13990   }
13991 
13992   bool VisitCallExpr(const CallExpr *E);
13993 
13994   bool VisitUnaryOperator(const UnaryOperator *E);
13995   bool VisitBinaryOperator(const BinaryOperator *E);
13996   bool VisitFloatingLiteral(const FloatingLiteral *E);
13997   bool VisitCastExpr(const CastExpr *E);
13998 
13999   bool VisitUnaryReal(const UnaryOperator *E);
14000   bool VisitUnaryImag(const UnaryOperator *E);
14001 
14002   // FIXME: Missing: array subscript of vector, member of vector
14003 };
14004 } // end anonymous namespace
14005 
EvaluateFloat(const Expr * E,APFloat & Result,EvalInfo & Info)14006 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
14007   assert(!E->isValueDependent());
14008   assert(E->isPRValue() && E->getType()->isRealFloatingType());
14009   return FloatExprEvaluator(Info, Result).Visit(E);
14010 }
14011 
TryEvaluateBuiltinNaN(const ASTContext & Context,QualType ResultTy,const Expr * Arg,bool SNaN,llvm::APFloat & Result)14012 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
14013                                   QualType ResultTy,
14014                                   const Expr *Arg,
14015                                   bool SNaN,
14016                                   llvm::APFloat &Result) {
14017   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
14018   if (!S) return false;
14019 
14020   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
14021 
14022   llvm::APInt fill;
14023 
14024   // Treat empty strings as if they were zero.
14025   if (S->getString().empty())
14026     fill = llvm::APInt(32, 0);
14027   else if (S->getString().getAsInteger(0, fill))
14028     return false;
14029 
14030   if (Context.getTargetInfo().isNan2008()) {
14031     if (SNaN)
14032       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14033     else
14034       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14035   } else {
14036     // Prior to IEEE 754-2008, architectures were allowed to choose whether
14037     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
14038     // a different encoding to what became a standard in 2008, and for pre-
14039     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
14040     // sNaN. This is now known as "legacy NaN" encoding.
14041     if (SNaN)
14042       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14043     else
14044       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14045   }
14046 
14047   return true;
14048 }
14049 
VisitCallExpr(const CallExpr * E)14050 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
14051   if (!IsConstantEvaluatedBuiltinCall(E))
14052     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14053 
14054   switch (E->getBuiltinCallee()) {
14055   default:
14056     return false;
14057 
14058   case Builtin::BI__builtin_huge_val:
14059   case Builtin::BI__builtin_huge_valf:
14060   case Builtin::BI__builtin_huge_vall:
14061   case Builtin::BI__builtin_huge_valf16:
14062   case Builtin::BI__builtin_huge_valf128:
14063   case Builtin::BI__builtin_inf:
14064   case Builtin::BI__builtin_inff:
14065   case Builtin::BI__builtin_infl:
14066   case Builtin::BI__builtin_inff16:
14067   case Builtin::BI__builtin_inff128: {
14068     const llvm::fltSemantics &Sem =
14069       Info.Ctx.getFloatTypeSemantics(E->getType());
14070     Result = llvm::APFloat::getInf(Sem);
14071     return true;
14072   }
14073 
14074   case Builtin::BI__builtin_nans:
14075   case Builtin::BI__builtin_nansf:
14076   case Builtin::BI__builtin_nansl:
14077   case Builtin::BI__builtin_nansf16:
14078   case Builtin::BI__builtin_nansf128:
14079     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14080                                true, Result))
14081       return Error(E);
14082     return true;
14083 
14084   case Builtin::BI__builtin_nan:
14085   case Builtin::BI__builtin_nanf:
14086   case Builtin::BI__builtin_nanl:
14087   case Builtin::BI__builtin_nanf16:
14088   case Builtin::BI__builtin_nanf128:
14089     // If this is __builtin_nan() turn this into a nan, otherwise we
14090     // can't constant fold it.
14091     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14092                                false, Result))
14093       return Error(E);
14094     return true;
14095 
14096   case Builtin::BI__builtin_fabs:
14097   case Builtin::BI__builtin_fabsf:
14098   case Builtin::BI__builtin_fabsl:
14099   case Builtin::BI__builtin_fabsf128:
14100     // The C standard says "fabs raises no floating-point exceptions,
14101     // even if x is a signaling NaN. The returned value is independent of
14102     // the current rounding direction mode."  Therefore constant folding can
14103     // proceed without regard to the floating point settings.
14104     // Reference, WG14 N2478 F.10.4.3
14105     if (!EvaluateFloat(E->getArg(0), Result, Info))
14106       return false;
14107 
14108     if (Result.isNegative())
14109       Result.changeSign();
14110     return true;
14111 
14112   case Builtin::BI__arithmetic_fence:
14113     return EvaluateFloat(E->getArg(0), Result, Info);
14114 
14115   // FIXME: Builtin::BI__builtin_powi
14116   // FIXME: Builtin::BI__builtin_powif
14117   // FIXME: Builtin::BI__builtin_powil
14118 
14119   case Builtin::BI__builtin_copysign:
14120   case Builtin::BI__builtin_copysignf:
14121   case Builtin::BI__builtin_copysignl:
14122   case Builtin::BI__builtin_copysignf128: {
14123     APFloat RHS(0.);
14124     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14125         !EvaluateFloat(E->getArg(1), RHS, Info))
14126       return false;
14127     Result.copySign(RHS);
14128     return true;
14129   }
14130 
14131   case Builtin::BI__builtin_fmax:
14132   case Builtin::BI__builtin_fmaxf:
14133   case Builtin::BI__builtin_fmaxl:
14134   case Builtin::BI__builtin_fmaxf16:
14135   case Builtin::BI__builtin_fmaxf128: {
14136     // TODO: Handle sNaN.
14137     APFloat RHS(0.);
14138     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14139         !EvaluateFloat(E->getArg(1), RHS, Info))
14140       return false;
14141     // When comparing zeroes, return +0.0 if one of the zeroes is positive.
14142     if (Result.isZero() && RHS.isZero() && Result.isNegative())
14143       Result = RHS;
14144     else if (Result.isNaN() || RHS > Result)
14145       Result = RHS;
14146     return true;
14147   }
14148 
14149   case Builtin::BI__builtin_fmin:
14150   case Builtin::BI__builtin_fminf:
14151   case Builtin::BI__builtin_fminl:
14152   case Builtin::BI__builtin_fminf16:
14153   case Builtin::BI__builtin_fminf128: {
14154     // TODO: Handle sNaN.
14155     APFloat RHS(0.);
14156     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14157         !EvaluateFloat(E->getArg(1), RHS, Info))
14158       return false;
14159     // When comparing zeroes, return -0.0 if one of the zeroes is negative.
14160     if (Result.isZero() && RHS.isZero() && RHS.isNegative())
14161       Result = RHS;
14162     else if (Result.isNaN() || RHS < Result)
14163       Result = RHS;
14164     return true;
14165   }
14166   }
14167 }
14168 
VisitUnaryReal(const UnaryOperator * E)14169 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
14170   if (E->getSubExpr()->getType()->isAnyComplexType()) {
14171     ComplexValue CV;
14172     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14173       return false;
14174     Result = CV.FloatReal;
14175     return true;
14176   }
14177 
14178   return Visit(E->getSubExpr());
14179 }
14180 
VisitUnaryImag(const UnaryOperator * E)14181 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
14182   if (E->getSubExpr()->getType()->isAnyComplexType()) {
14183     ComplexValue CV;
14184     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14185       return false;
14186     Result = CV.FloatImag;
14187     return true;
14188   }
14189 
14190   VisitIgnoredValue(E->getSubExpr());
14191   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
14192   Result = llvm::APFloat::getZero(Sem);
14193   return true;
14194 }
14195 
VisitUnaryOperator(const UnaryOperator * E)14196 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14197   switch (E->getOpcode()) {
14198   default: return Error(E);
14199   case UO_Plus:
14200     return EvaluateFloat(E->getSubExpr(), Result, Info);
14201   case UO_Minus:
14202     // In C standard, WG14 N2478 F.3 p4
14203     // "the unary - raises no floating point exceptions,
14204     // even if the operand is signalling."
14205     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
14206       return false;
14207     Result.changeSign();
14208     return true;
14209   }
14210 }
14211 
VisitBinaryOperator(const BinaryOperator * E)14212 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14213   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14214     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14215 
14216   APFloat RHS(0.0);
14217   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
14218   if (!LHSOK && !Info.noteFailure())
14219     return false;
14220   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
14221          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
14222 }
14223 
VisitFloatingLiteral(const FloatingLiteral * E)14224 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
14225   Result = E->getValue();
14226   return true;
14227 }
14228 
VisitCastExpr(const CastExpr * E)14229 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
14230   const Expr* SubExpr = E->getSubExpr();
14231 
14232   switch (E->getCastKind()) {
14233   default:
14234     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14235 
14236   case CK_IntegralToFloating: {
14237     APSInt IntResult;
14238     const FPOptions FPO = E->getFPFeaturesInEffect(
14239                                   Info.Ctx.getLangOpts());
14240     return EvaluateInteger(SubExpr, IntResult, Info) &&
14241            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
14242                                 IntResult, E->getType(), Result);
14243   }
14244 
14245   case CK_FixedPointToFloating: {
14246     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14247     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
14248       return false;
14249     Result =
14250         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
14251     return true;
14252   }
14253 
14254   case CK_FloatingCast: {
14255     if (!Visit(SubExpr))
14256       return false;
14257     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
14258                                   Result);
14259   }
14260 
14261   case CK_FloatingComplexToReal: {
14262     ComplexValue V;
14263     if (!EvaluateComplex(SubExpr, V, Info))
14264       return false;
14265     Result = V.getComplexFloatReal();
14266     return true;
14267   }
14268   }
14269 }
14270 
14271 //===----------------------------------------------------------------------===//
14272 // Complex Evaluation (for float and integer)
14273 //===----------------------------------------------------------------------===//
14274 
14275 namespace {
14276 class ComplexExprEvaluator
14277   : public ExprEvaluatorBase<ComplexExprEvaluator> {
14278   ComplexValue &Result;
14279 
14280 public:
ComplexExprEvaluator(EvalInfo & info,ComplexValue & Result)14281   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
14282     : ExprEvaluatorBaseTy(info), Result(Result) {}
14283 
Success(const APValue & V,const Expr * e)14284   bool Success(const APValue &V, const Expr *e) {
14285     Result.setFrom(V);
14286     return true;
14287   }
14288 
14289   bool ZeroInitialization(const Expr *E);
14290 
14291   //===--------------------------------------------------------------------===//
14292   //                            Visitor Methods
14293   //===--------------------------------------------------------------------===//
14294 
14295   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
14296   bool VisitCastExpr(const CastExpr *E);
14297   bool VisitBinaryOperator(const BinaryOperator *E);
14298   bool VisitUnaryOperator(const UnaryOperator *E);
14299   bool VisitInitListExpr(const InitListExpr *E);
14300   bool VisitCallExpr(const CallExpr *E);
14301 };
14302 } // end anonymous namespace
14303 
EvaluateComplex(const Expr * E,ComplexValue & Result,EvalInfo & Info)14304 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
14305                             EvalInfo &Info) {
14306   assert(!E->isValueDependent());
14307   assert(E->isPRValue() && E->getType()->isAnyComplexType());
14308   return ComplexExprEvaluator(Info, Result).Visit(E);
14309 }
14310 
ZeroInitialization(const Expr * E)14311 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
14312   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
14313   if (ElemTy->isRealFloatingType()) {
14314     Result.makeComplexFloat();
14315     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
14316     Result.FloatReal = Zero;
14317     Result.FloatImag = Zero;
14318   } else {
14319     Result.makeComplexInt();
14320     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
14321     Result.IntReal = Zero;
14322     Result.IntImag = Zero;
14323   }
14324   return true;
14325 }
14326 
VisitImaginaryLiteral(const ImaginaryLiteral * E)14327 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
14328   const Expr* SubExpr = E->getSubExpr();
14329 
14330   if (SubExpr->getType()->isRealFloatingType()) {
14331     Result.makeComplexFloat();
14332     APFloat &Imag = Result.FloatImag;
14333     if (!EvaluateFloat(SubExpr, Imag, Info))
14334       return false;
14335 
14336     Result.FloatReal = APFloat(Imag.getSemantics());
14337     return true;
14338   } else {
14339     assert(SubExpr->getType()->isIntegerType() &&
14340            "Unexpected imaginary literal.");
14341 
14342     Result.makeComplexInt();
14343     APSInt &Imag = Result.IntImag;
14344     if (!EvaluateInteger(SubExpr, Imag, Info))
14345       return false;
14346 
14347     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
14348     return true;
14349   }
14350 }
14351 
VisitCastExpr(const CastExpr * E)14352 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14353 
14354   switch (E->getCastKind()) {
14355   case CK_BitCast:
14356   case CK_BaseToDerived:
14357   case CK_DerivedToBase:
14358   case CK_UncheckedDerivedToBase:
14359   case CK_Dynamic:
14360   case CK_ToUnion:
14361   case CK_ArrayToPointerDecay:
14362   case CK_FunctionToPointerDecay:
14363   case CK_NullToPointer:
14364   case CK_NullToMemberPointer:
14365   case CK_BaseToDerivedMemberPointer:
14366   case CK_DerivedToBaseMemberPointer:
14367   case CK_MemberPointerToBoolean:
14368   case CK_ReinterpretMemberPointer:
14369   case CK_ConstructorConversion:
14370   case CK_IntegralToPointer:
14371   case CK_PointerToIntegral:
14372   case CK_PointerToBoolean:
14373   case CK_ToVoid:
14374   case CK_VectorSplat:
14375   case CK_IntegralCast:
14376   case CK_BooleanToSignedIntegral:
14377   case CK_IntegralToBoolean:
14378   case CK_IntegralToFloating:
14379   case CK_FloatingToIntegral:
14380   case CK_FloatingToBoolean:
14381   case CK_FloatingCast:
14382   case CK_CPointerToObjCPointerCast:
14383   case CK_BlockPointerToObjCPointerCast:
14384   case CK_AnyPointerToBlockPointerCast:
14385   case CK_ObjCObjectLValueCast:
14386   case CK_FloatingComplexToReal:
14387   case CK_FloatingComplexToBoolean:
14388   case CK_IntegralComplexToReal:
14389   case CK_IntegralComplexToBoolean:
14390   case CK_ARCProduceObject:
14391   case CK_ARCConsumeObject:
14392   case CK_ARCReclaimReturnedObject:
14393   case CK_ARCExtendBlockObject:
14394   case CK_CopyAndAutoreleaseBlockObject:
14395   case CK_BuiltinFnToFnPtr:
14396   case CK_ZeroToOCLOpaqueType:
14397   case CK_NonAtomicToAtomic:
14398   case CK_AddressSpaceConversion:
14399   case CK_IntToOCLSampler:
14400   case CK_FloatingToFixedPoint:
14401   case CK_FixedPointToFloating:
14402   case CK_FixedPointCast:
14403   case CK_FixedPointToBoolean:
14404   case CK_FixedPointToIntegral:
14405   case CK_IntegralToFixedPoint:
14406   case CK_MatrixCast:
14407     llvm_unreachable("invalid cast kind for complex value");
14408 
14409   case CK_LValueToRValue:
14410   case CK_AtomicToNonAtomic:
14411   case CK_NoOp:
14412   case CK_LValueToRValueBitCast:
14413     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14414 
14415   case CK_Dependent:
14416   case CK_LValueBitCast:
14417   case CK_UserDefinedConversion:
14418     return Error(E);
14419 
14420   case CK_FloatingRealToComplex: {
14421     APFloat &Real = Result.FloatReal;
14422     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14423       return false;
14424 
14425     Result.makeComplexFloat();
14426     Result.FloatImag = APFloat(Real.getSemantics());
14427     return true;
14428   }
14429 
14430   case CK_FloatingComplexCast: {
14431     if (!Visit(E->getSubExpr()))
14432       return false;
14433 
14434     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14435     QualType From
14436       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14437 
14438     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14439            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14440   }
14441 
14442   case CK_FloatingComplexToIntegralComplex: {
14443     if (!Visit(E->getSubExpr()))
14444       return false;
14445 
14446     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14447     QualType From
14448       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14449     Result.makeComplexInt();
14450     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14451                                 To, Result.IntReal) &&
14452            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14453                                 To, Result.IntImag);
14454   }
14455 
14456   case CK_IntegralRealToComplex: {
14457     APSInt &Real = Result.IntReal;
14458     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14459       return false;
14460 
14461     Result.makeComplexInt();
14462     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14463     return true;
14464   }
14465 
14466   case CK_IntegralComplexCast: {
14467     if (!Visit(E->getSubExpr()))
14468       return false;
14469 
14470     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14471     QualType From
14472       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14473 
14474     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14475     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14476     return true;
14477   }
14478 
14479   case CK_IntegralComplexToFloatingComplex: {
14480     if (!Visit(E->getSubExpr()))
14481       return false;
14482 
14483     const FPOptions FPO = E->getFPFeaturesInEffect(
14484                                   Info.Ctx.getLangOpts());
14485     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14486     QualType From
14487       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14488     Result.makeComplexFloat();
14489     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14490                                 To, Result.FloatReal) &&
14491            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14492                                 To, Result.FloatImag);
14493   }
14494   }
14495 
14496   llvm_unreachable("unknown cast resulting in complex value");
14497 }
14498 
VisitBinaryOperator(const BinaryOperator * E)14499 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14500   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14501     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14502 
14503   // Track whether the LHS or RHS is real at the type system level. When this is
14504   // the case we can simplify our evaluation strategy.
14505   bool LHSReal = false, RHSReal = false;
14506 
14507   bool LHSOK;
14508   if (E->getLHS()->getType()->isRealFloatingType()) {
14509     LHSReal = true;
14510     APFloat &Real = Result.FloatReal;
14511     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14512     if (LHSOK) {
14513       Result.makeComplexFloat();
14514       Result.FloatImag = APFloat(Real.getSemantics());
14515     }
14516   } else {
14517     LHSOK = Visit(E->getLHS());
14518   }
14519   if (!LHSOK && !Info.noteFailure())
14520     return false;
14521 
14522   ComplexValue RHS;
14523   if (E->getRHS()->getType()->isRealFloatingType()) {
14524     RHSReal = true;
14525     APFloat &Real = RHS.FloatReal;
14526     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14527       return false;
14528     RHS.makeComplexFloat();
14529     RHS.FloatImag = APFloat(Real.getSemantics());
14530   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14531     return false;
14532 
14533   assert(!(LHSReal && RHSReal) &&
14534          "Cannot have both operands of a complex operation be real.");
14535   switch (E->getOpcode()) {
14536   default: return Error(E);
14537   case BO_Add:
14538     if (Result.isComplexFloat()) {
14539       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14540                                        APFloat::rmNearestTiesToEven);
14541       if (LHSReal)
14542         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14543       else if (!RHSReal)
14544         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14545                                          APFloat::rmNearestTiesToEven);
14546     } else {
14547       Result.getComplexIntReal() += RHS.getComplexIntReal();
14548       Result.getComplexIntImag() += RHS.getComplexIntImag();
14549     }
14550     break;
14551   case BO_Sub:
14552     if (Result.isComplexFloat()) {
14553       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14554                                             APFloat::rmNearestTiesToEven);
14555       if (LHSReal) {
14556         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14557         Result.getComplexFloatImag().changeSign();
14558       } else if (!RHSReal) {
14559         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14560                                               APFloat::rmNearestTiesToEven);
14561       }
14562     } else {
14563       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14564       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14565     }
14566     break;
14567   case BO_Mul:
14568     if (Result.isComplexFloat()) {
14569       // This is an implementation of complex multiplication according to the
14570       // constraints laid out in C11 Annex G. The implementation uses the
14571       // following naming scheme:
14572       //   (a + ib) * (c + id)
14573       ComplexValue LHS = Result;
14574       APFloat &A = LHS.getComplexFloatReal();
14575       APFloat &B = LHS.getComplexFloatImag();
14576       APFloat &C = RHS.getComplexFloatReal();
14577       APFloat &D = RHS.getComplexFloatImag();
14578       APFloat &ResR = Result.getComplexFloatReal();
14579       APFloat &ResI = Result.getComplexFloatImag();
14580       if (LHSReal) {
14581         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14582         ResR = A * C;
14583         ResI = A * D;
14584       } else if (RHSReal) {
14585         ResR = C * A;
14586         ResI = C * B;
14587       } else {
14588         // In the fully general case, we need to handle NaNs and infinities
14589         // robustly.
14590         APFloat AC = A * C;
14591         APFloat BD = B * D;
14592         APFloat AD = A * D;
14593         APFloat BC = B * C;
14594         ResR = AC - BD;
14595         ResI = AD + BC;
14596         if (ResR.isNaN() && ResI.isNaN()) {
14597           bool Recalc = false;
14598           if (A.isInfinity() || B.isInfinity()) {
14599             A = APFloat::copySign(
14600                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14601             B = APFloat::copySign(
14602                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14603             if (C.isNaN())
14604               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14605             if (D.isNaN())
14606               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14607             Recalc = true;
14608           }
14609           if (C.isInfinity() || D.isInfinity()) {
14610             C = APFloat::copySign(
14611                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14612             D = APFloat::copySign(
14613                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14614             if (A.isNaN())
14615               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14616             if (B.isNaN())
14617               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14618             Recalc = true;
14619           }
14620           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14621                           AD.isInfinity() || BC.isInfinity())) {
14622             if (A.isNaN())
14623               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14624             if (B.isNaN())
14625               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14626             if (C.isNaN())
14627               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14628             if (D.isNaN())
14629               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14630             Recalc = true;
14631           }
14632           if (Recalc) {
14633             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14634             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14635           }
14636         }
14637       }
14638     } else {
14639       ComplexValue LHS = Result;
14640       Result.getComplexIntReal() =
14641         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14642          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14643       Result.getComplexIntImag() =
14644         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14645          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14646     }
14647     break;
14648   case BO_Div:
14649     if (Result.isComplexFloat()) {
14650       // This is an implementation of complex division according to the
14651       // constraints laid out in C11 Annex G. The implementation uses the
14652       // following naming scheme:
14653       //   (a + ib) / (c + id)
14654       ComplexValue LHS = Result;
14655       APFloat &A = LHS.getComplexFloatReal();
14656       APFloat &B = LHS.getComplexFloatImag();
14657       APFloat &C = RHS.getComplexFloatReal();
14658       APFloat &D = RHS.getComplexFloatImag();
14659       APFloat &ResR = Result.getComplexFloatReal();
14660       APFloat &ResI = Result.getComplexFloatImag();
14661       if (RHSReal) {
14662         ResR = A / C;
14663         ResI = B / C;
14664       } else {
14665         if (LHSReal) {
14666           // No real optimizations we can do here, stub out with zero.
14667           B = APFloat::getZero(A.getSemantics());
14668         }
14669         int DenomLogB = 0;
14670         APFloat MaxCD = maxnum(abs(C), abs(D));
14671         if (MaxCD.isFinite()) {
14672           DenomLogB = ilogb(MaxCD);
14673           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14674           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14675         }
14676         APFloat Denom = C * C + D * D;
14677         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14678                       APFloat::rmNearestTiesToEven);
14679         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14680                       APFloat::rmNearestTiesToEven);
14681         if (ResR.isNaN() && ResI.isNaN()) {
14682           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14683             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14684             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14685           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14686                      D.isFinite()) {
14687             A = APFloat::copySign(
14688                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14689             B = APFloat::copySign(
14690                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14691             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14692             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14693           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14694             C = APFloat::copySign(
14695                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14696             D = APFloat::copySign(
14697                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14698             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14699             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14700           }
14701         }
14702       }
14703     } else {
14704       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14705         return Error(E, diag::note_expr_divide_by_zero);
14706 
14707       ComplexValue LHS = Result;
14708       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14709         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14710       Result.getComplexIntReal() =
14711         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14712          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14713       Result.getComplexIntImag() =
14714         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14715          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14716     }
14717     break;
14718   }
14719 
14720   return true;
14721 }
14722 
VisitUnaryOperator(const UnaryOperator * E)14723 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14724   // Get the operand value into 'Result'.
14725   if (!Visit(E->getSubExpr()))
14726     return false;
14727 
14728   switch (E->getOpcode()) {
14729   default:
14730     return Error(E);
14731   case UO_Extension:
14732     return true;
14733   case UO_Plus:
14734     // The result is always just the subexpr.
14735     return true;
14736   case UO_Minus:
14737     if (Result.isComplexFloat()) {
14738       Result.getComplexFloatReal().changeSign();
14739       Result.getComplexFloatImag().changeSign();
14740     }
14741     else {
14742       Result.getComplexIntReal() = -Result.getComplexIntReal();
14743       Result.getComplexIntImag() = -Result.getComplexIntImag();
14744     }
14745     return true;
14746   case UO_Not:
14747     if (Result.isComplexFloat())
14748       Result.getComplexFloatImag().changeSign();
14749     else
14750       Result.getComplexIntImag() = -Result.getComplexIntImag();
14751     return true;
14752   }
14753 }
14754 
VisitInitListExpr(const InitListExpr * E)14755 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14756   if (E->getNumInits() == 2) {
14757     if (E->getType()->isComplexType()) {
14758       Result.makeComplexFloat();
14759       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14760         return false;
14761       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14762         return false;
14763     } else {
14764       Result.makeComplexInt();
14765       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14766         return false;
14767       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14768         return false;
14769     }
14770     return true;
14771   }
14772   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14773 }
14774 
VisitCallExpr(const CallExpr * E)14775 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14776   if (!IsConstantEvaluatedBuiltinCall(E))
14777     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14778 
14779   switch (E->getBuiltinCallee()) {
14780   case Builtin::BI__builtin_complex:
14781     Result.makeComplexFloat();
14782     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14783       return false;
14784     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14785       return false;
14786     return true;
14787 
14788   default:
14789     return false;
14790   }
14791 }
14792 
14793 //===----------------------------------------------------------------------===//
14794 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14795 // implicit conversion.
14796 //===----------------------------------------------------------------------===//
14797 
14798 namespace {
14799 class AtomicExprEvaluator :
14800     public ExprEvaluatorBase<AtomicExprEvaluator> {
14801   const LValue *This;
14802   APValue &Result;
14803 public:
AtomicExprEvaluator(EvalInfo & Info,const LValue * This,APValue & Result)14804   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14805       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14806 
Success(const APValue & V,const Expr * E)14807   bool Success(const APValue &V, const Expr *E) {
14808     Result = V;
14809     return true;
14810   }
14811 
ZeroInitialization(const Expr * E)14812   bool ZeroInitialization(const Expr *E) {
14813     ImplicitValueInitExpr VIE(
14814         E->getType()->castAs<AtomicType>()->getValueType());
14815     // For atomic-qualified class (and array) types in C++, initialize the
14816     // _Atomic-wrapped subobject directly, in-place.
14817     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14818                 : Evaluate(Result, Info, &VIE);
14819   }
14820 
VisitCastExpr(const CastExpr * E)14821   bool VisitCastExpr(const CastExpr *E) {
14822     switch (E->getCastKind()) {
14823     default:
14824       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14825     case CK_NonAtomicToAtomic:
14826       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14827                   : Evaluate(Result, Info, E->getSubExpr());
14828     }
14829   }
14830 };
14831 } // end anonymous namespace
14832 
EvaluateAtomic(const Expr * E,const LValue * This,APValue & Result,EvalInfo & Info)14833 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14834                            EvalInfo &Info) {
14835   assert(!E->isValueDependent());
14836   assert(E->isPRValue() && E->getType()->isAtomicType());
14837   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14838 }
14839 
14840 //===----------------------------------------------------------------------===//
14841 // Void expression evaluation, primarily for a cast to void on the LHS of a
14842 // comma operator
14843 //===----------------------------------------------------------------------===//
14844 
14845 namespace {
14846 class VoidExprEvaluator
14847   : public ExprEvaluatorBase<VoidExprEvaluator> {
14848 public:
VoidExprEvaluator(EvalInfo & Info)14849   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14850 
Success(const APValue & V,const Expr * e)14851   bool Success(const APValue &V, const Expr *e) { return true; }
14852 
ZeroInitialization(const Expr * E)14853   bool ZeroInitialization(const Expr *E) { return true; }
14854 
VisitCastExpr(const CastExpr * E)14855   bool VisitCastExpr(const CastExpr *E) {
14856     switch (E->getCastKind()) {
14857     default:
14858       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14859     case CK_ToVoid:
14860       VisitIgnoredValue(E->getSubExpr());
14861       return true;
14862     }
14863   }
14864 
VisitCallExpr(const CallExpr * E)14865   bool VisitCallExpr(const CallExpr *E) {
14866     if (!IsConstantEvaluatedBuiltinCall(E))
14867       return ExprEvaluatorBaseTy::VisitCallExpr(E);
14868 
14869     switch (E->getBuiltinCallee()) {
14870     case Builtin::BI__assume:
14871     case Builtin::BI__builtin_assume:
14872       // The argument is not evaluated!
14873       return true;
14874 
14875     case Builtin::BI__builtin_operator_delete:
14876       return HandleOperatorDeleteCall(Info, E);
14877 
14878     default:
14879       return false;
14880     }
14881   }
14882 
14883   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14884 };
14885 } // end anonymous namespace
14886 
VisitCXXDeleteExpr(const CXXDeleteExpr * E)14887 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14888   // We cannot speculatively evaluate a delete expression.
14889   if (Info.SpeculativeEvaluationDepth)
14890     return false;
14891 
14892   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14893   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14894     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14895         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14896     return false;
14897   }
14898 
14899   const Expr *Arg = E->getArgument();
14900 
14901   LValue Pointer;
14902   if (!EvaluatePointer(Arg, Pointer, Info))
14903     return false;
14904   if (Pointer.Designator.Invalid)
14905     return false;
14906 
14907   // Deleting a null pointer has no effect.
14908   if (Pointer.isNullPointer()) {
14909     // This is the only case where we need to produce an extension warning:
14910     // the only other way we can succeed is if we find a dynamic allocation,
14911     // and we will have warned when we allocated it in that case.
14912     if (!Info.getLangOpts().CPlusPlus20)
14913       Info.CCEDiag(E, diag::note_constexpr_new);
14914     return true;
14915   }
14916 
14917   std::optional<DynAlloc *> Alloc = CheckDeleteKind(
14918       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14919   if (!Alloc)
14920     return false;
14921   QualType AllocType = Pointer.Base.getDynamicAllocType();
14922 
14923   // For the non-array case, the designator must be empty if the static type
14924   // does not have a virtual destructor.
14925   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14926       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14927     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14928         << Arg->getType()->getPointeeType() << AllocType;
14929     return false;
14930   }
14931 
14932   // For a class type with a virtual destructor, the selected operator delete
14933   // is the one looked up when building the destructor.
14934   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14935     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14936     if (VirtualDelete &&
14937         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14938       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14939           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14940       return false;
14941     }
14942   }
14943 
14944   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14945                          (*Alloc)->Value, AllocType))
14946     return false;
14947 
14948   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14949     // The element was already erased. This means the destructor call also
14950     // deleted the object.
14951     // FIXME: This probably results in undefined behavior before we get this
14952     // far, and should be diagnosed elsewhere first.
14953     Info.FFDiag(E, diag::note_constexpr_double_delete);
14954     return false;
14955   }
14956 
14957   return true;
14958 }
14959 
EvaluateVoid(const Expr * E,EvalInfo & Info)14960 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14961   assert(!E->isValueDependent());
14962   assert(E->isPRValue() && E->getType()->isVoidType());
14963   return VoidExprEvaluator(Info).Visit(E);
14964 }
14965 
14966 //===----------------------------------------------------------------------===//
14967 // Top level Expr::EvaluateAsRValue method.
14968 //===----------------------------------------------------------------------===//
14969 
Evaluate(APValue & Result,EvalInfo & Info,const Expr * E)14970 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14971   assert(!E->isValueDependent());
14972   // In C, function designators are not lvalues, but we evaluate them as if they
14973   // are.
14974   QualType T = E->getType();
14975   if (E->isGLValue() || T->isFunctionType()) {
14976     LValue LV;
14977     if (!EvaluateLValue(E, LV, Info))
14978       return false;
14979     LV.moveInto(Result);
14980   } else if (T->isVectorType()) {
14981     if (!EvaluateVector(E, Result, Info))
14982       return false;
14983   } else if (T->isIntegralOrEnumerationType()) {
14984     if (!IntExprEvaluator(Info, Result).Visit(E))
14985       return false;
14986   } else if (T->hasPointerRepresentation()) {
14987     LValue LV;
14988     if (!EvaluatePointer(E, LV, Info))
14989       return false;
14990     LV.moveInto(Result);
14991   } else if (T->isRealFloatingType()) {
14992     llvm::APFloat F(0.0);
14993     if (!EvaluateFloat(E, F, Info))
14994       return false;
14995     Result = APValue(F);
14996   } else if (T->isAnyComplexType()) {
14997     ComplexValue C;
14998     if (!EvaluateComplex(E, C, Info))
14999       return false;
15000     C.moveInto(Result);
15001   } else if (T->isFixedPointType()) {
15002     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
15003   } else if (T->isMemberPointerType()) {
15004     MemberPtr P;
15005     if (!EvaluateMemberPointer(E, P, Info))
15006       return false;
15007     P.moveInto(Result);
15008     return true;
15009   } else if (T->isArrayType()) {
15010     LValue LV;
15011     APValue &Value =
15012         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15013     if (!EvaluateArray(E, LV, Value, Info))
15014       return false;
15015     Result = Value;
15016   } else if (T->isRecordType()) {
15017     LValue LV;
15018     APValue &Value =
15019         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15020     if (!EvaluateRecord(E, LV, Value, Info))
15021       return false;
15022     Result = Value;
15023   } else if (T->isVoidType()) {
15024     if (!Info.getLangOpts().CPlusPlus11)
15025       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
15026         << E->getType();
15027     if (!EvaluateVoid(E, Info))
15028       return false;
15029   } else if (T->isAtomicType()) {
15030     QualType Unqual = T.getAtomicUnqualifiedType();
15031     if (Unqual->isArrayType() || Unqual->isRecordType()) {
15032       LValue LV;
15033       APValue &Value = Info.CurrentCall->createTemporary(
15034           E, Unqual, ScopeKind::FullExpression, LV);
15035       if (!EvaluateAtomic(E, &LV, Value, Info))
15036         return false;
15037     } else {
15038       if (!EvaluateAtomic(E, nullptr, Result, Info))
15039         return false;
15040     }
15041   } else if (Info.getLangOpts().CPlusPlus11) {
15042     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
15043     return false;
15044   } else {
15045     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15046     return false;
15047   }
15048 
15049   return true;
15050 }
15051 
15052 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
15053 /// cases, the in-place evaluation is essential, since later initializers for
15054 /// an object can indirectly refer to subobjects which were initialized earlier.
EvaluateInPlace(APValue & Result,EvalInfo & Info,const LValue & This,const Expr * E,bool AllowNonLiteralTypes)15055 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
15056                             const Expr *E, bool AllowNonLiteralTypes) {
15057   assert(!E->isValueDependent());
15058 
15059   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
15060     return false;
15061 
15062   if (E->isPRValue()) {
15063     // Evaluate arrays and record types in-place, so that later initializers can
15064     // refer to earlier-initialized members of the object.
15065     QualType T = E->getType();
15066     if (T->isArrayType())
15067       return EvaluateArray(E, This, Result, Info);
15068     else if (T->isRecordType())
15069       return EvaluateRecord(E, This, Result, Info);
15070     else if (T->isAtomicType()) {
15071       QualType Unqual = T.getAtomicUnqualifiedType();
15072       if (Unqual->isArrayType() || Unqual->isRecordType())
15073         return EvaluateAtomic(E, &This, Result, Info);
15074     }
15075   }
15076 
15077   // For any other type, in-place evaluation is unimportant.
15078   return Evaluate(Result, Info, E);
15079 }
15080 
15081 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
15082 /// lvalue-to-rvalue cast if it is an lvalue.
EvaluateAsRValue(EvalInfo & Info,const Expr * E,APValue & Result)15083 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
15084   assert(!E->isValueDependent());
15085 
15086   if (E->getType().isNull())
15087     return false;
15088 
15089   if (!CheckLiteralType(Info, E))
15090     return false;
15091 
15092   if (Info.EnableNewConstInterp) {
15093     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
15094       return false;
15095   } else {
15096     if (!::Evaluate(Result, Info, E))
15097       return false;
15098   }
15099 
15100   // Implicit lvalue-to-rvalue cast.
15101   if (E->isGLValue()) {
15102     LValue LV;
15103     LV.setFrom(Info.Ctx, Result);
15104     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
15105       return false;
15106   }
15107 
15108   // Check this core constant expression is a constant expression.
15109   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15110                                  ConstantExprKind::Normal) &&
15111          CheckMemoryLeaks(Info);
15112 }
15113 
FastEvaluateAsRValue(const Expr * Exp,Expr::EvalResult & Result,const ASTContext & Ctx,bool & IsConst)15114 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
15115                                  const ASTContext &Ctx, bool &IsConst) {
15116   // Fast-path evaluations of integer literals, since we sometimes see files
15117   // containing vast quantities of these.
15118   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
15119     Result.Val = APValue(APSInt(L->getValue(),
15120                                 L->getType()->isUnsignedIntegerType()));
15121     IsConst = true;
15122     return true;
15123   }
15124 
15125   if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
15126     Result.Val = APValue(APSInt(APInt(1, L->getValue())));
15127     IsConst = true;
15128     return true;
15129   }
15130 
15131   // This case should be rare, but we need to check it before we check on
15132   // the type below.
15133   if (Exp->getType().isNull()) {
15134     IsConst = false;
15135     return true;
15136   }
15137 
15138   // FIXME: Evaluating values of large array and record types can cause
15139   // performance problems. Only do so in C++11 for now.
15140   if (Exp->isPRValue() &&
15141       (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
15142       !Ctx.getLangOpts().CPlusPlus11) {
15143     IsConst = false;
15144     return true;
15145   }
15146   return false;
15147 }
15148 
hasUnacceptableSideEffect(Expr::EvalStatus & Result,Expr::SideEffectsKind SEK)15149 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
15150                                       Expr::SideEffectsKind SEK) {
15151   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
15152          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
15153 }
15154 
EvaluateAsRValue(const Expr * E,Expr::EvalResult & Result,const ASTContext & Ctx,EvalInfo & Info)15155 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
15156                              const ASTContext &Ctx, EvalInfo &Info) {
15157   assert(!E->isValueDependent());
15158   bool IsConst;
15159   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
15160     return IsConst;
15161 
15162   return EvaluateAsRValue(Info, E, Result.Val);
15163 }
15164 
EvaluateAsInt(const Expr * E,Expr::EvalResult & ExprResult,const ASTContext & Ctx,Expr::SideEffectsKind AllowSideEffects,EvalInfo & Info)15165 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
15166                           const ASTContext &Ctx,
15167                           Expr::SideEffectsKind AllowSideEffects,
15168                           EvalInfo &Info) {
15169   assert(!E->isValueDependent());
15170   if (!E->getType()->isIntegralOrEnumerationType())
15171     return false;
15172 
15173   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
15174       !ExprResult.Val.isInt() ||
15175       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15176     return false;
15177 
15178   return true;
15179 }
15180 
EvaluateAsFixedPoint(const Expr * E,Expr::EvalResult & ExprResult,const ASTContext & Ctx,Expr::SideEffectsKind AllowSideEffects,EvalInfo & Info)15181 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
15182                                  const ASTContext &Ctx,
15183                                  Expr::SideEffectsKind AllowSideEffects,
15184                                  EvalInfo &Info) {
15185   assert(!E->isValueDependent());
15186   if (!E->getType()->isFixedPointType())
15187     return false;
15188 
15189   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
15190     return false;
15191 
15192   if (!ExprResult.Val.isFixedPoint() ||
15193       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15194     return false;
15195 
15196   return true;
15197 }
15198 
15199 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
15200 /// any crazy technique (that has nothing to do with language standards) that
15201 /// we want to.  If this function returns true, it returns the folded constant
15202 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
15203 /// will be applied to the result.
EvaluateAsRValue(EvalResult & Result,const ASTContext & Ctx,bool InConstantContext) const15204 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
15205                             bool InConstantContext) const {
15206   assert(!isValueDependent() &&
15207          "Expression evaluator can't be called on a dependent expression.");
15208   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
15209   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15210   Info.InConstantContext = InConstantContext;
15211   return ::EvaluateAsRValue(this, Result, Ctx, Info);
15212 }
15213 
EvaluateAsBooleanCondition(bool & Result,const ASTContext & Ctx,bool InConstantContext) const15214 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
15215                                       bool InConstantContext) const {
15216   assert(!isValueDependent() &&
15217          "Expression evaluator can't be called on a dependent expression.");
15218   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
15219   EvalResult Scratch;
15220   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
15221          HandleConversionToBool(Scratch.Val, Result);
15222 }
15223 
EvaluateAsInt(EvalResult & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const15224 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
15225                          SideEffectsKind AllowSideEffects,
15226                          bool InConstantContext) const {
15227   assert(!isValueDependent() &&
15228          "Expression evaluator can't be called on a dependent expression.");
15229   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
15230   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15231   Info.InConstantContext = InConstantContext;
15232   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
15233 }
15234 
EvaluateAsFixedPoint(EvalResult & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const15235 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
15236                                 SideEffectsKind AllowSideEffects,
15237                                 bool InConstantContext) const {
15238   assert(!isValueDependent() &&
15239          "Expression evaluator can't be called on a dependent expression.");
15240   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
15241   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15242   Info.InConstantContext = InConstantContext;
15243   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
15244 }
15245 
EvaluateAsFloat(APFloat & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const15246 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
15247                            SideEffectsKind AllowSideEffects,
15248                            bool InConstantContext) const {
15249   assert(!isValueDependent() &&
15250          "Expression evaluator can't be called on a dependent expression.");
15251 
15252   if (!getType()->isRealFloatingType())
15253     return false;
15254 
15255   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
15256   EvalResult ExprResult;
15257   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
15258       !ExprResult.Val.isFloat() ||
15259       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15260     return false;
15261 
15262   Result = ExprResult.Val.getFloat();
15263   return true;
15264 }
15265 
EvaluateAsLValue(EvalResult & Result,const ASTContext & Ctx,bool InConstantContext) const15266 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
15267                             bool InConstantContext) const {
15268   assert(!isValueDependent() &&
15269          "Expression evaluator can't be called on a dependent expression.");
15270 
15271   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
15272   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
15273   Info.InConstantContext = InConstantContext;
15274   LValue LV;
15275   CheckedTemporaries CheckedTemps;
15276   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
15277       Result.HasSideEffects ||
15278       !CheckLValueConstantExpression(Info, getExprLoc(),
15279                                      Ctx.getLValueReferenceType(getType()), LV,
15280                                      ConstantExprKind::Normal, CheckedTemps))
15281     return false;
15282 
15283   LV.moveInto(Result.Val);
15284   return true;
15285 }
15286 
EvaluateDestruction(const ASTContext & Ctx,APValue::LValueBase Base,APValue DestroyedValue,QualType Type,SourceLocation Loc,Expr::EvalStatus & EStatus,bool IsConstantDestruction)15287 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
15288                                 APValue DestroyedValue, QualType Type,
15289                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
15290                                 bool IsConstantDestruction) {
15291   EvalInfo Info(Ctx, EStatus,
15292                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
15293                                       : EvalInfo::EM_ConstantFold);
15294   Info.setEvaluatingDecl(Base, DestroyedValue,
15295                          EvalInfo::EvaluatingDeclKind::Dtor);
15296   Info.InConstantContext = IsConstantDestruction;
15297 
15298   LValue LVal;
15299   LVal.set(Base);
15300 
15301   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
15302       EStatus.HasSideEffects)
15303     return false;
15304 
15305   if (!Info.discardCleanups())
15306     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15307 
15308   return true;
15309 }
15310 
EvaluateAsConstantExpr(EvalResult & Result,const ASTContext & Ctx,ConstantExprKind Kind) const15311 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
15312                                   ConstantExprKind Kind) const {
15313   assert(!isValueDependent() &&
15314          "Expression evaluator can't be called on a dependent expression.");
15315   bool IsConst;
15316   if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue())
15317     return true;
15318 
15319   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
15320   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
15321   EvalInfo Info(Ctx, Result, EM);
15322   Info.InConstantContext = true;
15323 
15324   // The type of the object we're initializing is 'const T' for a class NTTP.
15325   QualType T = getType();
15326   if (Kind == ConstantExprKind::ClassTemplateArgument)
15327     T.addConst();
15328 
15329   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
15330   // represent the result of the evaluation. CheckConstantExpression ensures
15331   // this doesn't escape.
15332   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
15333   APValue::LValueBase Base(&BaseMTE);
15334 
15335   Info.setEvaluatingDecl(Base, Result.Val);
15336   LValue LVal;
15337   LVal.set(Base);
15338 
15339   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
15340     return false;
15341 
15342   if (!Info.discardCleanups())
15343     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15344 
15345   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
15346                                Result.Val, Kind))
15347     return false;
15348   if (!CheckMemoryLeaks(Info))
15349     return false;
15350 
15351   // If this is a class template argument, it's required to have constant
15352   // destruction too.
15353   if (Kind == ConstantExprKind::ClassTemplateArgument &&
15354       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
15355                             true) ||
15356        Result.HasSideEffects)) {
15357     // FIXME: Prefix a note to indicate that the problem is lack of constant
15358     // destruction.
15359     return false;
15360   }
15361 
15362   return true;
15363 }
15364 
EvaluateAsInitializer(APValue & Value,const ASTContext & Ctx,const VarDecl * VD,SmallVectorImpl<PartialDiagnosticAt> & Notes,bool IsConstantInitialization) const15365 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
15366                                  const VarDecl *VD,
15367                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
15368                                  bool IsConstantInitialization) const {
15369   assert(!isValueDependent() &&
15370          "Expression evaluator can't be called on a dependent expression.");
15371 
15372   llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
15373     std::string Name;
15374     llvm::raw_string_ostream OS(Name);
15375     VD->printQualifiedName(OS);
15376     return Name;
15377   });
15378 
15379   // FIXME: Evaluating initializers for large array and record types can cause
15380   // performance problems. Only do so in C++11 for now.
15381   if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
15382       !Ctx.getLangOpts().CPlusPlus11)
15383     return false;
15384 
15385   Expr::EvalStatus EStatus;
15386   EStatus.Diag = &Notes;
15387 
15388   EvalInfo Info(Ctx, EStatus,
15389                 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
15390                     ? EvalInfo::EM_ConstantExpression
15391                     : EvalInfo::EM_ConstantFold);
15392   Info.setEvaluatingDecl(VD, Value);
15393   Info.InConstantContext = IsConstantInitialization;
15394 
15395   SourceLocation DeclLoc = VD->getLocation();
15396   QualType DeclTy = VD->getType();
15397 
15398   if (Info.EnableNewConstInterp) {
15399     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
15400     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
15401       return false;
15402   } else {
15403     LValue LVal;
15404     LVal.set(VD);
15405 
15406     if (!EvaluateInPlace(Value, Info, LVal, this,
15407                          /*AllowNonLiteralTypes=*/true) ||
15408         EStatus.HasSideEffects)
15409       return false;
15410 
15411     // At this point, any lifetime-extended temporaries are completely
15412     // initialized.
15413     Info.performLifetimeExtension();
15414 
15415     if (!Info.discardCleanups())
15416       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15417   }
15418   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15419                                  ConstantExprKind::Normal) &&
15420          CheckMemoryLeaks(Info);
15421 }
15422 
evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> & Notes) const15423 bool VarDecl::evaluateDestruction(
15424     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15425   Expr::EvalStatus EStatus;
15426   EStatus.Diag = &Notes;
15427 
15428   // Only treat the destruction as constant destruction if we formally have
15429   // constant initialization (or are usable in a constant expression).
15430   bool IsConstantDestruction = hasConstantInitialization();
15431 
15432   // Make a copy of the value for the destructor to mutate, if we know it.
15433   // Otherwise, treat the value as default-initialized; if the destructor works
15434   // anyway, then the destruction is constant (and must be essentially empty).
15435   APValue DestroyedValue;
15436   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15437     DestroyedValue = *getEvaluatedValue();
15438   else if (!getDefaultInitValue(getType(), DestroyedValue))
15439     return false;
15440 
15441   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15442                            getType(), getLocation(), EStatus,
15443                            IsConstantDestruction) ||
15444       EStatus.HasSideEffects)
15445     return false;
15446 
15447   ensureEvaluatedStmt()->HasConstantDestruction = true;
15448   return true;
15449 }
15450 
15451 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15452 /// constant folded, but discard the result.
isEvaluatable(const ASTContext & Ctx,SideEffectsKind SEK) const15453 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15454   assert(!isValueDependent() &&
15455          "Expression evaluator can't be called on a dependent expression.");
15456 
15457   EvalResult Result;
15458   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15459          !hasUnacceptableSideEffect(Result, SEK);
15460 }
15461 
EvaluateKnownConstInt(const ASTContext & Ctx,SmallVectorImpl<PartialDiagnosticAt> * Diag) const15462 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15463                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15464   assert(!isValueDependent() &&
15465          "Expression evaluator can't be called on a dependent expression.");
15466 
15467   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
15468   EvalResult EVResult;
15469   EVResult.Diag = Diag;
15470   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15471   Info.InConstantContext = true;
15472 
15473   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15474   (void)Result;
15475   assert(Result && "Could not evaluate expression");
15476   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15477 
15478   return EVResult.Val.getInt();
15479 }
15480 
EvaluateKnownConstIntCheckOverflow(const ASTContext & Ctx,SmallVectorImpl<PartialDiagnosticAt> * Diag) const15481 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15482     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15483   assert(!isValueDependent() &&
15484          "Expression evaluator can't be called on a dependent expression.");
15485 
15486   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
15487   EvalResult EVResult;
15488   EVResult.Diag = Diag;
15489   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15490   Info.InConstantContext = true;
15491   Info.CheckingForUndefinedBehavior = true;
15492 
15493   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15494   (void)Result;
15495   assert(Result && "Could not evaluate expression");
15496   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15497 
15498   return EVResult.Val.getInt();
15499 }
15500 
EvaluateForOverflow(const ASTContext & Ctx) const15501 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15502   assert(!isValueDependent() &&
15503          "Expression evaluator can't be called on a dependent expression.");
15504 
15505   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
15506   bool IsConst;
15507   EvalResult EVResult;
15508   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15509     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15510     Info.CheckingForUndefinedBehavior = true;
15511     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15512   }
15513 }
15514 
isGlobalLValue() const15515 bool Expr::EvalResult::isGlobalLValue() const {
15516   assert(Val.isLValue());
15517   return IsGlobalLValue(Val.getLValueBase());
15518 }
15519 
15520 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15521 /// an integer constant expression.
15522 
15523 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15524 /// comma, etc
15525 
15526 // CheckICE - This function does the fundamental ICE checking: the returned
15527 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15528 // and a (possibly null) SourceLocation indicating the location of the problem.
15529 //
15530 // Note that to reduce code duplication, this helper does no evaluation
15531 // itself; the caller checks whether the expression is evaluatable, and
15532 // in the rare cases where CheckICE actually cares about the evaluated
15533 // value, it calls into Evaluate.
15534 
15535 namespace {
15536 
15537 enum ICEKind {
15538   /// This expression is an ICE.
15539   IK_ICE,
15540   /// This expression is not an ICE, but if it isn't evaluated, it's
15541   /// a legal subexpression for an ICE. This return value is used to handle
15542   /// the comma operator in C99 mode, and non-constant subexpressions.
15543   IK_ICEIfUnevaluated,
15544   /// This expression is not an ICE, and is not a legal subexpression for one.
15545   IK_NotICE
15546 };
15547 
15548 struct ICEDiag {
15549   ICEKind Kind;
15550   SourceLocation Loc;
15551 
ICEDiag__anond52d8a673911::ICEDiag15552   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15553 };
15554 
15555 }
15556 
NoDiag()15557 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15558 
Worst(ICEDiag A,ICEDiag B)15559 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15560 
CheckEvalInICE(const Expr * E,const ASTContext & Ctx)15561 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15562   Expr::EvalResult EVResult;
15563   Expr::EvalStatus Status;
15564   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15565 
15566   Info.InConstantContext = true;
15567   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15568       !EVResult.Val.isInt())
15569     return ICEDiag(IK_NotICE, E->getBeginLoc());
15570 
15571   return NoDiag();
15572 }
15573 
CheckICE(const Expr * E,const ASTContext & Ctx)15574 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15575   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15576   if (!E->getType()->isIntegralOrEnumerationType())
15577     return ICEDiag(IK_NotICE, E->getBeginLoc());
15578 
15579   switch (E->getStmtClass()) {
15580 #define ABSTRACT_STMT(Node)
15581 #define STMT(Node, Base) case Expr::Node##Class:
15582 #define EXPR(Node, Base)
15583 #include "clang/AST/StmtNodes.inc"
15584   case Expr::PredefinedExprClass:
15585   case Expr::FloatingLiteralClass:
15586   case Expr::ImaginaryLiteralClass:
15587   case Expr::StringLiteralClass:
15588   case Expr::ArraySubscriptExprClass:
15589   case Expr::MatrixSubscriptExprClass:
15590   case Expr::OMPArraySectionExprClass:
15591   case Expr::OMPArrayShapingExprClass:
15592   case Expr::OMPIteratorExprClass:
15593   case Expr::MemberExprClass:
15594   case Expr::CompoundAssignOperatorClass:
15595   case Expr::CompoundLiteralExprClass:
15596   case Expr::ExtVectorElementExprClass:
15597   case Expr::DesignatedInitExprClass:
15598   case Expr::ArrayInitLoopExprClass:
15599   case Expr::ArrayInitIndexExprClass:
15600   case Expr::NoInitExprClass:
15601   case Expr::DesignatedInitUpdateExprClass:
15602   case Expr::ImplicitValueInitExprClass:
15603   case Expr::ParenListExprClass:
15604   case Expr::VAArgExprClass:
15605   case Expr::AddrLabelExprClass:
15606   case Expr::StmtExprClass:
15607   case Expr::CXXMemberCallExprClass:
15608   case Expr::CUDAKernelCallExprClass:
15609   case Expr::CXXAddrspaceCastExprClass:
15610   case Expr::CXXDynamicCastExprClass:
15611   case Expr::CXXTypeidExprClass:
15612   case Expr::CXXUuidofExprClass:
15613   case Expr::MSPropertyRefExprClass:
15614   case Expr::MSPropertySubscriptExprClass:
15615   case Expr::CXXNullPtrLiteralExprClass:
15616   case Expr::UserDefinedLiteralClass:
15617   case Expr::CXXThisExprClass:
15618   case Expr::CXXThrowExprClass:
15619   case Expr::CXXNewExprClass:
15620   case Expr::CXXDeleteExprClass:
15621   case Expr::CXXPseudoDestructorExprClass:
15622   case Expr::UnresolvedLookupExprClass:
15623   case Expr::TypoExprClass:
15624   case Expr::RecoveryExprClass:
15625   case Expr::DependentScopeDeclRefExprClass:
15626   case Expr::CXXConstructExprClass:
15627   case Expr::CXXInheritedCtorInitExprClass:
15628   case Expr::CXXStdInitializerListExprClass:
15629   case Expr::CXXBindTemporaryExprClass:
15630   case Expr::ExprWithCleanupsClass:
15631   case Expr::CXXTemporaryObjectExprClass:
15632   case Expr::CXXUnresolvedConstructExprClass:
15633   case Expr::CXXDependentScopeMemberExprClass:
15634   case Expr::UnresolvedMemberExprClass:
15635   case Expr::ObjCStringLiteralClass:
15636   case Expr::ObjCBoxedExprClass:
15637   case Expr::ObjCArrayLiteralClass:
15638   case Expr::ObjCDictionaryLiteralClass:
15639   case Expr::ObjCEncodeExprClass:
15640   case Expr::ObjCMessageExprClass:
15641   case Expr::ObjCSelectorExprClass:
15642   case Expr::ObjCProtocolExprClass:
15643   case Expr::ObjCIvarRefExprClass:
15644   case Expr::ObjCPropertyRefExprClass:
15645   case Expr::ObjCSubscriptRefExprClass:
15646   case Expr::ObjCIsaExprClass:
15647   case Expr::ObjCAvailabilityCheckExprClass:
15648   case Expr::ShuffleVectorExprClass:
15649   case Expr::ConvertVectorExprClass:
15650   case Expr::BlockExprClass:
15651   case Expr::NoStmtClass:
15652   case Expr::OpaqueValueExprClass:
15653   case Expr::PackExpansionExprClass:
15654   case Expr::SubstNonTypeTemplateParmPackExprClass:
15655   case Expr::FunctionParmPackExprClass:
15656   case Expr::AsTypeExprClass:
15657   case Expr::ObjCIndirectCopyRestoreExprClass:
15658   case Expr::MaterializeTemporaryExprClass:
15659   case Expr::PseudoObjectExprClass:
15660   case Expr::AtomicExprClass:
15661   case Expr::LambdaExprClass:
15662   case Expr::CXXFoldExprClass:
15663   case Expr::CoawaitExprClass:
15664   case Expr::DependentCoawaitExprClass:
15665   case Expr::CoyieldExprClass:
15666   case Expr::SYCLUniqueStableNameExprClass:
15667   case Expr::CXXParenListInitExprClass:
15668     return ICEDiag(IK_NotICE, E->getBeginLoc());
15669 
15670   case Expr::InitListExprClass: {
15671     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15672     // form "T x = { a };" is equivalent to "T x = a;".
15673     // Unless we're initializing a reference, T is a scalar as it is known to be
15674     // of integral or enumeration type.
15675     if (E->isPRValue())
15676       if (cast<InitListExpr>(E)->getNumInits() == 1)
15677         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15678     return ICEDiag(IK_NotICE, E->getBeginLoc());
15679   }
15680 
15681   case Expr::SizeOfPackExprClass:
15682   case Expr::GNUNullExprClass:
15683   case Expr::SourceLocExprClass:
15684     return NoDiag();
15685 
15686   case Expr::SubstNonTypeTemplateParmExprClass:
15687     return
15688       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15689 
15690   case Expr::ConstantExprClass:
15691     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15692 
15693   case Expr::ParenExprClass:
15694     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15695   case Expr::GenericSelectionExprClass:
15696     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15697   case Expr::IntegerLiteralClass:
15698   case Expr::FixedPointLiteralClass:
15699   case Expr::CharacterLiteralClass:
15700   case Expr::ObjCBoolLiteralExprClass:
15701   case Expr::CXXBoolLiteralExprClass:
15702   case Expr::CXXScalarValueInitExprClass:
15703   case Expr::TypeTraitExprClass:
15704   case Expr::ConceptSpecializationExprClass:
15705   case Expr::RequiresExprClass:
15706   case Expr::ArrayTypeTraitExprClass:
15707   case Expr::ExpressionTraitExprClass:
15708   case Expr::CXXNoexceptExprClass:
15709     return NoDiag();
15710   case Expr::CallExprClass:
15711   case Expr::CXXOperatorCallExprClass: {
15712     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15713     // constant expressions, but they can never be ICEs because an ICE cannot
15714     // contain an operand of (pointer to) function type.
15715     const CallExpr *CE = cast<CallExpr>(E);
15716     if (CE->getBuiltinCallee())
15717       return CheckEvalInICE(E, Ctx);
15718     return ICEDiag(IK_NotICE, E->getBeginLoc());
15719   }
15720   case Expr::CXXRewrittenBinaryOperatorClass:
15721     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15722                     Ctx);
15723   case Expr::DeclRefExprClass: {
15724     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15725     if (isa<EnumConstantDecl>(D))
15726       return NoDiag();
15727 
15728     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15729     // integer variables in constant expressions:
15730     //
15731     // C++ 7.1.5.1p2
15732     //   A variable of non-volatile const-qualified integral or enumeration
15733     //   type initialized by an ICE can be used in ICEs.
15734     //
15735     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15736     // that mode, use of reference variables should not be allowed.
15737     const VarDecl *VD = dyn_cast<VarDecl>(D);
15738     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15739         !VD->getType()->isReferenceType())
15740       return NoDiag();
15741 
15742     return ICEDiag(IK_NotICE, E->getBeginLoc());
15743   }
15744   case Expr::UnaryOperatorClass: {
15745     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15746     switch (Exp->getOpcode()) {
15747     case UO_PostInc:
15748     case UO_PostDec:
15749     case UO_PreInc:
15750     case UO_PreDec:
15751     case UO_AddrOf:
15752     case UO_Deref:
15753     case UO_Coawait:
15754       // C99 6.6/3 allows increment and decrement within unevaluated
15755       // subexpressions of constant expressions, but they can never be ICEs
15756       // because an ICE cannot contain an lvalue operand.
15757       return ICEDiag(IK_NotICE, E->getBeginLoc());
15758     case UO_Extension:
15759     case UO_LNot:
15760     case UO_Plus:
15761     case UO_Minus:
15762     case UO_Not:
15763     case UO_Real:
15764     case UO_Imag:
15765       return CheckICE(Exp->getSubExpr(), Ctx);
15766     }
15767     llvm_unreachable("invalid unary operator class");
15768   }
15769   case Expr::OffsetOfExprClass: {
15770     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15771     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15772     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15773     // compliance: we should warn earlier for offsetof expressions with
15774     // array subscripts that aren't ICEs, and if the array subscripts
15775     // are ICEs, the value of the offsetof must be an integer constant.
15776     return CheckEvalInICE(E, Ctx);
15777   }
15778   case Expr::UnaryExprOrTypeTraitExprClass: {
15779     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15780     if ((Exp->getKind() ==  UETT_SizeOf) &&
15781         Exp->getTypeOfArgument()->isVariableArrayType())
15782       return ICEDiag(IK_NotICE, E->getBeginLoc());
15783     return NoDiag();
15784   }
15785   case Expr::BinaryOperatorClass: {
15786     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15787     switch (Exp->getOpcode()) {
15788     case BO_PtrMemD:
15789     case BO_PtrMemI:
15790     case BO_Assign:
15791     case BO_MulAssign:
15792     case BO_DivAssign:
15793     case BO_RemAssign:
15794     case BO_AddAssign:
15795     case BO_SubAssign:
15796     case BO_ShlAssign:
15797     case BO_ShrAssign:
15798     case BO_AndAssign:
15799     case BO_XorAssign:
15800     case BO_OrAssign:
15801       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15802       // constant expressions, but they can never be ICEs because an ICE cannot
15803       // contain an lvalue operand.
15804       return ICEDiag(IK_NotICE, E->getBeginLoc());
15805 
15806     case BO_Mul:
15807     case BO_Div:
15808     case BO_Rem:
15809     case BO_Add:
15810     case BO_Sub:
15811     case BO_Shl:
15812     case BO_Shr:
15813     case BO_LT:
15814     case BO_GT:
15815     case BO_LE:
15816     case BO_GE:
15817     case BO_EQ:
15818     case BO_NE:
15819     case BO_And:
15820     case BO_Xor:
15821     case BO_Or:
15822     case BO_Comma:
15823     case BO_Cmp: {
15824       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15825       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15826       if (Exp->getOpcode() == BO_Div ||
15827           Exp->getOpcode() == BO_Rem) {
15828         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15829         // we don't evaluate one.
15830         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15831           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15832           if (REval == 0)
15833             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15834           if (REval.isSigned() && REval.isAllOnes()) {
15835             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15836             if (LEval.isMinSignedValue())
15837               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15838           }
15839         }
15840       }
15841       if (Exp->getOpcode() == BO_Comma) {
15842         if (Ctx.getLangOpts().C99) {
15843           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15844           // if it isn't evaluated.
15845           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15846             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15847         } else {
15848           // In both C89 and C++, commas in ICEs are illegal.
15849           return ICEDiag(IK_NotICE, E->getBeginLoc());
15850         }
15851       }
15852       return Worst(LHSResult, RHSResult);
15853     }
15854     case BO_LAnd:
15855     case BO_LOr: {
15856       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15857       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15858       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15859         // Rare case where the RHS has a comma "side-effect"; we need
15860         // to actually check the condition to see whether the side
15861         // with the comma is evaluated.
15862         if ((Exp->getOpcode() == BO_LAnd) !=
15863             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15864           return RHSResult;
15865         return NoDiag();
15866       }
15867 
15868       return Worst(LHSResult, RHSResult);
15869     }
15870     }
15871     llvm_unreachable("invalid binary operator kind");
15872   }
15873   case Expr::ImplicitCastExprClass:
15874   case Expr::CStyleCastExprClass:
15875   case Expr::CXXFunctionalCastExprClass:
15876   case Expr::CXXStaticCastExprClass:
15877   case Expr::CXXReinterpretCastExprClass:
15878   case Expr::CXXConstCastExprClass:
15879   case Expr::ObjCBridgedCastExprClass: {
15880     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15881     if (isa<ExplicitCastExpr>(E)) {
15882       if (const FloatingLiteral *FL
15883             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15884         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15885         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15886         APSInt IgnoredVal(DestWidth, !DestSigned);
15887         bool Ignored;
15888         // If the value does not fit in the destination type, the behavior is
15889         // undefined, so we are not required to treat it as a constant
15890         // expression.
15891         if (FL->getValue().convertToInteger(IgnoredVal,
15892                                             llvm::APFloat::rmTowardZero,
15893                                             &Ignored) & APFloat::opInvalidOp)
15894           return ICEDiag(IK_NotICE, E->getBeginLoc());
15895         return NoDiag();
15896       }
15897     }
15898     switch (cast<CastExpr>(E)->getCastKind()) {
15899     case CK_LValueToRValue:
15900     case CK_AtomicToNonAtomic:
15901     case CK_NonAtomicToAtomic:
15902     case CK_NoOp:
15903     case CK_IntegralToBoolean:
15904     case CK_IntegralCast:
15905       return CheckICE(SubExpr, Ctx);
15906     default:
15907       return ICEDiag(IK_NotICE, E->getBeginLoc());
15908     }
15909   }
15910   case Expr::BinaryConditionalOperatorClass: {
15911     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15912     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15913     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15914     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15915     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15916     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15917     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15918         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15919     return FalseResult;
15920   }
15921   case Expr::ConditionalOperatorClass: {
15922     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15923     // If the condition (ignoring parens) is a __builtin_constant_p call,
15924     // then only the true side is actually considered in an integer constant
15925     // expression, and it is fully evaluated.  This is an important GNU
15926     // extension.  See GCC PR38377 for discussion.
15927     if (const CallExpr *CallCE
15928         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15929       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15930         return CheckEvalInICE(E, Ctx);
15931     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15932     if (CondResult.Kind == IK_NotICE)
15933       return CondResult;
15934 
15935     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15936     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15937 
15938     if (TrueResult.Kind == IK_NotICE)
15939       return TrueResult;
15940     if (FalseResult.Kind == IK_NotICE)
15941       return FalseResult;
15942     if (CondResult.Kind == IK_ICEIfUnevaluated)
15943       return CondResult;
15944     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15945       return NoDiag();
15946     // Rare case where the diagnostics depend on which side is evaluated
15947     // Note that if we get here, CondResult is 0, and at least one of
15948     // TrueResult and FalseResult is non-zero.
15949     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15950       return FalseResult;
15951     return TrueResult;
15952   }
15953   case Expr::CXXDefaultArgExprClass:
15954     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15955   case Expr::CXXDefaultInitExprClass:
15956     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15957   case Expr::ChooseExprClass: {
15958     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15959   }
15960   case Expr::BuiltinBitCastExprClass: {
15961     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15962       return ICEDiag(IK_NotICE, E->getBeginLoc());
15963     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15964   }
15965   }
15966 
15967   llvm_unreachable("Invalid StmtClass!");
15968 }
15969 
15970 /// Evaluate an expression as a C++11 integral constant expression.
EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext & Ctx,const Expr * E,llvm::APSInt * Value,SourceLocation * Loc)15971 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15972                                                     const Expr *E,
15973                                                     llvm::APSInt *Value,
15974                                                     SourceLocation *Loc) {
15975   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15976     if (Loc) *Loc = E->getExprLoc();
15977     return false;
15978   }
15979 
15980   APValue Result;
15981   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15982     return false;
15983 
15984   if (!Result.isInt()) {
15985     if (Loc) *Loc = E->getExprLoc();
15986     return false;
15987   }
15988 
15989   if (Value) *Value = Result.getInt();
15990   return true;
15991 }
15992 
isIntegerConstantExpr(const ASTContext & Ctx,SourceLocation * Loc) const15993 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15994                                  SourceLocation *Loc) const {
15995   assert(!isValueDependent() &&
15996          "Expression evaluator can't be called on a dependent expression.");
15997 
15998   ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
15999 
16000   if (Ctx.getLangOpts().CPlusPlus11)
16001     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
16002 
16003   ICEDiag D = CheckICE(this, Ctx);
16004   if (D.Kind != IK_ICE) {
16005     if (Loc) *Loc = D.Loc;
16006     return false;
16007   }
16008   return true;
16009 }
16010 
16011 std::optional<llvm::APSInt>
getIntegerConstantExpr(const ASTContext & Ctx,SourceLocation * Loc,bool isEvaluated) const16012 Expr::getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc,
16013                              bool isEvaluated) const {
16014   if (isValueDependent()) {
16015     // Expression evaluator can't succeed on a dependent expression.
16016     return std::nullopt;
16017   }
16018 
16019   APSInt Value;
16020 
16021   if (Ctx.getLangOpts().CPlusPlus11) {
16022     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
16023       return Value;
16024     return std::nullopt;
16025   }
16026 
16027   if (!isIntegerConstantExpr(Ctx, Loc))
16028     return std::nullopt;
16029 
16030   // The only possible side-effects here are due to UB discovered in the
16031   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
16032   // required to treat the expression as an ICE, so we produce the folded
16033   // value.
16034   EvalResult ExprResult;
16035   Expr::EvalStatus Status;
16036   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
16037   Info.InConstantContext = true;
16038 
16039   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
16040     llvm_unreachable("ICE cannot be evaluated!");
16041 
16042   return ExprResult.Val.getInt();
16043 }
16044 
isCXX98IntegralConstantExpr(const ASTContext & Ctx) const16045 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
16046   assert(!isValueDependent() &&
16047          "Expression evaluator can't be called on a dependent expression.");
16048 
16049   return CheckICE(this, Ctx).Kind == IK_ICE;
16050 }
16051 
isCXX11ConstantExpr(const ASTContext & Ctx,APValue * Result,SourceLocation * Loc) const16052 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
16053                                SourceLocation *Loc) const {
16054   assert(!isValueDependent() &&
16055          "Expression evaluator can't be called on a dependent expression.");
16056 
16057   // We support this checking in C++98 mode in order to diagnose compatibility
16058   // issues.
16059   assert(Ctx.getLangOpts().CPlusPlus);
16060 
16061   // Build evaluation settings.
16062   Expr::EvalStatus Status;
16063   SmallVector<PartialDiagnosticAt, 8> Diags;
16064   Status.Diag = &Diags;
16065   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16066 
16067   APValue Scratch;
16068   bool IsConstExpr =
16069       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
16070       // FIXME: We don't produce a diagnostic for this, but the callers that
16071       // call us on arbitrary full-expressions should generally not care.
16072       Info.discardCleanups() && !Status.HasSideEffects;
16073 
16074   if (!Diags.empty()) {
16075     IsConstExpr = false;
16076     if (Loc) *Loc = Diags[0].first;
16077   } else if (!IsConstExpr) {
16078     // FIXME: This shouldn't happen.
16079     if (Loc) *Loc = getExprLoc();
16080   }
16081 
16082   return IsConstExpr;
16083 }
16084 
EvaluateWithSubstitution(APValue & Value,ASTContext & Ctx,const FunctionDecl * Callee,ArrayRef<const Expr * > Args,const Expr * This) const16085 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
16086                                     const FunctionDecl *Callee,
16087                                     ArrayRef<const Expr*> Args,
16088                                     const Expr *This) const {
16089   assert(!isValueDependent() &&
16090          "Expression evaluator can't be called on a dependent expression.");
16091 
16092   llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
16093     std::string Name;
16094     llvm::raw_string_ostream OS(Name);
16095     Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
16096                                  /*Qualified=*/true);
16097     return Name;
16098   });
16099 
16100   Expr::EvalStatus Status;
16101   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
16102   Info.InConstantContext = true;
16103 
16104   LValue ThisVal;
16105   const LValue *ThisPtr = nullptr;
16106   if (This) {
16107 #ifndef NDEBUG
16108     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
16109     assert(MD && "Don't provide `this` for non-methods.");
16110     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
16111 #endif
16112     if (!This->isValueDependent() &&
16113         EvaluateObjectArgument(Info, This, ThisVal) &&
16114         !Info.EvalStatus.HasSideEffects)
16115       ThisPtr = &ThisVal;
16116 
16117     // Ignore any side-effects from a failed evaluation. This is safe because
16118     // they can't interfere with any other argument evaluation.
16119     Info.EvalStatus.HasSideEffects = false;
16120   }
16121 
16122   CallRef Call = Info.CurrentCall->createCall(Callee);
16123   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
16124        I != E; ++I) {
16125     unsigned Idx = I - Args.begin();
16126     if (Idx >= Callee->getNumParams())
16127       break;
16128     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
16129     if ((*I)->isValueDependent() ||
16130         !EvaluateCallArg(PVD, *I, Call, Info) ||
16131         Info.EvalStatus.HasSideEffects) {
16132       // If evaluation fails, throw away the argument entirely.
16133       if (APValue *Slot = Info.getParamSlot(Call, PVD))
16134         *Slot = APValue();
16135     }
16136 
16137     // Ignore any side-effects from a failed evaluation. This is safe because
16138     // they can't interfere with any other argument evaluation.
16139     Info.EvalStatus.HasSideEffects = false;
16140   }
16141 
16142   // Parameter cleanups happen in the caller and are not part of this
16143   // evaluation.
16144   Info.discardCleanups();
16145   Info.EvalStatus.HasSideEffects = false;
16146 
16147   // Build fake call to Callee.
16148   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
16149   // FIXME: Missing ExprWithCleanups in enable_if conditions?
16150   FullExpressionRAII Scope(Info);
16151   return Evaluate(Value, Info, this) && Scope.destroy() &&
16152          !Info.EvalStatus.HasSideEffects;
16153 }
16154 
isPotentialConstantExpr(const FunctionDecl * FD,SmallVectorImpl<PartialDiagnosticAt> & Diags)16155 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
16156                                    SmallVectorImpl<
16157                                      PartialDiagnosticAt> &Diags) {
16158   // FIXME: It would be useful to check constexpr function templates, but at the
16159   // moment the constant expression evaluator cannot cope with the non-rigorous
16160   // ASTs which we build for dependent expressions.
16161   if (FD->isDependentContext())
16162     return true;
16163 
16164   llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
16165     std::string Name;
16166     llvm::raw_string_ostream OS(Name);
16167     FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(),
16168                              /*Qualified=*/true);
16169     return Name;
16170   });
16171 
16172   Expr::EvalStatus Status;
16173   Status.Diag = &Diags;
16174 
16175   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
16176   Info.InConstantContext = true;
16177   Info.CheckingPotentialConstantExpression = true;
16178 
16179   // The constexpr VM attempts to compile all methods to bytecode here.
16180   if (Info.EnableNewConstInterp) {
16181     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
16182     return Diags.empty();
16183   }
16184 
16185   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
16186   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
16187 
16188   // Fabricate an arbitrary expression on the stack and pretend that it
16189   // is a temporary being used as the 'this' pointer.
16190   LValue This;
16191   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
16192   This.set({&VIE, Info.CurrentCall->Index});
16193 
16194   ArrayRef<const Expr*> Args;
16195 
16196   APValue Scratch;
16197   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
16198     // Evaluate the call as a constant initializer, to allow the construction
16199     // of objects of non-literal types.
16200     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
16201     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
16202   } else {
16203     SourceLocation Loc = FD->getLocation();
16204     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
16205                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
16206   }
16207 
16208   return Diags.empty();
16209 }
16210 
isPotentialConstantExprUnevaluated(Expr * E,const FunctionDecl * FD,SmallVectorImpl<PartialDiagnosticAt> & Diags)16211 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
16212                                               const FunctionDecl *FD,
16213                                               SmallVectorImpl<
16214                                                 PartialDiagnosticAt> &Diags) {
16215   assert(!E->isValueDependent() &&
16216          "Expression evaluator can't be called on a dependent expression.");
16217 
16218   Expr::EvalStatus Status;
16219   Status.Diag = &Diags;
16220 
16221   EvalInfo Info(FD->getASTContext(), Status,
16222                 EvalInfo::EM_ConstantExpressionUnevaluated);
16223   Info.InConstantContext = true;
16224   Info.CheckingPotentialConstantExpression = true;
16225 
16226   // Fabricate a call stack frame to give the arguments a plausible cover story.
16227   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
16228 
16229   APValue ResultScratch;
16230   Evaluate(ResultScratch, Info, E);
16231   return Diags.empty();
16232 }
16233 
tryEvaluateObjectSize(uint64_t & Result,ASTContext & Ctx,unsigned Type) const16234 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
16235                                  unsigned Type) const {
16236   if (!getType()->isPointerType())
16237     return false;
16238 
16239   Expr::EvalStatus Status;
16240   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16241   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
16242 }
16243 
EvaluateBuiltinStrLen(const Expr * E,uint64_t & Result,EvalInfo & Info)16244 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
16245                                   EvalInfo &Info) {
16246   if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
16247     return false;
16248 
16249   LValue String;
16250 
16251   if (!EvaluatePointer(E, String, Info))
16252     return false;
16253 
16254   QualType CharTy = E->getType()->getPointeeType();
16255 
16256   // Fast path: if it's a string literal, search the string value.
16257   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
16258           String.getLValueBase().dyn_cast<const Expr *>())) {
16259     StringRef Str = S->getBytes();
16260     int64_t Off = String.Offset.getQuantity();
16261     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
16262         S->getCharByteWidth() == 1 &&
16263         // FIXME: Add fast-path for wchar_t too.
16264         Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
16265       Str = Str.substr(Off);
16266 
16267       StringRef::size_type Pos = Str.find(0);
16268       if (Pos != StringRef::npos)
16269         Str = Str.substr(0, Pos);
16270 
16271       Result = Str.size();
16272       return true;
16273     }
16274 
16275     // Fall through to slow path.
16276   }
16277 
16278   // Slow path: scan the bytes of the string looking for the terminating 0.
16279   for (uint64_t Strlen = 0; /**/; ++Strlen) {
16280     APValue Char;
16281     if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
16282         !Char.isInt())
16283       return false;
16284     if (!Char.getInt()) {
16285       Result = Strlen;
16286       return true;
16287     }
16288     if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
16289       return false;
16290   }
16291 }
16292 
tryEvaluateStrLen(uint64_t & Result,ASTContext & Ctx) const16293 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
16294   Expr::EvalStatus Status;
16295   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16296   return EvaluateBuiltinStrLen(this, Result, Info);
16297 }
16298