1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Expr constant evaluator.
10 //
11 // Constant expression evaluation produces four main results:
12 //
13 //  * A success/failure flag indicating whether constant folding was successful.
14 //    This is the 'bool' return value used by most of the code in this file. A
15 //    'false' return value indicates that constant folding has failed, and any
16 //    appropriate diagnostic has already been produced.
17 //
18 //  * An evaluated result, valid only if constant folding has not failed.
19 //
20 //  * A flag indicating if evaluation encountered (unevaluated) side-effects.
21 //    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22 //    where it is possible to determine the evaluated result regardless.
23 //
24 //  * A set of notes indicating why the evaluation was not a constant expression
25 //    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26 //    too, why the expression could not be folded.
27 //
28 // If we are checking for a potential constant expression, failure to constant
29 // fold a potential constant sub-expression will be indicated by a 'false'
30 // return value (the expression could not be folded) and no diagnostic (the
31 // expression is not necessarily non-constant).
32 //
33 //===----------------------------------------------------------------------===//
34 
35 #include "Interp/Context.h"
36 #include "Interp/Frame.h"
37 #include "Interp/State.h"
38 #include "clang/AST/APValue.h"
39 #include "clang/AST/ASTContext.h"
40 #include "clang/AST/ASTDiagnostic.h"
41 #include "clang/AST/ASTLambda.h"
42 #include "clang/AST/Attr.h"
43 #include "clang/AST/CXXInheritance.h"
44 #include "clang/AST/CharUnits.h"
45 #include "clang/AST/CurrentSourceLocExprScope.h"
46 #include "clang/AST/Expr.h"
47 #include "clang/AST/OSLog.h"
48 #include "clang/AST/OptionalDiagnostic.h"
49 #include "clang/AST/RecordLayout.h"
50 #include "clang/AST/StmtVisitor.h"
51 #include "clang/AST/TypeLoc.h"
52 #include "clang/Basic/Builtins.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "llvm/ADT/APFixedPoint.h"
55 #include "llvm/ADT/Optional.h"
56 #include "llvm/ADT/SmallBitVector.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/SaveAndRestore.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include <cstring>
61 #include <functional>
62 
63 #define DEBUG_TYPE "exprconstant"
64 
65 using namespace clang;
66 using llvm::APFixedPoint;
67 using llvm::APInt;
68 using llvm::APSInt;
69 using llvm::APFloat;
70 using llvm::FixedPointSemantics;
71 using llvm::Optional;
72 
73 namespace {
74   struct LValue;
75   class CallStackFrame;
76   class EvalInfo;
77 
78   using SourceLocExprScopeGuard =
79       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
80 
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.
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.
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.
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.
103   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
104     if (E->isRValue())
105       return E->getType();
106     return Ctx.getLValueReferenceType(E->getType());
107   }
108 
109   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
110   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
111     const FunctionDecl *Callee = CE->getDirectCallee();
112     return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
113   }
114 
115   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
116   /// This will look through a single cast.
117   ///
118   /// Returns null if we couldn't unwrap a function with alloc_size.
119   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
120     if (!E->getType()->isPointerType())
121       return nullptr;
122 
123     E = E->IgnoreParens();
124     // If we're doing a variable assignment from e.g. malloc(N), there will
125     // probably be a cast of some kind. In exotic cases, we might also see a
126     // top-level ExprWithCleanups. Ignore them either way.
127     if (const auto *FE = dyn_cast<FullExpr>(E))
128       E = FE->getSubExpr()->IgnoreParens();
129 
130     if (const auto *Cast = dyn_cast<CastExpr>(E))
131       E = Cast->getSubExpr()->IgnoreParens();
132 
133     if (const auto *CE = dyn_cast<CallExpr>(E))
134       return getAllocSizeAttr(CE) ? CE : nullptr;
135     return nullptr;
136   }
137 
138   /// Determines whether or not the given Base contains a call to a function
139   /// with the alloc_size attribute.
140   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
141     const auto *E = Base.dyn_cast<const Expr *>();
142     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
143   }
144 
145   /// Determines whether the given kind of constant expression is only ever
146   /// used for name mangling. If so, it's permitted to reference things that we
147   /// can't generate code for (in particular, dllimported functions).
148   static bool isForManglingOnly(ConstantExprKind Kind) {
149     switch (Kind) {
150     case ConstantExprKind::Normal:
151     case ConstantExprKind::ClassTemplateArgument:
152     case ConstantExprKind::ImmediateInvocation:
153       // Note that non-type template arguments of class type are emitted as
154       // template parameter objects.
155       return false;
156 
157     case ConstantExprKind::NonClassTemplateArgument:
158       return true;
159     }
160     llvm_unreachable("unknown ConstantExprKind");
161   }
162 
163   static bool isTemplateArgument(ConstantExprKind Kind) {
164     switch (Kind) {
165     case ConstantExprKind::Normal:
166     case ConstantExprKind::ImmediateInvocation:
167       return false;
168 
169     case ConstantExprKind::ClassTemplateArgument:
170     case ConstantExprKind::NonClassTemplateArgument:
171       return true;
172     }
173     llvm_unreachable("unknown ConstantExprKind");
174   }
175 
176   /// The bound to claim that an array of unknown bound has.
177   /// The value in MostDerivedArraySize is undefined in this case. So, set it
178   /// to an arbitrary value that's likely to loudly break things if it's used.
179   static const uint64_t AssumedSizeForUnsizedArray =
180       std::numeric_limits<uint64_t>::max() / 2;
181 
182   /// Determines if an LValue with the given LValueBase will have an unsized
183   /// array in its designator.
184   /// Find the path length and type of the most-derived subobject in the given
185   /// path, and find the size of the containing array, if any.
186   static unsigned
187   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
188                            ArrayRef<APValue::LValuePathEntry> Path,
189                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
190                            bool &FirstEntryIsUnsizedArray) {
191     // This only accepts LValueBases from APValues, and APValues don't support
192     // arrays that lack size info.
193     assert(!isBaseAnAllocSizeCall(Base) &&
194            "Unsized arrays shouldn't appear here");
195     unsigned MostDerivedLength = 0;
196     Type = getType(Base);
197 
198     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
199       if (Type->isArrayType()) {
200         const ArrayType *AT = Ctx.getAsArrayType(Type);
201         Type = AT->getElementType();
202         MostDerivedLength = I + 1;
203         IsArray = true;
204 
205         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
206           ArraySize = CAT->getSize().getZExtValue();
207         } else {
208           assert(I == 0 && "unexpected unsized array designator");
209           FirstEntryIsUnsizedArray = true;
210           ArraySize = AssumedSizeForUnsizedArray;
211         }
212       } else if (Type->isAnyComplexType()) {
213         const ComplexType *CT = Type->castAs<ComplexType>();
214         Type = CT->getElementType();
215         ArraySize = 2;
216         MostDerivedLength = I + 1;
217         IsArray = true;
218       } else if (const FieldDecl *FD = getAsField(Path[I])) {
219         Type = FD->getType();
220         ArraySize = 0;
221         MostDerivedLength = I + 1;
222         IsArray = false;
223       } else {
224         // Path[I] describes a base class.
225         ArraySize = 0;
226         IsArray = false;
227       }
228     }
229     return MostDerivedLength;
230   }
231 
232   /// A path from a glvalue to a subobject of that glvalue.
233   struct SubobjectDesignator {
234     /// True if the subobject was named in a manner not supported by C++11. Such
235     /// lvalues can still be folded, but they are not core constant expressions
236     /// and we cannot perform lvalue-to-rvalue conversions on them.
237     unsigned Invalid : 1;
238 
239     /// Is this a pointer one past the end of an object?
240     unsigned IsOnePastTheEnd : 1;
241 
242     /// Indicator of whether the first entry is an unsized array.
243     unsigned FirstEntryIsAnUnsizedArray : 1;
244 
245     /// Indicator of whether the most-derived object is an array element.
246     unsigned MostDerivedIsArrayElement : 1;
247 
248     /// The length of the path to the most-derived object of which this is a
249     /// subobject.
250     unsigned MostDerivedPathLength : 28;
251 
252     /// The size of the array of which the most-derived object is an element.
253     /// This will always be 0 if the most-derived object is not an array
254     /// element. 0 is not an indicator of whether or not the most-derived object
255     /// is an array, however, because 0-length arrays are allowed.
256     ///
257     /// If the current array is an unsized array, the value of this is
258     /// undefined.
259     uint64_t MostDerivedArraySize;
260 
261     /// The type of the most derived object referred to by this address.
262     QualType MostDerivedType;
263 
264     typedef APValue::LValuePathEntry PathEntry;
265 
266     /// The entries on the path from the glvalue to the designated subobject.
267     SmallVector<PathEntry, 8> Entries;
268 
269     SubobjectDesignator() : Invalid(true) {}
270 
271     explicit SubobjectDesignator(QualType T)
272         : Invalid(false), IsOnePastTheEnd(false),
273           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
274           MostDerivedPathLength(0), MostDerivedArraySize(0),
275           MostDerivedType(T) {}
276 
277     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
278         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
279           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
280           MostDerivedPathLength(0), MostDerivedArraySize(0) {
281       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
282       if (!Invalid) {
283         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
284         ArrayRef<PathEntry> VEntries = V.getLValuePath();
285         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
286         if (V.getLValueBase()) {
287           bool IsArray = false;
288           bool FirstIsUnsizedArray = false;
289           MostDerivedPathLength = findMostDerivedSubobject(
290               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
291               MostDerivedType, IsArray, FirstIsUnsizedArray);
292           MostDerivedIsArrayElement = IsArray;
293           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
294         }
295       }
296     }
297 
298     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
299                   unsigned NewLength) {
300       if (Invalid)
301         return;
302 
303       assert(Base && "cannot truncate path for null pointer");
304       assert(NewLength <= Entries.size() && "not a truncation");
305 
306       if (NewLength == Entries.size())
307         return;
308       Entries.resize(NewLength);
309 
310       bool IsArray = false;
311       bool FirstIsUnsizedArray = false;
312       MostDerivedPathLength = findMostDerivedSubobject(
313           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
314           FirstIsUnsizedArray);
315       MostDerivedIsArrayElement = IsArray;
316       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
317     }
318 
319     void setInvalid() {
320       Invalid = true;
321       Entries.clear();
322     }
323 
324     /// Determine whether the most derived subobject is an array without a
325     /// known bound.
326     bool isMostDerivedAnUnsizedArray() const {
327       assert(!Invalid && "Calling this makes no sense on invalid designators");
328       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
329     }
330 
331     /// Determine what the most derived array's size is. Results in an assertion
332     /// failure if the most derived array lacks a size.
333     uint64_t getMostDerivedArraySize() const {
334       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
335       return MostDerivedArraySize;
336     }
337 
338     /// Determine whether this is a one-past-the-end pointer.
339     bool isOnePastTheEnd() const {
340       assert(!Invalid);
341       if (IsOnePastTheEnd)
342         return true;
343       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
344           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
345               MostDerivedArraySize)
346         return true;
347       return false;
348     }
349 
350     /// Get the range of valid index adjustments in the form
351     ///   {maximum value that can be subtracted from this pointer,
352     ///    maximum value that can be added to this pointer}
353     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
354       if (Invalid || isMostDerivedAnUnsizedArray())
355         return {0, 0};
356 
357       // [expr.add]p4: For the purposes of these operators, a pointer to a
358       // nonarray object behaves the same as a pointer to the first element of
359       // an array of length one with the type of the object as its element type.
360       bool IsArray = MostDerivedPathLength == Entries.size() &&
361                      MostDerivedIsArrayElement;
362       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
363                                     : (uint64_t)IsOnePastTheEnd;
364       uint64_t ArraySize =
365           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
366       return {ArrayIndex, ArraySize - ArrayIndex};
367     }
368 
369     /// Check that this refers to a valid subobject.
370     bool isValidSubobject() const {
371       if (Invalid)
372         return false;
373       return !isOnePastTheEnd();
374     }
375     /// Check that this refers to a valid subobject, and if not, produce a
376     /// relevant diagnostic and set the designator as invalid.
377     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
378 
379     /// Get the type of the designated object.
380     QualType getType(ASTContext &Ctx) const {
381       assert(!Invalid && "invalid designator has no subobject type");
382       return MostDerivedPathLength == Entries.size()
383                  ? MostDerivedType
384                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
385     }
386 
387     /// Update this designator to refer to the first element within this array.
388     void addArrayUnchecked(const ConstantArrayType *CAT) {
389       Entries.push_back(PathEntry::ArrayIndex(0));
390 
391       // This is a most-derived object.
392       MostDerivedType = CAT->getElementType();
393       MostDerivedIsArrayElement = true;
394       MostDerivedArraySize = CAT->getSize().getZExtValue();
395       MostDerivedPathLength = Entries.size();
396     }
397     /// Update this designator to refer to the first element within the array of
398     /// elements of type T. This is an array of unknown size.
399     void addUnsizedArrayUnchecked(QualType ElemTy) {
400       Entries.push_back(PathEntry::ArrayIndex(0));
401 
402       MostDerivedType = ElemTy;
403       MostDerivedIsArrayElement = true;
404       // The value in MostDerivedArraySize is undefined in this case. So, set it
405       // to an arbitrary value that's likely to loudly break things if it's
406       // used.
407       MostDerivedArraySize = AssumedSizeForUnsizedArray;
408       MostDerivedPathLength = Entries.size();
409     }
410     /// Update this designator to refer to the given base or member of this
411     /// object.
412     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
413       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
414 
415       // If this isn't a base class, it's a new most-derived object.
416       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
417         MostDerivedType = FD->getType();
418         MostDerivedIsArrayElement = false;
419         MostDerivedArraySize = 0;
420         MostDerivedPathLength = Entries.size();
421       }
422     }
423     /// Update this designator to refer to the given complex component.
424     void addComplexUnchecked(QualType EltTy, bool Imag) {
425       Entries.push_back(PathEntry::ArrayIndex(Imag));
426 
427       // This is technically a most-derived object, though in practice this
428       // is unlikely to matter.
429       MostDerivedType = EltTy;
430       MostDerivedIsArrayElement = true;
431       MostDerivedArraySize = 2;
432       MostDerivedPathLength = Entries.size();
433     }
434     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
435     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
436                                    const APSInt &N);
437     /// Add N to the address of this subobject.
438     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
439       if (Invalid || !N) return;
440       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
441       if (isMostDerivedAnUnsizedArray()) {
442         diagnoseUnsizedArrayPointerArithmetic(Info, E);
443         // Can't verify -- trust that the user is doing the right thing (or if
444         // not, trust that the caller will catch the bad behavior).
445         // FIXME: Should we reject if this overflows, at least?
446         Entries.back() = PathEntry::ArrayIndex(
447             Entries.back().getAsArrayIndex() + TruncatedN);
448         return;
449       }
450 
451       // [expr.add]p4: For the purposes of these operators, a pointer to a
452       // nonarray object behaves the same as a pointer to the first element of
453       // an array of length one with the type of the object as its element type.
454       bool IsArray = MostDerivedPathLength == Entries.size() &&
455                      MostDerivedIsArrayElement;
456       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
457                                     : (uint64_t)IsOnePastTheEnd;
458       uint64_t ArraySize =
459           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
460 
461       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
462         // Calculate the actual index in a wide enough type, so we can include
463         // it in the note.
464         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
465         (llvm::APInt&)N += ArrayIndex;
466         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
467         diagnosePointerArithmetic(Info, E, N);
468         setInvalid();
469         return;
470       }
471 
472       ArrayIndex += TruncatedN;
473       assert(ArrayIndex <= ArraySize &&
474              "bounds check succeeded for out-of-bounds index");
475 
476       if (IsArray)
477         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
478       else
479         IsOnePastTheEnd = (ArrayIndex != 0);
480     }
481   };
482 
483   /// A scope at the end of which an object can need to be destroyed.
484   enum class ScopeKind {
485     Block,
486     FullExpression,
487     Call
488   };
489 
490   /// A reference to a particular call and its arguments.
491   struct CallRef {
492     CallRef() : OrigCallee(), CallIndex(0), Version() {}
493     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
494         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
495 
496     explicit operator bool() const { return OrigCallee; }
497 
498     /// Get the parameter that the caller initialized, corresponding to the
499     /// given parameter in the callee.
500     const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
501       return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
502                         : PVD;
503     }
504 
505     /// The callee at the point where the arguments were evaluated. This might
506     /// be different from the actual callee (a different redeclaration, or a
507     /// virtual override), but this function's parameters are the ones that
508     /// appear in the parameter map.
509     const FunctionDecl *OrigCallee;
510     /// The call index of the frame that holds the argument values.
511     unsigned CallIndex;
512     /// The version of the parameters corresponding to this call.
513     unsigned Version;
514   };
515 
516   /// A stack frame in the constexpr call stack.
517   class CallStackFrame : public interp::Frame {
518   public:
519     EvalInfo &Info;
520 
521     /// Parent - The caller of this stack frame.
522     CallStackFrame *Caller;
523 
524     /// Callee - The function which was called.
525     const FunctionDecl *Callee;
526 
527     /// This - The binding for the this pointer in this call, if any.
528     const LValue *This;
529 
530     /// Information on how to find the arguments to this call. Our arguments
531     /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
532     /// key and this value as the version.
533     CallRef Arguments;
534 
535     /// Source location information about the default argument or default
536     /// initializer expression we're evaluating, if any.
537     CurrentSourceLocExprScope CurSourceLocExprScope;
538 
539     // Note that we intentionally use std::map here so that references to
540     // values are stable.
541     typedef std::pair<const void *, unsigned> MapKeyTy;
542     typedef std::map<MapKeyTy, APValue> MapTy;
543     /// Temporaries - Temporary lvalues materialized within this stack frame.
544     MapTy Temporaries;
545 
546     /// CallLoc - The location of the call expression for this call.
547     SourceLocation CallLoc;
548 
549     /// Index - The call index of this call.
550     unsigned Index;
551 
552     /// The stack of integers for tracking version numbers for temporaries.
553     SmallVector<unsigned, 2> TempVersionStack = {1};
554     unsigned CurTempVersion = TempVersionStack.back();
555 
556     unsigned getTempVersion() const { return TempVersionStack.back(); }
557 
558     void pushTempVersion() {
559       TempVersionStack.push_back(++CurTempVersion);
560     }
561 
562     void popTempVersion() {
563       TempVersionStack.pop_back();
564     }
565 
566     CallRef createCall(const FunctionDecl *Callee) {
567       return {Callee, Index, ++CurTempVersion};
568     }
569 
570     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
571     // on the overall stack usage of deeply-recursing constexpr evaluations.
572     // (We should cache this map rather than recomputing it repeatedly.)
573     // But let's try this and see how it goes; we can look into caching the map
574     // as a later change.
575 
576     /// LambdaCaptureFields - Mapping from captured variables/this to
577     /// corresponding data members in the closure class.
578     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
579     FieldDecl *LambdaThisCaptureField;
580 
581     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
582                    const FunctionDecl *Callee, const LValue *This,
583                    CallRef Arguments);
584     ~CallStackFrame();
585 
586     // Return the temporary for Key whose version number is Version.
587     APValue *getTemporary(const void *Key, unsigned Version) {
588       MapKeyTy KV(Key, Version);
589       auto LB = Temporaries.lower_bound(KV);
590       if (LB != Temporaries.end() && LB->first == KV)
591         return &LB->second;
592       // Pair (Key,Version) wasn't found in the map. Check that no elements
593       // in the map have 'Key' as their key.
594       assert((LB == Temporaries.end() || LB->first.first != Key) &&
595              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
596              "Element with key 'Key' found in map");
597       return nullptr;
598     }
599 
600     // Return the current temporary for Key in the map.
601     APValue *getCurrentTemporary(const void *Key) {
602       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
603       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
604         return &std::prev(UB)->second;
605       return nullptr;
606     }
607 
608     // Return the version number of the current temporary for Key.
609     unsigned getCurrentTemporaryVersion(const void *Key) const {
610       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
611       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
612         return std::prev(UB)->first.second;
613       return 0;
614     }
615 
616     /// Allocate storage for an object of type T in this stack frame.
617     /// Populates LV with a handle to the created object. Key identifies
618     /// the temporary within the stack frame, and must not be reused without
619     /// bumping the temporary version number.
620     template<typename KeyT>
621     APValue &createTemporary(const KeyT *Key, QualType T,
622                              ScopeKind Scope, LValue &LV);
623 
624     /// Allocate storage for a parameter of a function call made in this frame.
625     APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
626 
627     void describe(llvm::raw_ostream &OS) override;
628 
629     Frame *getCaller() const override { return Caller; }
630     SourceLocation getCallLocation() const override { return CallLoc; }
631     const FunctionDecl *getCallee() const override { return Callee; }
632 
633     bool isStdFunction() const {
634       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
635         if (DC->isStdNamespace())
636           return true;
637       return false;
638     }
639 
640   private:
641     APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
642                          ScopeKind Scope);
643   };
644 
645   /// Temporarily override 'this'.
646   class ThisOverrideRAII {
647   public:
648     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
649         : Frame(Frame), OldThis(Frame.This) {
650       if (Enable)
651         Frame.This = NewThis;
652     }
653     ~ThisOverrideRAII() {
654       Frame.This = OldThis;
655     }
656   private:
657     CallStackFrame &Frame;
658     const LValue *OldThis;
659   };
660 }
661 
662 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
663                               const LValue &This, QualType ThisType);
664 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
665                               APValue::LValueBase LVBase, APValue &Value,
666                               QualType T);
667 
668 namespace {
669   /// A cleanup, and a flag indicating whether it is lifetime-extended.
670   class Cleanup {
671     llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
672     APValue::LValueBase Base;
673     QualType T;
674 
675   public:
676     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
677             ScopeKind Scope)
678         : Value(Val, Scope), Base(Base), T(T) {}
679 
680     /// Determine whether this cleanup should be performed at the end of the
681     /// given kind of scope.
682     bool isDestroyedAtEndOf(ScopeKind K) const {
683       return (int)Value.getInt() >= (int)K;
684     }
685     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
686       if (RunDestructors) {
687         SourceLocation Loc;
688         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
689           Loc = VD->getLocation();
690         else if (const Expr *E = Base.dyn_cast<const Expr*>())
691           Loc = E->getExprLoc();
692         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
693       }
694       *Value.getPointer() = APValue();
695       return true;
696     }
697 
698     bool hasSideEffect() {
699       return T.isDestructedType();
700     }
701   };
702 
703   /// A reference to an object whose construction we are currently evaluating.
704   struct ObjectUnderConstruction {
705     APValue::LValueBase Base;
706     ArrayRef<APValue::LValuePathEntry> Path;
707     friend bool operator==(const ObjectUnderConstruction &LHS,
708                            const ObjectUnderConstruction &RHS) {
709       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
710     }
711     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
712       return llvm::hash_combine(Obj.Base, Obj.Path);
713     }
714   };
715   enum class ConstructionPhase {
716     None,
717     Bases,
718     AfterBases,
719     AfterFields,
720     Destroying,
721     DestroyingBases
722   };
723 }
724 
725 namespace llvm {
726 template<> struct DenseMapInfo<ObjectUnderConstruction> {
727   using Base = DenseMapInfo<APValue::LValueBase>;
728   static ObjectUnderConstruction getEmptyKey() {
729     return {Base::getEmptyKey(), {}}; }
730   static ObjectUnderConstruction getTombstoneKey() {
731     return {Base::getTombstoneKey(), {}};
732   }
733   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
734     return hash_value(Object);
735   }
736   static bool isEqual(const ObjectUnderConstruction &LHS,
737                       const ObjectUnderConstruction &RHS) {
738     return LHS == RHS;
739   }
740 };
741 }
742 
743 namespace {
744   /// A dynamically-allocated heap object.
745   struct DynAlloc {
746     /// The value of this heap-allocated object.
747     APValue Value;
748     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
749     /// or a CallExpr (the latter is for direct calls to operator new inside
750     /// std::allocator<T>::allocate).
751     const Expr *AllocExpr = nullptr;
752 
753     enum Kind {
754       New,
755       ArrayNew,
756       StdAllocator
757     };
758 
759     /// Get the kind of the allocation. This must match between allocation
760     /// and deallocation.
761     Kind getKind() const {
762       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
763         return NE->isArray() ? ArrayNew : New;
764       assert(isa<CallExpr>(AllocExpr));
765       return StdAllocator;
766     }
767   };
768 
769   struct DynAllocOrder {
770     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
771       return L.getIndex() < R.getIndex();
772     }
773   };
774 
775   /// EvalInfo - This is a private struct used by the evaluator to capture
776   /// information about a subexpression as it is folded.  It retains information
777   /// about the AST context, but also maintains information about the folded
778   /// expression.
779   ///
780   /// If an expression could be evaluated, it is still possible it is not a C
781   /// "integer constant expression" or constant expression.  If not, this struct
782   /// captures information about how and why not.
783   ///
784   /// One bit of information passed *into* the request for constant folding
785   /// indicates whether the subexpression is "evaluated" or not according to C
786   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
787   /// evaluate the expression regardless of what the RHS is, but C only allows
788   /// certain things in certain situations.
789   class EvalInfo : public interp::State {
790   public:
791     ASTContext &Ctx;
792 
793     /// EvalStatus - Contains information about the evaluation.
794     Expr::EvalStatus &EvalStatus;
795 
796     /// CurrentCall - The top of the constexpr call stack.
797     CallStackFrame *CurrentCall;
798 
799     /// CallStackDepth - The number of calls in the call stack right now.
800     unsigned CallStackDepth;
801 
802     /// NextCallIndex - The next call index to assign.
803     unsigned NextCallIndex;
804 
805     /// StepsLeft - The remaining number of evaluation steps we're permitted
806     /// to perform. This is essentially a limit for the number of statements
807     /// we will evaluate.
808     unsigned StepsLeft;
809 
810     /// Enable the experimental new constant interpreter. If an expression is
811     /// not supported by the interpreter, an error is triggered.
812     bool EnableNewConstInterp;
813 
814     /// BottomFrame - The frame in which evaluation started. This must be
815     /// initialized after CurrentCall and CallStackDepth.
816     CallStackFrame BottomFrame;
817 
818     /// A stack of values whose lifetimes end at the end of some surrounding
819     /// evaluation frame.
820     llvm::SmallVector<Cleanup, 16> CleanupStack;
821 
822     /// EvaluatingDecl - This is the declaration whose initializer is being
823     /// evaluated, if any.
824     APValue::LValueBase EvaluatingDecl;
825 
826     enum class EvaluatingDeclKind {
827       None,
828       /// We're evaluating the construction of EvaluatingDecl.
829       Ctor,
830       /// We're evaluating the destruction of EvaluatingDecl.
831       Dtor,
832     };
833     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
834 
835     /// EvaluatingDeclValue - This is the value being constructed for the
836     /// declaration whose initializer is being evaluated, if any.
837     APValue *EvaluatingDeclValue;
838 
839     /// Set of objects that are currently being constructed.
840     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
841         ObjectsUnderConstruction;
842 
843     /// Current heap allocations, along with the location where each was
844     /// allocated. We use std::map here because we need stable addresses
845     /// for the stored APValues.
846     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
847 
848     /// The number of heap allocations performed so far in this evaluation.
849     unsigned NumHeapAllocs = 0;
850 
851     struct EvaluatingConstructorRAII {
852       EvalInfo &EI;
853       ObjectUnderConstruction Object;
854       bool DidInsert;
855       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
856                                 bool HasBases)
857           : EI(EI), Object(Object) {
858         DidInsert =
859             EI.ObjectsUnderConstruction
860                 .insert({Object, HasBases ? ConstructionPhase::Bases
861                                           : ConstructionPhase::AfterBases})
862                 .second;
863       }
864       void finishedConstructingBases() {
865         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
866       }
867       void finishedConstructingFields() {
868         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
869       }
870       ~EvaluatingConstructorRAII() {
871         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
872       }
873     };
874 
875     struct EvaluatingDestructorRAII {
876       EvalInfo &EI;
877       ObjectUnderConstruction Object;
878       bool DidInsert;
879       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
880           : EI(EI), Object(Object) {
881         DidInsert = EI.ObjectsUnderConstruction
882                         .insert({Object, ConstructionPhase::Destroying})
883                         .second;
884       }
885       void startedDestroyingBases() {
886         EI.ObjectsUnderConstruction[Object] =
887             ConstructionPhase::DestroyingBases;
888       }
889       ~EvaluatingDestructorRAII() {
890         if (DidInsert)
891           EI.ObjectsUnderConstruction.erase(Object);
892       }
893     };
894 
895     ConstructionPhase
896     isEvaluatingCtorDtor(APValue::LValueBase Base,
897                          ArrayRef<APValue::LValuePathEntry> Path) {
898       return ObjectsUnderConstruction.lookup({Base, Path});
899     }
900 
901     /// If we're currently speculatively evaluating, the outermost call stack
902     /// depth at which we can mutate state, otherwise 0.
903     unsigned SpeculativeEvaluationDepth = 0;
904 
905     /// The current array initialization index, if we're performing array
906     /// initialization.
907     uint64_t ArrayInitIndex = -1;
908 
909     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
910     /// notes attached to it will also be stored, otherwise they will not be.
911     bool HasActiveDiagnostic;
912 
913     /// Have we emitted a diagnostic explaining why we couldn't constant
914     /// fold (not just why it's not strictly a constant expression)?
915     bool HasFoldFailureDiagnostic;
916 
917     /// Whether or not we're in a context where the front end requires a
918     /// constant value.
919     bool InConstantContext;
920 
921     /// Whether we're checking that an expression is a potential constant
922     /// expression. If so, do not fail on constructs that could become constant
923     /// later on (such as a use of an undefined global).
924     bool CheckingPotentialConstantExpression = false;
925 
926     /// Whether we're checking for an expression that has undefined behavior.
927     /// If so, we will produce warnings if we encounter an operation that is
928     /// always undefined.
929     bool CheckingForUndefinedBehavior = false;
930 
931     enum EvaluationMode {
932       /// Evaluate as a constant expression. Stop if we find that the expression
933       /// is not a constant expression.
934       EM_ConstantExpression,
935 
936       /// Evaluate as a constant expression. Stop if we find that the expression
937       /// is not a constant expression. Some expressions can be retried in the
938       /// optimizer if we don't constant fold them here, but in an unevaluated
939       /// context we try to fold them immediately since the optimizer never
940       /// gets a chance to look at it.
941       EM_ConstantExpressionUnevaluated,
942 
943       /// Fold the expression to a constant. Stop if we hit a side-effect that
944       /// we can't model.
945       EM_ConstantFold,
946 
947       /// Evaluate in any way we know how. Don't worry about side-effects that
948       /// can't be modeled.
949       EM_IgnoreSideEffects,
950     } EvalMode;
951 
952     /// Are we checking whether the expression is a potential constant
953     /// expression?
954     bool checkingPotentialConstantExpression() const override  {
955       return CheckingPotentialConstantExpression;
956     }
957 
958     /// Are we checking an expression for overflow?
959     // FIXME: We should check for any kind of undefined or suspicious behavior
960     // in such constructs, not just overflow.
961     bool checkingForUndefinedBehavior() const override {
962       return CheckingForUndefinedBehavior;
963     }
964 
965     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
966         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
967           CallStackDepth(0), NextCallIndex(1),
968           StepsLeft(C.getLangOpts().ConstexprStepLimit),
969           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
970           BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
971           EvaluatingDecl((const ValueDecl *)nullptr),
972           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
973           HasFoldFailureDiagnostic(false), InConstantContext(false),
974           EvalMode(Mode) {}
975 
976     ~EvalInfo() {
977       discardCleanups();
978     }
979 
980     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
981                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
982       EvaluatingDecl = Base;
983       IsEvaluatingDecl = EDK;
984       EvaluatingDeclValue = &Value;
985     }
986 
987     bool CheckCallLimit(SourceLocation Loc) {
988       // Don't perform any constexpr calls (other than the call we're checking)
989       // when checking a potential constant expression.
990       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
991         return false;
992       if (NextCallIndex == 0) {
993         // NextCallIndex has wrapped around.
994         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
995         return false;
996       }
997       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
998         return true;
999       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1000         << getLangOpts().ConstexprCallDepth;
1001       return false;
1002     }
1003 
1004     std::pair<CallStackFrame *, unsigned>
1005     getCallFrameAndDepth(unsigned CallIndex) {
1006       assert(CallIndex && "no call index in getCallFrameAndDepth");
1007       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1008       // be null in this loop.
1009       unsigned Depth = CallStackDepth;
1010       CallStackFrame *Frame = CurrentCall;
1011       while (Frame->Index > CallIndex) {
1012         Frame = Frame->Caller;
1013         --Depth;
1014       }
1015       if (Frame->Index == CallIndex)
1016         return {Frame, Depth};
1017       return {nullptr, 0};
1018     }
1019 
1020     bool nextStep(const Stmt *S) {
1021       if (!StepsLeft) {
1022         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1023         return false;
1024       }
1025       --StepsLeft;
1026       return true;
1027     }
1028 
1029     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1030 
1031     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1032       Optional<DynAlloc*> Result;
1033       auto It = HeapAllocs.find(DA);
1034       if (It != HeapAllocs.end())
1035         Result = &It->second;
1036       return Result;
1037     }
1038 
1039     /// Get the allocated storage for the given parameter of the given call.
1040     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1041       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1042       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1043                    : nullptr;
1044     }
1045 
1046     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1047     struct StdAllocatorCaller {
1048       unsigned FrameIndex;
1049       QualType ElemType;
1050       explicit operator bool() const { return FrameIndex != 0; };
1051     };
1052 
1053     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1054       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1055            Call = Call->Caller) {
1056         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1057         if (!MD)
1058           continue;
1059         const IdentifierInfo *FnII = MD->getIdentifier();
1060         if (!FnII || !FnII->isStr(FnName))
1061           continue;
1062 
1063         const auto *CTSD =
1064             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1065         if (!CTSD)
1066           continue;
1067 
1068         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1069         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1070         if (CTSD->isInStdNamespace() && ClassII &&
1071             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1072             TAL[0].getKind() == TemplateArgument::Type)
1073           return {Call->Index, TAL[0].getAsType()};
1074       }
1075 
1076       return {};
1077     }
1078 
1079     void performLifetimeExtension() {
1080       // Disable the cleanups for lifetime-extended temporaries.
1081       CleanupStack.erase(std::remove_if(CleanupStack.begin(),
1082                                         CleanupStack.end(),
1083                                         [](Cleanup &C) {
1084                                           return !C.isDestroyedAtEndOf(
1085                                               ScopeKind::FullExpression);
1086                                         }),
1087                          CleanupStack.end());
1088      }
1089 
1090     /// Throw away any remaining cleanups at the end of evaluation. If any
1091     /// cleanups would have had a side-effect, note that as an unmodeled
1092     /// side-effect and return false. Otherwise, return true.
1093     bool discardCleanups() {
1094       for (Cleanup &C : CleanupStack) {
1095         if (C.hasSideEffect() && !noteSideEffect()) {
1096           CleanupStack.clear();
1097           return false;
1098         }
1099       }
1100       CleanupStack.clear();
1101       return true;
1102     }
1103 
1104   private:
1105     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1106     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1107 
1108     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1109     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1110 
1111     void setFoldFailureDiagnostic(bool Flag) override {
1112       HasFoldFailureDiagnostic = Flag;
1113     }
1114 
1115     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1116 
1117     ASTContext &getCtx() const override { return Ctx; }
1118 
1119     // If we have a prior diagnostic, it will be noting that the expression
1120     // isn't a constant expression. This diagnostic is more important,
1121     // unless we require this evaluation to produce a constant expression.
1122     //
1123     // FIXME: We might want to show both diagnostics to the user in
1124     // EM_ConstantFold mode.
1125     bool hasPriorDiagnostic() override {
1126       if (!EvalStatus.Diag->empty()) {
1127         switch (EvalMode) {
1128         case EM_ConstantFold:
1129         case EM_IgnoreSideEffects:
1130           if (!HasFoldFailureDiagnostic)
1131             break;
1132           // We've already failed to fold something. Keep that diagnostic.
1133           LLVM_FALLTHROUGH;
1134         case EM_ConstantExpression:
1135         case EM_ConstantExpressionUnevaluated:
1136           setActiveDiagnostic(false);
1137           return true;
1138         }
1139       }
1140       return false;
1141     }
1142 
1143     unsigned getCallStackDepth() override { return CallStackDepth; }
1144 
1145   public:
1146     /// Should we continue evaluation after encountering a side-effect that we
1147     /// couldn't model?
1148     bool keepEvaluatingAfterSideEffect() {
1149       switch (EvalMode) {
1150       case EM_IgnoreSideEffects:
1151         return true;
1152 
1153       case EM_ConstantExpression:
1154       case EM_ConstantExpressionUnevaluated:
1155       case EM_ConstantFold:
1156         // By default, assume any side effect might be valid in some other
1157         // evaluation of this expression from a different context.
1158         return checkingPotentialConstantExpression() ||
1159                checkingForUndefinedBehavior();
1160       }
1161       llvm_unreachable("Missed EvalMode case");
1162     }
1163 
1164     /// Note that we have had a side-effect, and determine whether we should
1165     /// keep evaluating.
1166     bool noteSideEffect() {
1167       EvalStatus.HasSideEffects = true;
1168       return keepEvaluatingAfterSideEffect();
1169     }
1170 
1171     /// Should we continue evaluation after encountering undefined behavior?
1172     bool keepEvaluatingAfterUndefinedBehavior() {
1173       switch (EvalMode) {
1174       case EM_IgnoreSideEffects:
1175       case EM_ConstantFold:
1176         return true;
1177 
1178       case EM_ConstantExpression:
1179       case EM_ConstantExpressionUnevaluated:
1180         return checkingForUndefinedBehavior();
1181       }
1182       llvm_unreachable("Missed EvalMode case");
1183     }
1184 
1185     /// Note that we hit something that was technically undefined behavior, but
1186     /// that we can evaluate past it (such as signed overflow or floating-point
1187     /// division by zero.)
1188     bool noteUndefinedBehavior() override {
1189       EvalStatus.HasUndefinedBehavior = true;
1190       return keepEvaluatingAfterUndefinedBehavior();
1191     }
1192 
1193     /// Should we continue evaluation as much as possible after encountering a
1194     /// construct which can't be reduced to a value?
1195     bool keepEvaluatingAfterFailure() const override {
1196       if (!StepsLeft)
1197         return false;
1198 
1199       switch (EvalMode) {
1200       case EM_ConstantExpression:
1201       case EM_ConstantExpressionUnevaluated:
1202       case EM_ConstantFold:
1203       case EM_IgnoreSideEffects:
1204         return checkingPotentialConstantExpression() ||
1205                checkingForUndefinedBehavior();
1206       }
1207       llvm_unreachable("Missed EvalMode case");
1208     }
1209 
1210     /// Notes that we failed to evaluate an expression that other expressions
1211     /// directly depend on, and determine if we should keep evaluating. This
1212     /// should only be called if we actually intend to keep evaluating.
1213     ///
1214     /// Call noteSideEffect() instead if we may be able to ignore the value that
1215     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1216     ///
1217     /// (Foo(), 1)      // use noteSideEffect
1218     /// (Foo() || true) // use noteSideEffect
1219     /// Foo() + 1       // use noteFailure
1220     LLVM_NODISCARD bool noteFailure() {
1221       // Failure when evaluating some expression often means there is some
1222       // subexpression whose evaluation was skipped. Therefore, (because we
1223       // don't track whether we skipped an expression when unwinding after an
1224       // evaluation failure) every evaluation failure that bubbles up from a
1225       // subexpression implies that a side-effect has potentially happened. We
1226       // skip setting the HasSideEffects flag to true until we decide to
1227       // continue evaluating after that point, which happens here.
1228       bool KeepGoing = keepEvaluatingAfterFailure();
1229       EvalStatus.HasSideEffects |= KeepGoing;
1230       return KeepGoing;
1231     }
1232 
1233     class ArrayInitLoopIndex {
1234       EvalInfo &Info;
1235       uint64_t OuterIndex;
1236 
1237     public:
1238       ArrayInitLoopIndex(EvalInfo &Info)
1239           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1240         Info.ArrayInitIndex = 0;
1241       }
1242       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1243 
1244       operator uint64_t&() { return Info.ArrayInitIndex; }
1245     };
1246   };
1247 
1248   /// Object used to treat all foldable expressions as constant expressions.
1249   struct FoldConstant {
1250     EvalInfo &Info;
1251     bool Enabled;
1252     bool HadNoPriorDiags;
1253     EvalInfo::EvaluationMode OldMode;
1254 
1255     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1256       : Info(Info),
1257         Enabled(Enabled),
1258         HadNoPriorDiags(Info.EvalStatus.Diag &&
1259                         Info.EvalStatus.Diag->empty() &&
1260                         !Info.EvalStatus.HasSideEffects),
1261         OldMode(Info.EvalMode) {
1262       if (Enabled)
1263         Info.EvalMode = EvalInfo::EM_ConstantFold;
1264     }
1265     void keepDiagnostics() { Enabled = false; }
1266     ~FoldConstant() {
1267       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1268           !Info.EvalStatus.HasSideEffects)
1269         Info.EvalStatus.Diag->clear();
1270       Info.EvalMode = OldMode;
1271     }
1272   };
1273 
1274   /// RAII object used to set the current evaluation mode to ignore
1275   /// side-effects.
1276   struct IgnoreSideEffectsRAII {
1277     EvalInfo &Info;
1278     EvalInfo::EvaluationMode OldMode;
1279     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1280         : Info(Info), OldMode(Info.EvalMode) {
1281       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1282     }
1283 
1284     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1285   };
1286 
1287   /// RAII object used to optionally suppress diagnostics and side-effects from
1288   /// a speculative evaluation.
1289   class SpeculativeEvaluationRAII {
1290     EvalInfo *Info = nullptr;
1291     Expr::EvalStatus OldStatus;
1292     unsigned OldSpeculativeEvaluationDepth;
1293 
1294     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1295       Info = Other.Info;
1296       OldStatus = Other.OldStatus;
1297       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1298       Other.Info = nullptr;
1299     }
1300 
1301     void maybeRestoreState() {
1302       if (!Info)
1303         return;
1304 
1305       Info->EvalStatus = OldStatus;
1306       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1307     }
1308 
1309   public:
1310     SpeculativeEvaluationRAII() = default;
1311 
1312     SpeculativeEvaluationRAII(
1313         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1314         : Info(&Info), OldStatus(Info.EvalStatus),
1315           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1316       Info.EvalStatus.Diag = NewDiag;
1317       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1318     }
1319 
1320     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1321     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1322       moveFromAndCancel(std::move(Other));
1323     }
1324 
1325     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1326       maybeRestoreState();
1327       moveFromAndCancel(std::move(Other));
1328       return *this;
1329     }
1330 
1331     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1332   };
1333 
1334   /// RAII object wrapping a full-expression or block scope, and handling
1335   /// the ending of the lifetime of temporaries created within it.
1336   template<ScopeKind Kind>
1337   class ScopeRAII {
1338     EvalInfo &Info;
1339     unsigned OldStackSize;
1340   public:
1341     ScopeRAII(EvalInfo &Info)
1342         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1343       // Push a new temporary version. This is needed to distinguish between
1344       // temporaries created in different iterations of a loop.
1345       Info.CurrentCall->pushTempVersion();
1346     }
1347     bool destroy(bool RunDestructors = true) {
1348       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1349       OldStackSize = -1U;
1350       return OK;
1351     }
1352     ~ScopeRAII() {
1353       if (OldStackSize != -1U)
1354         destroy(false);
1355       // Body moved to a static method to encourage the compiler to inline away
1356       // instances of this class.
1357       Info.CurrentCall->popTempVersion();
1358     }
1359   private:
1360     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1361                         unsigned OldStackSize) {
1362       assert(OldStackSize <= Info.CleanupStack.size() &&
1363              "running cleanups out of order?");
1364 
1365       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1366       // for a full-expression scope.
1367       bool Success = true;
1368       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1369         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1370           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1371             Success = false;
1372             break;
1373           }
1374         }
1375       }
1376 
1377       // Compact any retained cleanups.
1378       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1379       if (Kind != ScopeKind::Block)
1380         NewEnd =
1381             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1382               return C.isDestroyedAtEndOf(Kind);
1383             });
1384       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1385       return Success;
1386     }
1387   };
1388   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1389   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1390   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1391 }
1392 
1393 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1394                                          CheckSubobjectKind CSK) {
1395   if (Invalid)
1396     return false;
1397   if (isOnePastTheEnd()) {
1398     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1399       << CSK;
1400     setInvalid();
1401     return false;
1402   }
1403   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1404   // must actually be at least one array element; even a VLA cannot have a
1405   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1406   return true;
1407 }
1408 
1409 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1410                                                                 const Expr *E) {
1411   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1412   // Do not set the designator as invalid: we can represent this situation,
1413   // and correct handling of __builtin_object_size requires us to do so.
1414 }
1415 
1416 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1417                                                     const Expr *E,
1418                                                     const APSInt &N) {
1419   // If we're complaining, we must be able to statically determine the size of
1420   // the most derived array.
1421   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1422     Info.CCEDiag(E, diag::note_constexpr_array_index)
1423       << N << /*array*/ 0
1424       << static_cast<unsigned>(getMostDerivedArraySize());
1425   else
1426     Info.CCEDiag(E, diag::note_constexpr_array_index)
1427       << N << /*non-array*/ 1;
1428   setInvalid();
1429 }
1430 
1431 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1432                                const FunctionDecl *Callee, const LValue *This,
1433                                CallRef Call)
1434     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1435       Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1436   Info.CurrentCall = this;
1437   ++Info.CallStackDepth;
1438 }
1439 
1440 CallStackFrame::~CallStackFrame() {
1441   assert(Info.CurrentCall == this && "calls retired out of order");
1442   --Info.CallStackDepth;
1443   Info.CurrentCall = Caller;
1444 }
1445 
1446 static bool isRead(AccessKinds AK) {
1447   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1448 }
1449 
1450 static bool isModification(AccessKinds AK) {
1451   switch (AK) {
1452   case AK_Read:
1453   case AK_ReadObjectRepresentation:
1454   case AK_MemberCall:
1455   case AK_DynamicCast:
1456   case AK_TypeId:
1457     return false;
1458   case AK_Assign:
1459   case AK_Increment:
1460   case AK_Decrement:
1461   case AK_Construct:
1462   case AK_Destroy:
1463     return true;
1464   }
1465   llvm_unreachable("unknown access kind");
1466 }
1467 
1468 static bool isAnyAccess(AccessKinds AK) {
1469   return isRead(AK) || isModification(AK);
1470 }
1471 
1472 /// Is this an access per the C++ definition?
1473 static bool isFormalAccess(AccessKinds AK) {
1474   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1475 }
1476 
1477 /// Is this kind of axcess valid on an indeterminate object value?
1478 static bool isValidIndeterminateAccess(AccessKinds AK) {
1479   switch (AK) {
1480   case AK_Read:
1481   case AK_Increment:
1482   case AK_Decrement:
1483     // These need the object's value.
1484     return false;
1485 
1486   case AK_ReadObjectRepresentation:
1487   case AK_Assign:
1488   case AK_Construct:
1489   case AK_Destroy:
1490     // Construction and destruction don't need the value.
1491     return true;
1492 
1493   case AK_MemberCall:
1494   case AK_DynamicCast:
1495   case AK_TypeId:
1496     // These aren't really meaningful on scalars.
1497     return true;
1498   }
1499   llvm_unreachable("unknown access kind");
1500 }
1501 
1502 namespace {
1503   struct ComplexValue {
1504   private:
1505     bool IsInt;
1506 
1507   public:
1508     APSInt IntReal, IntImag;
1509     APFloat FloatReal, FloatImag;
1510 
1511     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1512 
1513     void makeComplexFloat() { IsInt = false; }
1514     bool isComplexFloat() const { return !IsInt; }
1515     APFloat &getComplexFloatReal() { return FloatReal; }
1516     APFloat &getComplexFloatImag() { return FloatImag; }
1517 
1518     void makeComplexInt() { IsInt = true; }
1519     bool isComplexInt() const { return IsInt; }
1520     APSInt &getComplexIntReal() { return IntReal; }
1521     APSInt &getComplexIntImag() { return IntImag; }
1522 
1523     void moveInto(APValue &v) const {
1524       if (isComplexFloat())
1525         v = APValue(FloatReal, FloatImag);
1526       else
1527         v = APValue(IntReal, IntImag);
1528     }
1529     void setFrom(const APValue &v) {
1530       assert(v.isComplexFloat() || v.isComplexInt());
1531       if (v.isComplexFloat()) {
1532         makeComplexFloat();
1533         FloatReal = v.getComplexFloatReal();
1534         FloatImag = v.getComplexFloatImag();
1535       } else {
1536         makeComplexInt();
1537         IntReal = v.getComplexIntReal();
1538         IntImag = v.getComplexIntImag();
1539       }
1540     }
1541   };
1542 
1543   struct LValue {
1544     APValue::LValueBase Base;
1545     CharUnits Offset;
1546     SubobjectDesignator Designator;
1547     bool IsNullPtr : 1;
1548     bool InvalidBase : 1;
1549 
1550     const APValue::LValueBase getLValueBase() const { return Base; }
1551     CharUnits &getLValueOffset() { return Offset; }
1552     const CharUnits &getLValueOffset() const { return Offset; }
1553     SubobjectDesignator &getLValueDesignator() { return Designator; }
1554     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1555     bool isNullPointer() const { return IsNullPtr;}
1556 
1557     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1558     unsigned getLValueVersion() const { return Base.getVersion(); }
1559 
1560     void moveInto(APValue &V) const {
1561       if (Designator.Invalid)
1562         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1563       else {
1564         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1565         V = APValue(Base, Offset, Designator.Entries,
1566                     Designator.IsOnePastTheEnd, IsNullPtr);
1567       }
1568     }
1569     void setFrom(ASTContext &Ctx, const APValue &V) {
1570       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1571       Base = V.getLValueBase();
1572       Offset = V.getLValueOffset();
1573       InvalidBase = false;
1574       Designator = SubobjectDesignator(Ctx, V);
1575       IsNullPtr = V.isNullPointer();
1576     }
1577 
1578     void set(APValue::LValueBase B, bool BInvalid = false) {
1579 #ifndef NDEBUG
1580       // We only allow a few types of invalid bases. Enforce that here.
1581       if (BInvalid) {
1582         const auto *E = B.get<const Expr *>();
1583         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1584                "Unexpected type of invalid base");
1585       }
1586 #endif
1587 
1588       Base = B;
1589       Offset = CharUnits::fromQuantity(0);
1590       InvalidBase = BInvalid;
1591       Designator = SubobjectDesignator(getType(B));
1592       IsNullPtr = false;
1593     }
1594 
1595     void setNull(ASTContext &Ctx, QualType PointerTy) {
1596       Base = (const ValueDecl *)nullptr;
1597       Offset =
1598           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1599       InvalidBase = false;
1600       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1601       IsNullPtr = true;
1602     }
1603 
1604     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1605       set(B, true);
1606     }
1607 
1608     std::string toString(ASTContext &Ctx, QualType T) const {
1609       APValue Printable;
1610       moveInto(Printable);
1611       return Printable.getAsString(Ctx, T);
1612     }
1613 
1614   private:
1615     // Check that this LValue is not based on a null pointer. If it is, produce
1616     // a diagnostic and mark the designator as invalid.
1617     template <typename GenDiagType>
1618     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1619       if (Designator.Invalid)
1620         return false;
1621       if (IsNullPtr) {
1622         GenDiag();
1623         Designator.setInvalid();
1624         return false;
1625       }
1626       return true;
1627     }
1628 
1629   public:
1630     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1631                           CheckSubobjectKind CSK) {
1632       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1633         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1634       });
1635     }
1636 
1637     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1638                                        AccessKinds AK) {
1639       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1640         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1641       });
1642     }
1643 
1644     // Check this LValue refers to an object. If not, set the designator to be
1645     // invalid and emit a diagnostic.
1646     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1647       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1648              Designator.checkSubobject(Info, E, CSK);
1649     }
1650 
1651     void addDecl(EvalInfo &Info, const Expr *E,
1652                  const Decl *D, bool Virtual = false) {
1653       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1654         Designator.addDeclUnchecked(D, Virtual);
1655     }
1656     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1657       if (!Designator.Entries.empty()) {
1658         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1659         Designator.setInvalid();
1660         return;
1661       }
1662       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1663         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1664         Designator.FirstEntryIsAnUnsizedArray = true;
1665         Designator.addUnsizedArrayUnchecked(ElemTy);
1666       }
1667     }
1668     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1669       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1670         Designator.addArrayUnchecked(CAT);
1671     }
1672     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1673       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1674         Designator.addComplexUnchecked(EltTy, Imag);
1675     }
1676     void clearIsNullPointer() {
1677       IsNullPtr = false;
1678     }
1679     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1680                               const APSInt &Index, CharUnits ElementSize) {
1681       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1682       // but we're not required to diagnose it and it's valid in C++.)
1683       if (!Index)
1684         return;
1685 
1686       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1687       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1688       // offsets.
1689       uint64_t Offset64 = Offset.getQuantity();
1690       uint64_t ElemSize64 = ElementSize.getQuantity();
1691       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1692       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1693 
1694       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1695         Designator.adjustIndex(Info, E, Index);
1696       clearIsNullPointer();
1697     }
1698     void adjustOffset(CharUnits N) {
1699       Offset += N;
1700       if (N.getQuantity())
1701         clearIsNullPointer();
1702     }
1703   };
1704 
1705   struct MemberPtr {
1706     MemberPtr() {}
1707     explicit MemberPtr(const ValueDecl *Decl) :
1708       DeclAndIsDerivedMember(Decl, false), Path() {}
1709 
1710     /// The member or (direct or indirect) field referred to by this member
1711     /// pointer, or 0 if this is a null member pointer.
1712     const ValueDecl *getDecl() const {
1713       return DeclAndIsDerivedMember.getPointer();
1714     }
1715     /// Is this actually a member of some type derived from the relevant class?
1716     bool isDerivedMember() const {
1717       return DeclAndIsDerivedMember.getInt();
1718     }
1719     /// Get the class which the declaration actually lives in.
1720     const CXXRecordDecl *getContainingRecord() const {
1721       return cast<CXXRecordDecl>(
1722           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1723     }
1724 
1725     void moveInto(APValue &V) const {
1726       V = APValue(getDecl(), isDerivedMember(), Path);
1727     }
1728     void setFrom(const APValue &V) {
1729       assert(V.isMemberPointer());
1730       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1731       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1732       Path.clear();
1733       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1734       Path.insert(Path.end(), P.begin(), P.end());
1735     }
1736 
1737     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1738     /// whether the member is a member of some class derived from the class type
1739     /// of the member pointer.
1740     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1741     /// Path - The path of base/derived classes from the member declaration's
1742     /// class (exclusive) to the class type of the member pointer (inclusive).
1743     SmallVector<const CXXRecordDecl*, 4> Path;
1744 
1745     /// Perform a cast towards the class of the Decl (either up or down the
1746     /// hierarchy).
1747     bool castBack(const CXXRecordDecl *Class) {
1748       assert(!Path.empty());
1749       const CXXRecordDecl *Expected;
1750       if (Path.size() >= 2)
1751         Expected = Path[Path.size() - 2];
1752       else
1753         Expected = getContainingRecord();
1754       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1755         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1756         // if B does not contain the original member and is not a base or
1757         // derived class of the class containing the original member, the result
1758         // of the cast is undefined.
1759         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1760         // (D::*). We consider that to be a language defect.
1761         return false;
1762       }
1763       Path.pop_back();
1764       return true;
1765     }
1766     /// Perform a base-to-derived member pointer cast.
1767     bool castToDerived(const CXXRecordDecl *Derived) {
1768       if (!getDecl())
1769         return true;
1770       if (!isDerivedMember()) {
1771         Path.push_back(Derived);
1772         return true;
1773       }
1774       if (!castBack(Derived))
1775         return false;
1776       if (Path.empty())
1777         DeclAndIsDerivedMember.setInt(false);
1778       return true;
1779     }
1780     /// Perform a derived-to-base member pointer cast.
1781     bool castToBase(const CXXRecordDecl *Base) {
1782       if (!getDecl())
1783         return true;
1784       if (Path.empty())
1785         DeclAndIsDerivedMember.setInt(true);
1786       if (isDerivedMember()) {
1787         Path.push_back(Base);
1788         return true;
1789       }
1790       return castBack(Base);
1791     }
1792   };
1793 
1794   /// Compare two member pointers, which are assumed to be of the same type.
1795   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1796     if (!LHS.getDecl() || !RHS.getDecl())
1797       return !LHS.getDecl() && !RHS.getDecl();
1798     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1799       return false;
1800     return LHS.Path == RHS.Path;
1801   }
1802 }
1803 
1804 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1805 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1806                             const LValue &This, const Expr *E,
1807                             bool AllowNonLiteralTypes = false);
1808 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1809                            bool InvalidBaseOK = false);
1810 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1811                             bool InvalidBaseOK = false);
1812 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1813                                   EvalInfo &Info);
1814 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1815 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1816 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1817                                     EvalInfo &Info);
1818 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1819 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1820 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1821                            EvalInfo &Info);
1822 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1823 
1824 /// Evaluate an integer or fixed point expression into an APResult.
1825 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1826                                         EvalInfo &Info);
1827 
1828 /// Evaluate only a fixed point expression into an APResult.
1829 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1830                                EvalInfo &Info);
1831 
1832 //===----------------------------------------------------------------------===//
1833 // Misc utilities
1834 //===----------------------------------------------------------------------===//
1835 
1836 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1837 /// preserving its value (by extending by up to one bit as needed).
1838 static void negateAsSigned(APSInt &Int) {
1839   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1840     Int = Int.extend(Int.getBitWidth() + 1);
1841     Int.setIsSigned(true);
1842   }
1843   Int = -Int;
1844 }
1845 
1846 template<typename KeyT>
1847 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1848                                          ScopeKind Scope, LValue &LV) {
1849   unsigned Version = getTempVersion();
1850   APValue::LValueBase Base(Key, Index, Version);
1851   LV.set(Base);
1852   return createLocal(Base, Key, T, Scope);
1853 }
1854 
1855 /// Allocate storage for a parameter of a function call made in this frame.
1856 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1857                                      LValue &LV) {
1858   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1859   APValue::LValueBase Base(PVD, Index, Args.Version);
1860   LV.set(Base);
1861   // We always destroy parameters at the end of the call, even if we'd allow
1862   // them to live to the end of the full-expression at runtime, in order to
1863   // give portable results and match other compilers.
1864   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1865 }
1866 
1867 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1868                                      QualType T, ScopeKind Scope) {
1869   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1870   unsigned Version = Base.getVersion();
1871   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1872   assert(Result.isAbsent() && "local created multiple times");
1873 
1874   // If we're creating a local immediately in the operand of a speculative
1875   // evaluation, don't register a cleanup to be run outside the speculative
1876   // evaluation context, since we won't actually be able to initialize this
1877   // object.
1878   if (Index <= Info.SpeculativeEvaluationDepth) {
1879     if (T.isDestructedType())
1880       Info.noteSideEffect();
1881   } else {
1882     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1883   }
1884   return Result;
1885 }
1886 
1887 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1888   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1889     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1890     return nullptr;
1891   }
1892 
1893   DynamicAllocLValue DA(NumHeapAllocs++);
1894   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1895   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1896                                    std::forward_as_tuple(DA), std::tuple<>());
1897   assert(Result.second && "reused a heap alloc index?");
1898   Result.first->second.AllocExpr = E;
1899   return &Result.first->second.Value;
1900 }
1901 
1902 /// Produce a string describing the given constexpr call.
1903 void CallStackFrame::describe(raw_ostream &Out) {
1904   unsigned ArgIndex = 0;
1905   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1906                       !isa<CXXConstructorDecl>(Callee) &&
1907                       cast<CXXMethodDecl>(Callee)->isInstance();
1908 
1909   if (!IsMemberCall)
1910     Out << *Callee << '(';
1911 
1912   if (This && IsMemberCall) {
1913     APValue Val;
1914     This->moveInto(Val);
1915     Val.printPretty(Out, Info.Ctx,
1916                     This->Designator.MostDerivedType);
1917     // FIXME: Add parens around Val if needed.
1918     Out << "->" << *Callee << '(';
1919     IsMemberCall = false;
1920   }
1921 
1922   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1923        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1924     if (ArgIndex > (unsigned)IsMemberCall)
1925       Out << ", ";
1926 
1927     const ParmVarDecl *Param = *I;
1928     APValue *V = Info.getParamSlot(Arguments, Param);
1929     if (V)
1930       V->printPretty(Out, Info.Ctx, Param->getType());
1931     else
1932       Out << "<...>";
1933 
1934     if (ArgIndex == 0 && IsMemberCall)
1935       Out << "->" << *Callee << '(';
1936   }
1937 
1938   Out << ')';
1939 }
1940 
1941 /// Evaluate an expression to see if it had side-effects, and discard its
1942 /// result.
1943 /// \return \c true if the caller should keep evaluating.
1944 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1945   assert(!E->isValueDependent());
1946   APValue Scratch;
1947   if (!Evaluate(Scratch, Info, E))
1948     // We don't need the value, but we might have skipped a side effect here.
1949     return Info.noteSideEffect();
1950   return true;
1951 }
1952 
1953 /// Should this call expression be treated as a string literal?
1954 static bool IsStringLiteralCall(const CallExpr *E) {
1955   unsigned Builtin = E->getBuiltinCallee();
1956   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1957           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1958 }
1959 
1960 static bool IsGlobalLValue(APValue::LValueBase B) {
1961   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1962   // constant expression of pointer type that evaluates to...
1963 
1964   // ... a null pointer value, or a prvalue core constant expression of type
1965   // std::nullptr_t.
1966   if (!B) return true;
1967 
1968   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1969     // ... the address of an object with static storage duration,
1970     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1971       return VD->hasGlobalStorage();
1972     if (isa<TemplateParamObjectDecl>(D))
1973       return true;
1974     // ... the address of a function,
1975     // ... the address of a GUID [MS extension],
1976     return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D);
1977   }
1978 
1979   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1980     return true;
1981 
1982   const Expr *E = B.get<const Expr*>();
1983   switch (E->getStmtClass()) {
1984   default:
1985     return false;
1986   case Expr::CompoundLiteralExprClass: {
1987     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1988     return CLE->isFileScope() && CLE->isLValue();
1989   }
1990   case Expr::MaterializeTemporaryExprClass:
1991     // A materialized temporary might have been lifetime-extended to static
1992     // storage duration.
1993     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1994   // A string literal has static storage duration.
1995   case Expr::StringLiteralClass:
1996   case Expr::PredefinedExprClass:
1997   case Expr::ObjCStringLiteralClass:
1998   case Expr::ObjCEncodeExprClass:
1999     return true;
2000   case Expr::ObjCBoxedExprClass:
2001     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2002   case Expr::CallExprClass:
2003     return IsStringLiteralCall(cast<CallExpr>(E));
2004   // For GCC compatibility, &&label has static storage duration.
2005   case Expr::AddrLabelExprClass:
2006     return true;
2007   // A Block literal expression may be used as the initialization value for
2008   // Block variables at global or local static scope.
2009   case Expr::BlockExprClass:
2010     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2011   case Expr::ImplicitValueInitExprClass:
2012     // FIXME:
2013     // We can never form an lvalue with an implicit value initialization as its
2014     // base through expression evaluation, so these only appear in one case: the
2015     // implicit variable declaration we invent when checking whether a constexpr
2016     // constructor can produce a constant expression. We must assume that such
2017     // an expression might be a global lvalue.
2018     return true;
2019   }
2020 }
2021 
2022 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2023   return LVal.Base.dyn_cast<const ValueDecl*>();
2024 }
2025 
2026 static bool IsLiteralLValue(const LValue &Value) {
2027   if (Value.getLValueCallIndex())
2028     return false;
2029   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2030   return E && !isa<MaterializeTemporaryExpr>(E);
2031 }
2032 
2033 static bool IsWeakLValue(const LValue &Value) {
2034   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2035   return Decl && Decl->isWeak();
2036 }
2037 
2038 static bool isZeroSized(const LValue &Value) {
2039   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2040   if (Decl && isa<VarDecl>(Decl)) {
2041     QualType Ty = Decl->getType();
2042     if (Ty->isArrayType())
2043       return Ty->isIncompleteType() ||
2044              Decl->getASTContext().getTypeSize(Ty) == 0;
2045   }
2046   return false;
2047 }
2048 
2049 static bool HasSameBase(const LValue &A, const LValue &B) {
2050   if (!A.getLValueBase())
2051     return !B.getLValueBase();
2052   if (!B.getLValueBase())
2053     return false;
2054 
2055   if (A.getLValueBase().getOpaqueValue() !=
2056       B.getLValueBase().getOpaqueValue())
2057     return false;
2058 
2059   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2060          A.getLValueVersion() == B.getLValueVersion();
2061 }
2062 
2063 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2064   assert(Base && "no location for a null lvalue");
2065   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2066 
2067   // For a parameter, find the corresponding call stack frame (if it still
2068   // exists), and point at the parameter of the function definition we actually
2069   // invoked.
2070   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2071     unsigned Idx = PVD->getFunctionScopeIndex();
2072     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2073       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2074           F->Arguments.Version == Base.getVersion() && F->Callee &&
2075           Idx < F->Callee->getNumParams()) {
2076         VD = F->Callee->getParamDecl(Idx);
2077         break;
2078       }
2079     }
2080   }
2081 
2082   if (VD)
2083     Info.Note(VD->getLocation(), diag::note_declared_at);
2084   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2085     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2086   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2087     // FIXME: Produce a note for dangling pointers too.
2088     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2089       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2090                 diag::note_constexpr_dynamic_alloc_here);
2091   }
2092   // We have no information to show for a typeid(T) object.
2093 }
2094 
2095 enum class CheckEvaluationResultKind {
2096   ConstantExpression,
2097   FullyInitialized,
2098 };
2099 
2100 /// Materialized temporaries that we've already checked to determine if they're
2101 /// initializsed by a constant expression.
2102 using CheckedTemporaries =
2103     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2104 
2105 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2106                                   EvalInfo &Info, SourceLocation DiagLoc,
2107                                   QualType Type, const APValue &Value,
2108                                   ConstantExprKind Kind,
2109                                   SourceLocation SubobjectLoc,
2110                                   CheckedTemporaries &CheckedTemps);
2111 
2112 /// Check that this reference or pointer core constant expression is a valid
2113 /// value for an address or reference constant expression. Return true if we
2114 /// can fold this expression, whether or not it's a constant expression.
2115 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2116                                           QualType Type, const LValue &LVal,
2117                                           ConstantExprKind Kind,
2118                                           CheckedTemporaries &CheckedTemps) {
2119   bool IsReferenceType = Type->isReferenceType();
2120 
2121   APValue::LValueBase Base = LVal.getLValueBase();
2122   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2123 
2124   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2125   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2126 
2127   // Additional restrictions apply in a template argument. We only enforce the
2128   // C++20 restrictions here; additional syntactic and semantic restrictions
2129   // are applied elsewhere.
2130   if (isTemplateArgument(Kind)) {
2131     int InvalidBaseKind = -1;
2132     StringRef Ident;
2133     if (Base.is<TypeInfoLValue>())
2134       InvalidBaseKind = 0;
2135     else if (isa_and_nonnull<StringLiteral>(BaseE))
2136       InvalidBaseKind = 1;
2137     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2138              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2139       InvalidBaseKind = 2;
2140     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2141       InvalidBaseKind = 3;
2142       Ident = PE->getIdentKindName();
2143     }
2144 
2145     if (InvalidBaseKind != -1) {
2146       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2147           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2148           << Ident;
2149       return false;
2150     }
2151   }
2152 
2153   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2154     if (FD->isConsteval()) {
2155       Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2156           << !Type->isAnyPointerType();
2157       Info.Note(FD->getLocation(), diag::note_declared_at);
2158       return false;
2159     }
2160   }
2161 
2162   // Check that the object is a global. Note that the fake 'this' object we
2163   // manufacture when checking potential constant expressions is conservatively
2164   // assumed to be global here.
2165   if (!IsGlobalLValue(Base)) {
2166     if (Info.getLangOpts().CPlusPlus11) {
2167       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2168       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2169         << IsReferenceType << !Designator.Entries.empty()
2170         << !!VD << VD;
2171 
2172       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2173       if (VarD && VarD->isConstexpr()) {
2174         // Non-static local constexpr variables have unintuitive semantics:
2175         //   constexpr int a = 1;
2176         //   constexpr const int *p = &a;
2177         // ... is invalid because the address of 'a' is not constant. Suggest
2178         // adding a 'static' in this case.
2179         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2180             << VarD
2181             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2182       } else {
2183         NoteLValueLocation(Info, Base);
2184       }
2185     } else {
2186       Info.FFDiag(Loc);
2187     }
2188     // Don't allow references to temporaries to escape.
2189     return false;
2190   }
2191   assert((Info.checkingPotentialConstantExpression() ||
2192           LVal.getLValueCallIndex() == 0) &&
2193          "have call index for global lvalue");
2194 
2195   if (Base.is<DynamicAllocLValue>()) {
2196     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2197         << IsReferenceType << !Designator.Entries.empty();
2198     NoteLValueLocation(Info, Base);
2199     return false;
2200   }
2201 
2202   if (BaseVD) {
2203     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2204       // Check if this is a thread-local variable.
2205       if (Var->getTLSKind())
2206         // FIXME: Diagnostic!
2207         return false;
2208 
2209       // A dllimport variable never acts like a constant, unless we're
2210       // evaluating a value for use only in name mangling.
2211       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2212         // FIXME: Diagnostic!
2213         return false;
2214     }
2215     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2216       // __declspec(dllimport) must be handled very carefully:
2217       // We must never initialize an expression with the thunk in C++.
2218       // Doing otherwise would allow the same id-expression to yield
2219       // different addresses for the same function in different translation
2220       // units.  However, this means that we must dynamically initialize the
2221       // expression with the contents of the import address table at runtime.
2222       //
2223       // The C language has no notion of ODR; furthermore, it has no notion of
2224       // dynamic initialization.  This means that we are permitted to
2225       // perform initialization with the address of the thunk.
2226       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2227           FD->hasAttr<DLLImportAttr>())
2228         // FIXME: Diagnostic!
2229         return false;
2230     }
2231   } else if (const auto *MTE =
2232                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2233     if (CheckedTemps.insert(MTE).second) {
2234       QualType TempType = getType(Base);
2235       if (TempType.isDestructedType()) {
2236         Info.FFDiag(MTE->getExprLoc(),
2237                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2238             << TempType;
2239         return false;
2240       }
2241 
2242       APValue *V = MTE->getOrCreateValue(false);
2243       assert(V && "evasluation result refers to uninitialised temporary");
2244       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2245                                  Info, MTE->getExprLoc(), TempType, *V,
2246                                  Kind, SourceLocation(), CheckedTemps))
2247         return false;
2248     }
2249   }
2250 
2251   // Allow address constant expressions to be past-the-end pointers. This is
2252   // an extension: the standard requires them to point to an object.
2253   if (!IsReferenceType)
2254     return true;
2255 
2256   // A reference constant expression must refer to an object.
2257   if (!Base) {
2258     // FIXME: diagnostic
2259     Info.CCEDiag(Loc);
2260     return true;
2261   }
2262 
2263   // Does this refer one past the end of some object?
2264   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2265     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2266       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2267     NoteLValueLocation(Info, Base);
2268   }
2269 
2270   return true;
2271 }
2272 
2273 /// Member pointers are constant expressions unless they point to a
2274 /// non-virtual dllimport member function.
2275 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2276                                                  SourceLocation Loc,
2277                                                  QualType Type,
2278                                                  const APValue &Value,
2279                                                  ConstantExprKind Kind) {
2280   const ValueDecl *Member = Value.getMemberPointerDecl();
2281   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2282   if (!FD)
2283     return true;
2284   if (FD->isConsteval()) {
2285     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2286     Info.Note(FD->getLocation(), diag::note_declared_at);
2287     return false;
2288   }
2289   return isForManglingOnly(Kind) || FD->isVirtual() ||
2290          !FD->hasAttr<DLLImportAttr>();
2291 }
2292 
2293 /// Check that this core constant expression is of literal type, and if not,
2294 /// produce an appropriate diagnostic.
2295 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2296                              const LValue *This = nullptr) {
2297   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2298     return true;
2299 
2300   // C++1y: A constant initializer for an object o [...] may also invoke
2301   // constexpr constructors for o and its subobjects even if those objects
2302   // are of non-literal class types.
2303   //
2304   // C++11 missed this detail for aggregates, so classes like this:
2305   //   struct foo_t { union { int i; volatile int j; } u; };
2306   // are not (obviously) initializable like so:
2307   //   __attribute__((__require_constant_initialization__))
2308   //   static const foo_t x = {{0}};
2309   // because "i" is a subobject with non-literal initialization (due to the
2310   // volatile member of the union). See:
2311   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2312   // Therefore, we use the C++1y behavior.
2313   if (This && Info.EvaluatingDecl == This->getLValueBase())
2314     return true;
2315 
2316   // Prvalue constant expressions must be of literal types.
2317   if (Info.getLangOpts().CPlusPlus11)
2318     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2319       << E->getType();
2320   else
2321     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2322   return false;
2323 }
2324 
2325 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2326                                   EvalInfo &Info, SourceLocation DiagLoc,
2327                                   QualType Type, const APValue &Value,
2328                                   ConstantExprKind Kind,
2329                                   SourceLocation SubobjectLoc,
2330                                   CheckedTemporaries &CheckedTemps) {
2331   if (!Value.hasValue()) {
2332     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2333       << true << Type;
2334     if (SubobjectLoc.isValid())
2335       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2336     return false;
2337   }
2338 
2339   // We allow _Atomic(T) to be initialized from anything that T can be
2340   // initialized from.
2341   if (const AtomicType *AT = Type->getAs<AtomicType>())
2342     Type = AT->getValueType();
2343 
2344   // Core issue 1454: For a literal constant expression of array or class type,
2345   // each subobject of its value shall have been initialized by a constant
2346   // expression.
2347   if (Value.isArray()) {
2348     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2349     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2350       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2351                                  Value.getArrayInitializedElt(I), Kind,
2352                                  SubobjectLoc, CheckedTemps))
2353         return false;
2354     }
2355     if (!Value.hasArrayFiller())
2356       return true;
2357     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2358                                  Value.getArrayFiller(), Kind, SubobjectLoc,
2359                                  CheckedTemps);
2360   }
2361   if (Value.isUnion() && Value.getUnionField()) {
2362     return CheckEvaluationResult(
2363         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2364         Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2365         CheckedTemps);
2366   }
2367   if (Value.isStruct()) {
2368     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2369     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2370       unsigned BaseIndex = 0;
2371       for (const CXXBaseSpecifier &BS : CD->bases()) {
2372         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2373                                    Value.getStructBase(BaseIndex), Kind,
2374                                    BS.getBeginLoc(), CheckedTemps))
2375           return false;
2376         ++BaseIndex;
2377       }
2378     }
2379     for (const auto *I : RD->fields()) {
2380       if (I->isUnnamedBitfield())
2381         continue;
2382 
2383       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2384                                  Value.getStructField(I->getFieldIndex()),
2385                                  Kind, I->getLocation(), CheckedTemps))
2386         return false;
2387     }
2388   }
2389 
2390   if (Value.isLValue() &&
2391       CERK == CheckEvaluationResultKind::ConstantExpression) {
2392     LValue LVal;
2393     LVal.setFrom(Info.Ctx, Value);
2394     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2395                                          CheckedTemps);
2396   }
2397 
2398   if (Value.isMemberPointer() &&
2399       CERK == CheckEvaluationResultKind::ConstantExpression)
2400     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2401 
2402   // Everything else is fine.
2403   return true;
2404 }
2405 
2406 /// Check that this core constant expression value is a valid value for a
2407 /// constant expression. If not, report an appropriate diagnostic. Does not
2408 /// check that the expression is of literal type.
2409 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2410                                     QualType Type, const APValue &Value,
2411                                     ConstantExprKind Kind) {
2412   // Nothing to check for a constant expression of type 'cv void'.
2413   if (Type->isVoidType())
2414     return true;
2415 
2416   CheckedTemporaries CheckedTemps;
2417   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2418                                Info, DiagLoc, Type, Value, Kind,
2419                                SourceLocation(), CheckedTemps);
2420 }
2421 
2422 /// Check that this evaluated value is fully-initialized and can be loaded by
2423 /// an lvalue-to-rvalue conversion.
2424 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2425                                   QualType Type, const APValue &Value) {
2426   CheckedTemporaries CheckedTemps;
2427   return CheckEvaluationResult(
2428       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2429       ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2430 }
2431 
2432 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2433 /// "the allocated storage is deallocated within the evaluation".
2434 static bool CheckMemoryLeaks(EvalInfo &Info) {
2435   if (!Info.HeapAllocs.empty()) {
2436     // We can still fold to a constant despite a compile-time memory leak,
2437     // so long as the heap allocation isn't referenced in the result (we check
2438     // that in CheckConstantExpression).
2439     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2440                  diag::note_constexpr_memory_leak)
2441         << unsigned(Info.HeapAllocs.size() - 1);
2442   }
2443   return true;
2444 }
2445 
2446 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2447   // A null base expression indicates a null pointer.  These are always
2448   // evaluatable, and they are false unless the offset is zero.
2449   if (!Value.getLValueBase()) {
2450     Result = !Value.getLValueOffset().isZero();
2451     return true;
2452   }
2453 
2454   // We have a non-null base.  These are generally known to be true, but if it's
2455   // a weak declaration it can be null at runtime.
2456   Result = true;
2457   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2458   return !Decl || !Decl->isWeak();
2459 }
2460 
2461 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2462   switch (Val.getKind()) {
2463   case APValue::None:
2464   case APValue::Indeterminate:
2465     return false;
2466   case APValue::Int:
2467     Result = Val.getInt().getBoolValue();
2468     return true;
2469   case APValue::FixedPoint:
2470     Result = Val.getFixedPoint().getBoolValue();
2471     return true;
2472   case APValue::Float:
2473     Result = !Val.getFloat().isZero();
2474     return true;
2475   case APValue::ComplexInt:
2476     Result = Val.getComplexIntReal().getBoolValue() ||
2477              Val.getComplexIntImag().getBoolValue();
2478     return true;
2479   case APValue::ComplexFloat:
2480     Result = !Val.getComplexFloatReal().isZero() ||
2481              !Val.getComplexFloatImag().isZero();
2482     return true;
2483   case APValue::LValue:
2484     return EvalPointerValueAsBool(Val, Result);
2485   case APValue::MemberPointer:
2486     Result = Val.getMemberPointerDecl();
2487     return true;
2488   case APValue::Vector:
2489   case APValue::Array:
2490   case APValue::Struct:
2491   case APValue::Union:
2492   case APValue::AddrLabelDiff:
2493     return false;
2494   }
2495 
2496   llvm_unreachable("unknown APValue kind");
2497 }
2498 
2499 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2500                                        EvalInfo &Info) {
2501   assert(!E->isValueDependent());
2502   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2503   APValue Val;
2504   if (!Evaluate(Val, Info, E))
2505     return false;
2506   return HandleConversionToBool(Val, Result);
2507 }
2508 
2509 template<typename T>
2510 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2511                            const T &SrcValue, QualType DestType) {
2512   Info.CCEDiag(E, diag::note_constexpr_overflow)
2513     << SrcValue << DestType;
2514   return Info.noteUndefinedBehavior();
2515 }
2516 
2517 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2518                                  QualType SrcType, const APFloat &Value,
2519                                  QualType DestType, APSInt &Result) {
2520   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2521   // Determine whether we are converting to unsigned or signed.
2522   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2523 
2524   Result = APSInt(DestWidth, !DestSigned);
2525   bool ignored;
2526   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2527       & APFloat::opInvalidOp)
2528     return HandleOverflow(Info, E, Value, DestType);
2529   return true;
2530 }
2531 
2532 /// Get rounding mode used for evaluation of the specified expression.
2533 /// \param[out] DynamicRM Is set to true is the requested rounding mode is
2534 ///                       dynamic.
2535 /// If rounding mode is unknown at compile time, still try to evaluate the
2536 /// expression. If the result is exact, it does not depend on rounding mode.
2537 /// So return "tonearest" mode instead of "dynamic".
2538 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
2539                                                 bool &DynamicRM) {
2540   llvm::RoundingMode RM =
2541       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2542   DynamicRM = (RM == llvm::RoundingMode::Dynamic);
2543   if (DynamicRM)
2544     RM = llvm::RoundingMode::NearestTiesToEven;
2545   return RM;
2546 }
2547 
2548 /// Check if the given evaluation result is allowed for constant evaluation.
2549 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2550                                      APFloat::opStatus St) {
2551   // In a constant context, assume that any dynamic rounding mode or FP
2552   // exception state matches the default floating-point environment.
2553   if (Info.InConstantContext)
2554     return true;
2555 
2556   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2557   if ((St & APFloat::opInexact) &&
2558       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2559     // Inexact result means that it depends on rounding mode. If the requested
2560     // mode is dynamic, the evaluation cannot be made in compile time.
2561     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2562     return false;
2563   }
2564 
2565   if ((St != APFloat::opOK) &&
2566       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2567        FPO.getFPExceptionMode() != LangOptions::FPE_Ignore ||
2568        FPO.getAllowFEnvAccess())) {
2569     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2570     return false;
2571   }
2572 
2573   if ((St & APFloat::opStatus::opInvalidOp) &&
2574       FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) {
2575     // There is no usefully definable result.
2576     Info.FFDiag(E);
2577     return false;
2578   }
2579 
2580   // FIXME: if:
2581   // - evaluation triggered other FP exception, and
2582   // - exception mode is not "ignore", and
2583   // - the expression being evaluated is not a part of global variable
2584   //   initializer,
2585   // the evaluation probably need to be rejected.
2586   return true;
2587 }
2588 
2589 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2590                                    QualType SrcType, QualType DestType,
2591                                    APFloat &Result) {
2592   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2593   bool DynamicRM;
2594   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2595   APFloat::opStatus St;
2596   APFloat Value = Result;
2597   bool ignored;
2598   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2599   return checkFloatingPointResult(Info, E, St);
2600 }
2601 
2602 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2603                                  QualType DestType, QualType SrcType,
2604                                  const APSInt &Value) {
2605   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2606   // Figure out if this is a truncate, extend or noop cast.
2607   // If the input is signed, do a sign extend, noop, or truncate.
2608   APSInt Result = Value.extOrTrunc(DestWidth);
2609   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2610   if (DestType->isBooleanType())
2611     Result = Value.getBoolValue();
2612   return Result;
2613 }
2614 
2615 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2616                                  const FPOptions FPO,
2617                                  QualType SrcType, const APSInt &Value,
2618                                  QualType DestType, APFloat &Result) {
2619   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2620   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2621        APFloat::rmNearestTiesToEven);
2622   if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
2623       FPO.isFPConstrained()) {
2624     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2625     return false;
2626   }
2627   return true;
2628 }
2629 
2630 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2631                                   APValue &Value, const FieldDecl *FD) {
2632   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2633 
2634   if (!Value.isInt()) {
2635     // Trying to store a pointer-cast-to-integer into a bitfield.
2636     // FIXME: In this case, we should provide the diagnostic for casting
2637     // a pointer to an integer.
2638     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2639     Info.FFDiag(E);
2640     return false;
2641   }
2642 
2643   APSInt &Int = Value.getInt();
2644   unsigned OldBitWidth = Int.getBitWidth();
2645   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2646   if (NewBitWidth < OldBitWidth)
2647     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2648   return true;
2649 }
2650 
2651 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2652                                   llvm::APInt &Res) {
2653   APValue SVal;
2654   if (!Evaluate(SVal, Info, E))
2655     return false;
2656   if (SVal.isInt()) {
2657     Res = SVal.getInt();
2658     return true;
2659   }
2660   if (SVal.isFloat()) {
2661     Res = SVal.getFloat().bitcastToAPInt();
2662     return true;
2663   }
2664   if (SVal.isVector()) {
2665     QualType VecTy = E->getType();
2666     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2667     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2668     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2669     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2670     Res = llvm::APInt::getNullValue(VecSize);
2671     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2672       APValue &Elt = SVal.getVectorElt(i);
2673       llvm::APInt EltAsInt;
2674       if (Elt.isInt()) {
2675         EltAsInt = Elt.getInt();
2676       } else if (Elt.isFloat()) {
2677         EltAsInt = Elt.getFloat().bitcastToAPInt();
2678       } else {
2679         // Don't try to handle vectors of anything other than int or float
2680         // (not sure if it's possible to hit this case).
2681         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2682         return false;
2683       }
2684       unsigned BaseEltSize = EltAsInt.getBitWidth();
2685       if (BigEndian)
2686         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2687       else
2688         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2689     }
2690     return true;
2691   }
2692   // Give up if the input isn't an int, float, or vector.  For example, we
2693   // reject "(v4i16)(intptr_t)&a".
2694   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2695   return false;
2696 }
2697 
2698 /// Perform the given integer operation, which is known to need at most BitWidth
2699 /// bits, and check for overflow in the original type (if that type was not an
2700 /// unsigned type).
2701 template<typename Operation>
2702 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2703                                  const APSInt &LHS, const APSInt &RHS,
2704                                  unsigned BitWidth, Operation Op,
2705                                  APSInt &Result) {
2706   if (LHS.isUnsigned()) {
2707     Result = Op(LHS, RHS);
2708     return true;
2709   }
2710 
2711   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2712   Result = Value.trunc(LHS.getBitWidth());
2713   if (Result.extend(BitWidth) != Value) {
2714     if (Info.checkingForUndefinedBehavior())
2715       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2716                                        diag::warn_integer_constant_overflow)
2717           << Result.toString(10) << E->getType();
2718     else
2719       return HandleOverflow(Info, E, Value, E->getType());
2720   }
2721   return true;
2722 }
2723 
2724 /// Perform the given binary integer operation.
2725 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2726                               BinaryOperatorKind Opcode, APSInt RHS,
2727                               APSInt &Result) {
2728   switch (Opcode) {
2729   default:
2730     Info.FFDiag(E);
2731     return false;
2732   case BO_Mul:
2733     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2734                                 std::multiplies<APSInt>(), Result);
2735   case BO_Add:
2736     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2737                                 std::plus<APSInt>(), Result);
2738   case BO_Sub:
2739     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2740                                 std::minus<APSInt>(), Result);
2741   case BO_And: Result = LHS & RHS; return true;
2742   case BO_Xor: Result = LHS ^ RHS; return true;
2743   case BO_Or:  Result = LHS | RHS; return true;
2744   case BO_Div:
2745   case BO_Rem:
2746     if (RHS == 0) {
2747       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2748       return false;
2749     }
2750     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2751     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2752     // this operation and gives the two's complement result.
2753     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2754         LHS.isSigned() && LHS.isMinSignedValue())
2755       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2756                             E->getType());
2757     return true;
2758   case BO_Shl: {
2759     if (Info.getLangOpts().OpenCL)
2760       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2761       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2762                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2763                     RHS.isUnsigned());
2764     else if (RHS.isSigned() && RHS.isNegative()) {
2765       // During constant-folding, a negative shift is an opposite shift. Such
2766       // a shift is not a constant expression.
2767       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2768       RHS = -RHS;
2769       goto shift_right;
2770     }
2771   shift_left:
2772     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2773     // the shifted type.
2774     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2775     if (SA != RHS) {
2776       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2777         << RHS << E->getType() << LHS.getBitWidth();
2778     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2779       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2780       // operand, and must not overflow the corresponding unsigned type.
2781       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2782       // E1 x 2^E2 module 2^N.
2783       if (LHS.isNegative())
2784         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2785       else if (LHS.countLeadingZeros() < SA)
2786         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2787     }
2788     Result = LHS << SA;
2789     return true;
2790   }
2791   case BO_Shr: {
2792     if (Info.getLangOpts().OpenCL)
2793       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2794       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2795                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2796                     RHS.isUnsigned());
2797     else if (RHS.isSigned() && RHS.isNegative()) {
2798       // During constant-folding, a negative shift is an opposite shift. Such a
2799       // shift is not a constant expression.
2800       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2801       RHS = -RHS;
2802       goto shift_left;
2803     }
2804   shift_right:
2805     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2806     // shifted type.
2807     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2808     if (SA != RHS)
2809       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2810         << RHS << E->getType() << LHS.getBitWidth();
2811     Result = LHS >> SA;
2812     return true;
2813   }
2814 
2815   case BO_LT: Result = LHS < RHS; return true;
2816   case BO_GT: Result = LHS > RHS; return true;
2817   case BO_LE: Result = LHS <= RHS; return true;
2818   case BO_GE: Result = LHS >= RHS; return true;
2819   case BO_EQ: Result = LHS == RHS; return true;
2820   case BO_NE: Result = LHS != RHS; return true;
2821   case BO_Cmp:
2822     llvm_unreachable("BO_Cmp should be handled elsewhere");
2823   }
2824 }
2825 
2826 /// Perform the given binary floating-point operation, in-place, on LHS.
2827 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2828                                   APFloat &LHS, BinaryOperatorKind Opcode,
2829                                   const APFloat &RHS) {
2830   bool DynamicRM;
2831   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2832   APFloat::opStatus St;
2833   switch (Opcode) {
2834   default:
2835     Info.FFDiag(E);
2836     return false;
2837   case BO_Mul:
2838     St = LHS.multiply(RHS, RM);
2839     break;
2840   case BO_Add:
2841     St = LHS.add(RHS, RM);
2842     break;
2843   case BO_Sub:
2844     St = LHS.subtract(RHS, RM);
2845     break;
2846   case BO_Div:
2847     // [expr.mul]p4:
2848     //   If the second operand of / or % is zero the behavior is undefined.
2849     if (RHS.isZero())
2850       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2851     St = LHS.divide(RHS, RM);
2852     break;
2853   }
2854 
2855   // [expr.pre]p4:
2856   //   If during the evaluation of an expression, the result is not
2857   //   mathematically defined [...], the behavior is undefined.
2858   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2859   if (LHS.isNaN()) {
2860     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2861     return Info.noteUndefinedBehavior();
2862   }
2863 
2864   return checkFloatingPointResult(Info, E, St);
2865 }
2866 
2867 static bool handleLogicalOpForVector(const APInt &LHSValue,
2868                                      BinaryOperatorKind Opcode,
2869                                      const APInt &RHSValue, APInt &Result) {
2870   bool LHS = (LHSValue != 0);
2871   bool RHS = (RHSValue != 0);
2872 
2873   if (Opcode == BO_LAnd)
2874     Result = LHS && RHS;
2875   else
2876     Result = LHS || RHS;
2877   return true;
2878 }
2879 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2880                                      BinaryOperatorKind Opcode,
2881                                      const APFloat &RHSValue, APInt &Result) {
2882   bool LHS = !LHSValue.isZero();
2883   bool RHS = !RHSValue.isZero();
2884 
2885   if (Opcode == BO_LAnd)
2886     Result = LHS && RHS;
2887   else
2888     Result = LHS || RHS;
2889   return true;
2890 }
2891 
2892 static bool handleLogicalOpForVector(const APValue &LHSValue,
2893                                      BinaryOperatorKind Opcode,
2894                                      const APValue &RHSValue, APInt &Result) {
2895   // The result is always an int type, however operands match the first.
2896   if (LHSValue.getKind() == APValue::Int)
2897     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2898                                     RHSValue.getInt(), Result);
2899   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2900   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2901                                   RHSValue.getFloat(), Result);
2902 }
2903 
2904 template <typename APTy>
2905 static bool
2906 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2907                                const APTy &RHSValue, APInt &Result) {
2908   switch (Opcode) {
2909   default:
2910     llvm_unreachable("unsupported binary operator");
2911   case BO_EQ:
2912     Result = (LHSValue == RHSValue);
2913     break;
2914   case BO_NE:
2915     Result = (LHSValue != RHSValue);
2916     break;
2917   case BO_LT:
2918     Result = (LHSValue < RHSValue);
2919     break;
2920   case BO_GT:
2921     Result = (LHSValue > RHSValue);
2922     break;
2923   case BO_LE:
2924     Result = (LHSValue <= RHSValue);
2925     break;
2926   case BO_GE:
2927     Result = (LHSValue >= RHSValue);
2928     break;
2929   }
2930 
2931   return true;
2932 }
2933 
2934 static bool handleCompareOpForVector(const APValue &LHSValue,
2935                                      BinaryOperatorKind Opcode,
2936                                      const APValue &RHSValue, APInt &Result) {
2937   // The result is always an int type, however operands match the first.
2938   if (LHSValue.getKind() == APValue::Int)
2939     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2940                                           RHSValue.getInt(), Result);
2941   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2942   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2943                                         RHSValue.getFloat(), Result);
2944 }
2945 
2946 // Perform binary operations for vector types, in place on the LHS.
2947 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2948                                     BinaryOperatorKind Opcode,
2949                                     APValue &LHSValue,
2950                                     const APValue &RHSValue) {
2951   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2952          "Operation not supported on vector types");
2953 
2954   const auto *VT = E->getType()->castAs<VectorType>();
2955   unsigned NumElements = VT->getNumElements();
2956   QualType EltTy = VT->getElementType();
2957 
2958   // In the cases (typically C as I've observed) where we aren't evaluating
2959   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2960   // just give up.
2961   if (!LHSValue.isVector()) {
2962     assert(LHSValue.isLValue() &&
2963            "A vector result that isn't a vector OR uncalculated LValue");
2964     Info.FFDiag(E);
2965     return false;
2966   }
2967 
2968   assert(LHSValue.getVectorLength() == NumElements &&
2969          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2970 
2971   SmallVector<APValue, 4> ResultElements;
2972 
2973   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2974     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2975     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2976 
2977     if (EltTy->isIntegerType()) {
2978       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2979                        EltTy->isUnsignedIntegerType()};
2980       bool Success = true;
2981 
2982       if (BinaryOperator::isLogicalOp(Opcode))
2983         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2984       else if (BinaryOperator::isComparisonOp(Opcode))
2985         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2986       else
2987         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2988                                     RHSElt.getInt(), EltResult);
2989 
2990       if (!Success) {
2991         Info.FFDiag(E);
2992         return false;
2993       }
2994       ResultElements.emplace_back(EltResult);
2995 
2996     } else if (EltTy->isFloatingType()) {
2997       assert(LHSElt.getKind() == APValue::Float &&
2998              RHSElt.getKind() == APValue::Float &&
2999              "Mismatched LHS/RHS/Result Type");
3000       APFloat LHSFloat = LHSElt.getFloat();
3001 
3002       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3003                                  RHSElt.getFloat())) {
3004         Info.FFDiag(E);
3005         return false;
3006       }
3007 
3008       ResultElements.emplace_back(LHSFloat);
3009     }
3010   }
3011 
3012   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3013   return true;
3014 }
3015 
3016 /// Cast an lvalue referring to a base subobject to a derived class, by
3017 /// truncating the lvalue's path to the given length.
3018 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3019                                const RecordDecl *TruncatedType,
3020                                unsigned TruncatedElements) {
3021   SubobjectDesignator &D = Result.Designator;
3022 
3023   // Check we actually point to a derived class object.
3024   if (TruncatedElements == D.Entries.size())
3025     return true;
3026   assert(TruncatedElements >= D.MostDerivedPathLength &&
3027          "not casting to a derived class");
3028   if (!Result.checkSubobject(Info, E, CSK_Derived))
3029     return false;
3030 
3031   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3032   const RecordDecl *RD = TruncatedType;
3033   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3034     if (RD->isInvalidDecl()) return false;
3035     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3036     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3037     if (isVirtualBaseClass(D.Entries[I]))
3038       Result.Offset -= Layout.getVBaseClassOffset(Base);
3039     else
3040       Result.Offset -= Layout.getBaseClassOffset(Base);
3041     RD = Base;
3042   }
3043   D.Entries.resize(TruncatedElements);
3044   return true;
3045 }
3046 
3047 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3048                                    const CXXRecordDecl *Derived,
3049                                    const CXXRecordDecl *Base,
3050                                    const ASTRecordLayout *RL = nullptr) {
3051   if (!RL) {
3052     if (Derived->isInvalidDecl()) return false;
3053     RL = &Info.Ctx.getASTRecordLayout(Derived);
3054   }
3055 
3056   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3057   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3058   return true;
3059 }
3060 
3061 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3062                              const CXXRecordDecl *DerivedDecl,
3063                              const CXXBaseSpecifier *Base) {
3064   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3065 
3066   if (!Base->isVirtual())
3067     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3068 
3069   SubobjectDesignator &D = Obj.Designator;
3070   if (D.Invalid)
3071     return false;
3072 
3073   // Extract most-derived object and corresponding type.
3074   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3075   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3076     return false;
3077 
3078   // Find the virtual base class.
3079   if (DerivedDecl->isInvalidDecl()) return false;
3080   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3081   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3082   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3083   return true;
3084 }
3085 
3086 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3087                                  QualType Type, LValue &Result) {
3088   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3089                                      PathE = E->path_end();
3090        PathI != PathE; ++PathI) {
3091     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3092                           *PathI))
3093       return false;
3094     Type = (*PathI)->getType();
3095   }
3096   return true;
3097 }
3098 
3099 /// Cast an lvalue referring to a derived class to a known base subobject.
3100 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3101                             const CXXRecordDecl *DerivedRD,
3102                             const CXXRecordDecl *BaseRD) {
3103   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3104                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3105   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3106     llvm_unreachable("Class must be derived from the passed in base class!");
3107 
3108   for (CXXBasePathElement &Elem : Paths.front())
3109     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3110       return false;
3111   return true;
3112 }
3113 
3114 /// Update LVal to refer to the given field, which must be a member of the type
3115 /// currently described by LVal.
3116 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3117                                const FieldDecl *FD,
3118                                const ASTRecordLayout *RL = nullptr) {
3119   if (!RL) {
3120     if (FD->getParent()->isInvalidDecl()) return false;
3121     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3122   }
3123 
3124   unsigned I = FD->getFieldIndex();
3125   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3126   LVal.addDecl(Info, E, FD);
3127   return true;
3128 }
3129 
3130 /// Update LVal to refer to the given indirect field.
3131 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3132                                        LValue &LVal,
3133                                        const IndirectFieldDecl *IFD) {
3134   for (const auto *C : IFD->chain())
3135     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3136       return false;
3137   return true;
3138 }
3139 
3140 /// Get the size of the given type in char units.
3141 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3142                          QualType Type, CharUnits &Size) {
3143   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3144   // extension.
3145   if (Type->isVoidType() || Type->isFunctionType()) {
3146     Size = CharUnits::One();
3147     return true;
3148   }
3149 
3150   if (Type->isDependentType()) {
3151     Info.FFDiag(Loc);
3152     return false;
3153   }
3154 
3155   if (!Type->isConstantSizeType()) {
3156     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3157     // FIXME: Better diagnostic.
3158     Info.FFDiag(Loc);
3159     return false;
3160   }
3161 
3162   Size = Info.Ctx.getTypeSizeInChars(Type);
3163   return true;
3164 }
3165 
3166 /// Update a pointer value to model pointer arithmetic.
3167 /// \param Info - Information about the ongoing evaluation.
3168 /// \param E - The expression being evaluated, for diagnostic purposes.
3169 /// \param LVal - The pointer value to be updated.
3170 /// \param EltTy - The pointee type represented by LVal.
3171 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3172 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3173                                         LValue &LVal, QualType EltTy,
3174                                         APSInt Adjustment) {
3175   CharUnits SizeOfPointee;
3176   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3177     return false;
3178 
3179   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3180   return true;
3181 }
3182 
3183 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3184                                         LValue &LVal, QualType EltTy,
3185                                         int64_t Adjustment) {
3186   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3187                                      APSInt::get(Adjustment));
3188 }
3189 
3190 /// Update an lvalue to refer to a component of a complex number.
3191 /// \param Info - Information about the ongoing evaluation.
3192 /// \param LVal - The lvalue to be updated.
3193 /// \param EltTy - The complex number's component type.
3194 /// \param Imag - False for the real component, true for the imaginary.
3195 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3196                                        LValue &LVal, QualType EltTy,
3197                                        bool Imag) {
3198   if (Imag) {
3199     CharUnits SizeOfComponent;
3200     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3201       return false;
3202     LVal.Offset += SizeOfComponent;
3203   }
3204   LVal.addComplex(Info, E, EltTy, Imag);
3205   return true;
3206 }
3207 
3208 /// Try to evaluate the initializer for a variable declaration.
3209 ///
3210 /// \param Info   Information about the ongoing evaluation.
3211 /// \param E      An expression to be used when printing diagnostics.
3212 /// \param VD     The variable whose initializer should be obtained.
3213 /// \param Version The version of the variable within the frame.
3214 /// \param Frame  The frame in which the variable was created. Must be null
3215 ///               if this variable is not local to the evaluation.
3216 /// \param Result Filled in with a pointer to the value of the variable.
3217 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3218                                 const VarDecl *VD, CallStackFrame *Frame,
3219                                 unsigned Version, APValue *&Result) {
3220   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3221 
3222   // If this is a local variable, dig out its value.
3223   if (Frame) {
3224     Result = Frame->getTemporary(VD, Version);
3225     if (Result)
3226       return true;
3227 
3228     if (!isa<ParmVarDecl>(VD)) {
3229       // Assume variables referenced within a lambda's call operator that were
3230       // not declared within the call operator are captures and during checking
3231       // of a potential constant expression, assume they are unknown constant
3232       // expressions.
3233       assert(isLambdaCallOperator(Frame->Callee) &&
3234              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3235              "missing value for local variable");
3236       if (Info.checkingPotentialConstantExpression())
3237         return false;
3238       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3239       // still reachable at all?
3240       Info.FFDiag(E->getBeginLoc(),
3241                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3242           << "captures not currently allowed";
3243       return false;
3244     }
3245   }
3246 
3247   // If we're currently evaluating the initializer of this declaration, use that
3248   // in-flight value.
3249   if (Info.EvaluatingDecl == Base) {
3250     Result = Info.EvaluatingDeclValue;
3251     return true;
3252   }
3253 
3254   if (isa<ParmVarDecl>(VD)) {
3255     // Assume parameters of a potential constant expression are usable in
3256     // constant expressions.
3257     if (!Info.checkingPotentialConstantExpression() ||
3258         !Info.CurrentCall->Callee ||
3259         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3260       if (Info.getLangOpts().CPlusPlus11) {
3261         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3262             << VD;
3263         NoteLValueLocation(Info, Base);
3264       } else {
3265         Info.FFDiag(E);
3266       }
3267     }
3268     return false;
3269   }
3270 
3271   // Dig out the initializer, and use the declaration which it's attached to.
3272   // FIXME: We should eventually check whether the variable has a reachable
3273   // initializing declaration.
3274   const Expr *Init = VD->getAnyInitializer(VD);
3275   if (!Init) {
3276     // Don't diagnose during potential constant expression checking; an
3277     // initializer might be added later.
3278     if (!Info.checkingPotentialConstantExpression()) {
3279       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3280         << VD;
3281       NoteLValueLocation(Info, Base);
3282     }
3283     return false;
3284   }
3285 
3286   if (Init->isValueDependent()) {
3287     // The DeclRefExpr is not value-dependent, but the variable it refers to
3288     // has a value-dependent initializer. This should only happen in
3289     // constant-folding cases, where the variable is not actually of a suitable
3290     // type for use in a constant expression (otherwise the DeclRefExpr would
3291     // have been value-dependent too), so diagnose that.
3292     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3293     if (!Info.checkingPotentialConstantExpression()) {
3294       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3295                          ? diag::note_constexpr_ltor_non_constexpr
3296                          : diag::note_constexpr_ltor_non_integral, 1)
3297           << VD << VD->getType();
3298       NoteLValueLocation(Info, Base);
3299     }
3300     return false;
3301   }
3302 
3303   // Check that we can fold the initializer. In C++, we will have already done
3304   // this in the cases where it matters for conformance.
3305   if (!VD->evaluateValue()) {
3306     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3307     NoteLValueLocation(Info, Base);
3308     return false;
3309   }
3310 
3311   // Check that the variable is actually usable in constant expressions. For a
3312   // const integral variable or a reference, we might have a non-constant
3313   // initializer that we can nonetheless evaluate the initializer for. Such
3314   // variables are not usable in constant expressions. In C++98, the
3315   // initializer also syntactically needs to be an ICE.
3316   //
3317   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3318   // expressions here; doing so would regress diagnostics for things like
3319   // reading from a volatile constexpr variable.
3320   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3321        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3322       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3323        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3324     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3325     NoteLValueLocation(Info, Base);
3326   }
3327 
3328   // Never use the initializer of a weak variable, not even for constant
3329   // folding. We can't be sure that this is the definition that will be used.
3330   if (VD->isWeak()) {
3331     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3332     NoteLValueLocation(Info, Base);
3333     return false;
3334   }
3335 
3336   Result = VD->getEvaluatedValue();
3337   return true;
3338 }
3339 
3340 /// Get the base index of the given base class within an APValue representing
3341 /// the given derived class.
3342 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3343                              const CXXRecordDecl *Base) {
3344   Base = Base->getCanonicalDecl();
3345   unsigned Index = 0;
3346   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3347          E = Derived->bases_end(); I != E; ++I, ++Index) {
3348     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3349       return Index;
3350   }
3351 
3352   llvm_unreachable("base class missing from derived class's bases list");
3353 }
3354 
3355 /// Extract the value of a character from a string literal.
3356 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3357                                             uint64_t Index) {
3358   assert(!isa<SourceLocExpr>(Lit) &&
3359          "SourceLocExpr should have already been converted to a StringLiteral");
3360 
3361   // FIXME: Support MakeStringConstant
3362   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3363     std::string Str;
3364     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3365     assert(Index <= Str.size() && "Index too large");
3366     return APSInt::getUnsigned(Str.c_str()[Index]);
3367   }
3368 
3369   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3370     Lit = PE->getFunctionName();
3371   const StringLiteral *S = cast<StringLiteral>(Lit);
3372   const ConstantArrayType *CAT =
3373       Info.Ctx.getAsConstantArrayType(S->getType());
3374   assert(CAT && "string literal isn't an array");
3375   QualType CharType = CAT->getElementType();
3376   assert(CharType->isIntegerType() && "unexpected character type");
3377 
3378   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3379                CharType->isUnsignedIntegerType());
3380   if (Index < S->getLength())
3381     Value = S->getCodeUnit(Index);
3382   return Value;
3383 }
3384 
3385 // Expand a string literal into an array of characters.
3386 //
3387 // FIXME: This is inefficient; we should probably introduce something similar
3388 // to the LLVM ConstantDataArray to make this cheaper.
3389 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3390                                 APValue &Result,
3391                                 QualType AllocType = QualType()) {
3392   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3393       AllocType.isNull() ? S->getType() : AllocType);
3394   assert(CAT && "string literal isn't an array");
3395   QualType CharType = CAT->getElementType();
3396   assert(CharType->isIntegerType() && "unexpected character type");
3397 
3398   unsigned Elts = CAT->getSize().getZExtValue();
3399   Result = APValue(APValue::UninitArray(),
3400                    std::min(S->getLength(), Elts), Elts);
3401   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3402                CharType->isUnsignedIntegerType());
3403   if (Result.hasArrayFiller())
3404     Result.getArrayFiller() = APValue(Value);
3405   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3406     Value = S->getCodeUnit(I);
3407     Result.getArrayInitializedElt(I) = APValue(Value);
3408   }
3409 }
3410 
3411 // Expand an array so that it has more than Index filled elements.
3412 static void expandArray(APValue &Array, unsigned Index) {
3413   unsigned Size = Array.getArraySize();
3414   assert(Index < Size);
3415 
3416   // Always at least double the number of elements for which we store a value.
3417   unsigned OldElts = Array.getArrayInitializedElts();
3418   unsigned NewElts = std::max(Index+1, OldElts * 2);
3419   NewElts = std::min(Size, std::max(NewElts, 8u));
3420 
3421   // Copy the data across.
3422   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3423   for (unsigned I = 0; I != OldElts; ++I)
3424     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3425   for (unsigned I = OldElts; I != NewElts; ++I)
3426     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3427   if (NewValue.hasArrayFiller())
3428     NewValue.getArrayFiller() = Array.getArrayFiller();
3429   Array.swap(NewValue);
3430 }
3431 
3432 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3433 /// conversion. If it's of class type, we may assume that the copy operation
3434 /// is trivial. Note that this is never true for a union type with fields
3435 /// (because the copy always "reads" the active member) and always true for
3436 /// a non-class type.
3437 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3438 static bool isReadByLvalueToRvalueConversion(QualType T) {
3439   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3440   return !RD || isReadByLvalueToRvalueConversion(RD);
3441 }
3442 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3443   // FIXME: A trivial copy of a union copies the object representation, even if
3444   // the union is empty.
3445   if (RD->isUnion())
3446     return !RD->field_empty();
3447   if (RD->isEmpty())
3448     return false;
3449 
3450   for (auto *Field : RD->fields())
3451     if (!Field->isUnnamedBitfield() &&
3452         isReadByLvalueToRvalueConversion(Field->getType()))
3453       return true;
3454 
3455   for (auto &BaseSpec : RD->bases())
3456     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3457       return true;
3458 
3459   return false;
3460 }
3461 
3462 /// Diagnose an attempt to read from any unreadable field within the specified
3463 /// type, which might be a class type.
3464 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3465                                   QualType T) {
3466   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3467   if (!RD)
3468     return false;
3469 
3470   if (!RD->hasMutableFields())
3471     return false;
3472 
3473   for (auto *Field : RD->fields()) {
3474     // If we're actually going to read this field in some way, then it can't
3475     // be mutable. If we're in a union, then assigning to a mutable field
3476     // (even an empty one) can change the active member, so that's not OK.
3477     // FIXME: Add core issue number for the union case.
3478     if (Field->isMutable() &&
3479         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3480       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3481       Info.Note(Field->getLocation(), diag::note_declared_at);
3482       return true;
3483     }
3484 
3485     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3486       return true;
3487   }
3488 
3489   for (auto &BaseSpec : RD->bases())
3490     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3491       return true;
3492 
3493   // All mutable fields were empty, and thus not actually read.
3494   return false;
3495 }
3496 
3497 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3498                                         APValue::LValueBase Base,
3499                                         bool MutableSubobject = false) {
3500   // A temporary or transient heap allocation we created.
3501   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3502     return true;
3503 
3504   switch (Info.IsEvaluatingDecl) {
3505   case EvalInfo::EvaluatingDeclKind::None:
3506     return false;
3507 
3508   case EvalInfo::EvaluatingDeclKind::Ctor:
3509     // The variable whose initializer we're evaluating.
3510     if (Info.EvaluatingDecl == Base)
3511       return true;
3512 
3513     // A temporary lifetime-extended by the variable whose initializer we're
3514     // evaluating.
3515     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3516       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3517         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3518     return false;
3519 
3520   case EvalInfo::EvaluatingDeclKind::Dtor:
3521     // C++2a [expr.const]p6:
3522     //   [during constant destruction] the lifetime of a and its non-mutable
3523     //   subobjects (but not its mutable subobjects) [are] considered to start
3524     //   within e.
3525     if (MutableSubobject || Base != Info.EvaluatingDecl)
3526       return false;
3527     // FIXME: We can meaningfully extend this to cover non-const objects, but
3528     // we will need special handling: we should be able to access only
3529     // subobjects of such objects that are themselves declared const.
3530     QualType T = getType(Base);
3531     return T.isConstQualified() || T->isReferenceType();
3532   }
3533 
3534   llvm_unreachable("unknown evaluating decl kind");
3535 }
3536 
3537 namespace {
3538 /// A handle to a complete object (an object that is not a subobject of
3539 /// another object).
3540 struct CompleteObject {
3541   /// The identity of the object.
3542   APValue::LValueBase Base;
3543   /// The value of the complete object.
3544   APValue *Value;
3545   /// The type of the complete object.
3546   QualType Type;
3547 
3548   CompleteObject() : Value(nullptr) {}
3549   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3550       : Base(Base), Value(Value), Type(Type) {}
3551 
3552   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3553     // If this isn't a "real" access (eg, if it's just accessing the type
3554     // info), allow it. We assume the type doesn't change dynamically for
3555     // subobjects of constexpr objects (even though we'd hit UB here if it
3556     // did). FIXME: Is this right?
3557     if (!isAnyAccess(AK))
3558       return true;
3559 
3560     // In C++14 onwards, it is permitted to read a mutable member whose
3561     // lifetime began within the evaluation.
3562     // FIXME: Should we also allow this in C++11?
3563     if (!Info.getLangOpts().CPlusPlus14)
3564       return false;
3565     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3566   }
3567 
3568   explicit operator bool() const { return !Type.isNull(); }
3569 };
3570 } // end anonymous namespace
3571 
3572 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3573                                  bool IsMutable = false) {
3574   // C++ [basic.type.qualifier]p1:
3575   // - A const object is an object of type const T or a non-mutable subobject
3576   //   of a const object.
3577   if (ObjType.isConstQualified() && !IsMutable)
3578     SubobjType.addConst();
3579   // - A volatile object is an object of type const T or a subobject of a
3580   //   volatile object.
3581   if (ObjType.isVolatileQualified())
3582     SubobjType.addVolatile();
3583   return SubobjType;
3584 }
3585 
3586 /// Find the designated sub-object of an rvalue.
3587 template<typename SubobjectHandler>
3588 typename SubobjectHandler::result_type
3589 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3590               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3591   if (Sub.Invalid)
3592     // A diagnostic will have already been produced.
3593     return handler.failed();
3594   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3595     if (Info.getLangOpts().CPlusPlus11)
3596       Info.FFDiag(E, Sub.isOnePastTheEnd()
3597                          ? diag::note_constexpr_access_past_end
3598                          : diag::note_constexpr_access_unsized_array)
3599           << handler.AccessKind;
3600     else
3601       Info.FFDiag(E);
3602     return handler.failed();
3603   }
3604 
3605   APValue *O = Obj.Value;
3606   QualType ObjType = Obj.Type;
3607   const FieldDecl *LastField = nullptr;
3608   const FieldDecl *VolatileField = nullptr;
3609 
3610   // Walk the designator's path to find the subobject.
3611   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3612     // Reading an indeterminate value is undefined, but assigning over one is OK.
3613     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3614         (O->isIndeterminate() &&
3615          !isValidIndeterminateAccess(handler.AccessKind))) {
3616       if (!Info.checkingPotentialConstantExpression())
3617         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3618             << handler.AccessKind << O->isIndeterminate();
3619       return handler.failed();
3620     }
3621 
3622     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3623     //    const and volatile semantics are not applied on an object under
3624     //    {con,de}struction.
3625     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3626         ObjType->isRecordType() &&
3627         Info.isEvaluatingCtorDtor(
3628             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3629                                          Sub.Entries.begin() + I)) !=
3630                           ConstructionPhase::None) {
3631       ObjType = Info.Ctx.getCanonicalType(ObjType);
3632       ObjType.removeLocalConst();
3633       ObjType.removeLocalVolatile();
3634     }
3635 
3636     // If this is our last pass, check that the final object type is OK.
3637     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3638       // Accesses to volatile objects are prohibited.
3639       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3640         if (Info.getLangOpts().CPlusPlus) {
3641           int DiagKind;
3642           SourceLocation Loc;
3643           const NamedDecl *Decl = nullptr;
3644           if (VolatileField) {
3645             DiagKind = 2;
3646             Loc = VolatileField->getLocation();
3647             Decl = VolatileField;
3648           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3649             DiagKind = 1;
3650             Loc = VD->getLocation();
3651             Decl = VD;
3652           } else {
3653             DiagKind = 0;
3654             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3655               Loc = E->getExprLoc();
3656           }
3657           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3658               << handler.AccessKind << DiagKind << Decl;
3659           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3660         } else {
3661           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3662         }
3663         return handler.failed();
3664       }
3665 
3666       // If we are reading an object of class type, there may still be more
3667       // things we need to check: if there are any mutable subobjects, we
3668       // cannot perform this read. (This only happens when performing a trivial
3669       // copy or assignment.)
3670       if (ObjType->isRecordType() &&
3671           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3672           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3673         return handler.failed();
3674     }
3675 
3676     if (I == N) {
3677       if (!handler.found(*O, ObjType))
3678         return false;
3679 
3680       // If we modified a bit-field, truncate it to the right width.
3681       if (isModification(handler.AccessKind) &&
3682           LastField && LastField->isBitField() &&
3683           !truncateBitfieldValue(Info, E, *O, LastField))
3684         return false;
3685 
3686       return true;
3687     }
3688 
3689     LastField = nullptr;
3690     if (ObjType->isArrayType()) {
3691       // Next subobject is an array element.
3692       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3693       assert(CAT && "vla in literal type?");
3694       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3695       if (CAT->getSize().ule(Index)) {
3696         // Note, it should not be possible to form a pointer with a valid
3697         // designator which points more than one past the end of the array.
3698         if (Info.getLangOpts().CPlusPlus11)
3699           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3700             << handler.AccessKind;
3701         else
3702           Info.FFDiag(E);
3703         return handler.failed();
3704       }
3705 
3706       ObjType = CAT->getElementType();
3707 
3708       if (O->getArrayInitializedElts() > Index)
3709         O = &O->getArrayInitializedElt(Index);
3710       else if (!isRead(handler.AccessKind)) {
3711         expandArray(*O, Index);
3712         O = &O->getArrayInitializedElt(Index);
3713       } else
3714         O = &O->getArrayFiller();
3715     } else if (ObjType->isAnyComplexType()) {
3716       // Next subobject is a complex number.
3717       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3718       if (Index > 1) {
3719         if (Info.getLangOpts().CPlusPlus11)
3720           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3721             << handler.AccessKind;
3722         else
3723           Info.FFDiag(E);
3724         return handler.failed();
3725       }
3726 
3727       ObjType = getSubobjectType(
3728           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3729 
3730       assert(I == N - 1 && "extracting subobject of scalar?");
3731       if (O->isComplexInt()) {
3732         return handler.found(Index ? O->getComplexIntImag()
3733                                    : O->getComplexIntReal(), ObjType);
3734       } else {
3735         assert(O->isComplexFloat());
3736         return handler.found(Index ? O->getComplexFloatImag()
3737                                    : O->getComplexFloatReal(), ObjType);
3738       }
3739     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3740       if (Field->isMutable() &&
3741           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3742         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3743           << handler.AccessKind << Field;
3744         Info.Note(Field->getLocation(), diag::note_declared_at);
3745         return handler.failed();
3746       }
3747 
3748       // Next subobject is a class, struct or union field.
3749       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3750       if (RD->isUnion()) {
3751         const FieldDecl *UnionField = O->getUnionField();
3752         if (!UnionField ||
3753             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3754           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3755             // Placement new onto an inactive union member makes it active.
3756             O->setUnion(Field, APValue());
3757           } else {
3758             // FIXME: If O->getUnionValue() is absent, report that there's no
3759             // active union member rather than reporting the prior active union
3760             // member. We'll need to fix nullptr_t to not use APValue() as its
3761             // representation first.
3762             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3763                 << handler.AccessKind << Field << !UnionField << UnionField;
3764             return handler.failed();
3765           }
3766         }
3767         O = &O->getUnionValue();
3768       } else
3769         O = &O->getStructField(Field->getFieldIndex());
3770 
3771       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3772       LastField = Field;
3773       if (Field->getType().isVolatileQualified())
3774         VolatileField = Field;
3775     } else {
3776       // Next subobject is a base class.
3777       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3778       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3779       O = &O->getStructBase(getBaseIndex(Derived, Base));
3780 
3781       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3782     }
3783   }
3784 }
3785 
3786 namespace {
3787 struct ExtractSubobjectHandler {
3788   EvalInfo &Info;
3789   const Expr *E;
3790   APValue &Result;
3791   const AccessKinds AccessKind;
3792 
3793   typedef bool result_type;
3794   bool failed() { return false; }
3795   bool found(APValue &Subobj, QualType SubobjType) {
3796     Result = Subobj;
3797     if (AccessKind == AK_ReadObjectRepresentation)
3798       return true;
3799     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3800   }
3801   bool found(APSInt &Value, QualType SubobjType) {
3802     Result = APValue(Value);
3803     return true;
3804   }
3805   bool found(APFloat &Value, QualType SubobjType) {
3806     Result = APValue(Value);
3807     return true;
3808   }
3809 };
3810 } // end anonymous namespace
3811 
3812 /// Extract the designated sub-object of an rvalue.
3813 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3814                              const CompleteObject &Obj,
3815                              const SubobjectDesignator &Sub, APValue &Result,
3816                              AccessKinds AK = AK_Read) {
3817   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3818   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3819   return findSubobject(Info, E, Obj, Sub, Handler);
3820 }
3821 
3822 namespace {
3823 struct ModifySubobjectHandler {
3824   EvalInfo &Info;
3825   APValue &NewVal;
3826   const Expr *E;
3827 
3828   typedef bool result_type;
3829   static const AccessKinds AccessKind = AK_Assign;
3830 
3831   bool checkConst(QualType QT) {
3832     // Assigning to a const object has undefined behavior.
3833     if (QT.isConstQualified()) {
3834       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3835       return false;
3836     }
3837     return true;
3838   }
3839 
3840   bool failed() { return false; }
3841   bool found(APValue &Subobj, QualType SubobjType) {
3842     if (!checkConst(SubobjType))
3843       return false;
3844     // We've been given ownership of NewVal, so just swap it in.
3845     Subobj.swap(NewVal);
3846     return true;
3847   }
3848   bool found(APSInt &Value, QualType SubobjType) {
3849     if (!checkConst(SubobjType))
3850       return false;
3851     if (!NewVal.isInt()) {
3852       // Maybe trying to write a cast pointer value into a complex?
3853       Info.FFDiag(E);
3854       return false;
3855     }
3856     Value = NewVal.getInt();
3857     return true;
3858   }
3859   bool found(APFloat &Value, QualType SubobjType) {
3860     if (!checkConst(SubobjType))
3861       return false;
3862     Value = NewVal.getFloat();
3863     return true;
3864   }
3865 };
3866 } // end anonymous namespace
3867 
3868 const AccessKinds ModifySubobjectHandler::AccessKind;
3869 
3870 /// Update the designated sub-object of an rvalue to the given value.
3871 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3872                             const CompleteObject &Obj,
3873                             const SubobjectDesignator &Sub,
3874                             APValue &NewVal) {
3875   ModifySubobjectHandler Handler = { Info, NewVal, E };
3876   return findSubobject(Info, E, Obj, Sub, Handler);
3877 }
3878 
3879 /// Find the position where two subobject designators diverge, or equivalently
3880 /// the length of the common initial subsequence.
3881 static unsigned FindDesignatorMismatch(QualType ObjType,
3882                                        const SubobjectDesignator &A,
3883                                        const SubobjectDesignator &B,
3884                                        bool &WasArrayIndex) {
3885   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3886   for (/**/; I != N; ++I) {
3887     if (!ObjType.isNull() &&
3888         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3889       // Next subobject is an array element.
3890       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3891         WasArrayIndex = true;
3892         return I;
3893       }
3894       if (ObjType->isAnyComplexType())
3895         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3896       else
3897         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3898     } else {
3899       if (A.Entries[I].getAsBaseOrMember() !=
3900           B.Entries[I].getAsBaseOrMember()) {
3901         WasArrayIndex = false;
3902         return I;
3903       }
3904       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3905         // Next subobject is a field.
3906         ObjType = FD->getType();
3907       else
3908         // Next subobject is a base class.
3909         ObjType = QualType();
3910     }
3911   }
3912   WasArrayIndex = false;
3913   return I;
3914 }
3915 
3916 /// Determine whether the given subobject designators refer to elements of the
3917 /// same array object.
3918 static bool AreElementsOfSameArray(QualType ObjType,
3919                                    const SubobjectDesignator &A,
3920                                    const SubobjectDesignator &B) {
3921   if (A.Entries.size() != B.Entries.size())
3922     return false;
3923 
3924   bool IsArray = A.MostDerivedIsArrayElement;
3925   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3926     // A is a subobject of the array element.
3927     return false;
3928 
3929   // If A (and B) designates an array element, the last entry will be the array
3930   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3931   // of length 1' case, and the entire path must match.
3932   bool WasArrayIndex;
3933   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3934   return CommonLength >= A.Entries.size() - IsArray;
3935 }
3936 
3937 /// Find the complete object to which an LValue refers.
3938 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3939                                          AccessKinds AK, const LValue &LVal,
3940                                          QualType LValType) {
3941   if (LVal.InvalidBase) {
3942     Info.FFDiag(E);
3943     return CompleteObject();
3944   }
3945 
3946   if (!LVal.Base) {
3947     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3948     return CompleteObject();
3949   }
3950 
3951   CallStackFrame *Frame = nullptr;
3952   unsigned Depth = 0;
3953   if (LVal.getLValueCallIndex()) {
3954     std::tie(Frame, Depth) =
3955         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3956     if (!Frame) {
3957       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3958         << AK << LVal.Base.is<const ValueDecl*>();
3959       NoteLValueLocation(Info, LVal.Base);
3960       return CompleteObject();
3961     }
3962   }
3963 
3964   bool IsAccess = isAnyAccess(AK);
3965 
3966   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3967   // is not a constant expression (even if the object is non-volatile). We also
3968   // apply this rule to C++98, in order to conform to the expected 'volatile'
3969   // semantics.
3970   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3971     if (Info.getLangOpts().CPlusPlus)
3972       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3973         << AK << LValType;
3974     else
3975       Info.FFDiag(E);
3976     return CompleteObject();
3977   }
3978 
3979   // Compute value storage location and type of base object.
3980   APValue *BaseVal = nullptr;
3981   QualType BaseType = getType(LVal.Base);
3982 
3983   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
3984       lifetimeStartedInEvaluation(Info, LVal.Base)) {
3985     // This is the object whose initializer we're evaluating, so its lifetime
3986     // started in the current evaluation.
3987     BaseVal = Info.EvaluatingDeclValue;
3988   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3989     // Allow reading from a GUID declaration.
3990     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
3991       if (isModification(AK)) {
3992         // All the remaining cases do not permit modification of the object.
3993         Info.FFDiag(E, diag::note_constexpr_modify_global);
3994         return CompleteObject();
3995       }
3996       APValue &V = GD->getAsAPValue();
3997       if (V.isAbsent()) {
3998         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
3999             << GD->getType();
4000         return CompleteObject();
4001       }
4002       return CompleteObject(LVal.Base, &V, GD->getType());
4003     }
4004 
4005     // Allow reading from template parameter objects.
4006     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4007       if (isModification(AK)) {
4008         Info.FFDiag(E, diag::note_constexpr_modify_global);
4009         return CompleteObject();
4010       }
4011       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4012                             TPO->getType());
4013     }
4014 
4015     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4016     // In C++11, constexpr, non-volatile variables initialized with constant
4017     // expressions are constant expressions too. Inside constexpr functions,
4018     // parameters are constant expressions even if they're non-const.
4019     // In C++1y, objects local to a constant expression (those with a Frame) are
4020     // both readable and writable inside constant expressions.
4021     // In C, such things can also be folded, although they are not ICEs.
4022     const VarDecl *VD = dyn_cast<VarDecl>(D);
4023     if (VD) {
4024       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4025         VD = VDef;
4026     }
4027     if (!VD || VD->isInvalidDecl()) {
4028       Info.FFDiag(E);
4029       return CompleteObject();
4030     }
4031 
4032     bool IsConstant = BaseType.isConstant(Info.Ctx);
4033 
4034     // Unless we're looking at a local variable or argument in a constexpr call,
4035     // the variable we're reading must be const.
4036     if (!Frame) {
4037       if (IsAccess && isa<ParmVarDecl>(VD)) {
4038         // Access of a parameter that's not associated with a frame isn't going
4039         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4040         // suitable diagnostic.
4041       } else if (Info.getLangOpts().CPlusPlus14 &&
4042                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4043         // OK, we can read and modify an object if we're in the process of
4044         // evaluating its initializer, because its lifetime began in this
4045         // evaluation.
4046       } else if (isModification(AK)) {
4047         // All the remaining cases do not permit modification of the object.
4048         Info.FFDiag(E, diag::note_constexpr_modify_global);
4049         return CompleteObject();
4050       } else if (VD->isConstexpr()) {
4051         // OK, we can read this variable.
4052       } else if (BaseType->isIntegralOrEnumerationType()) {
4053         if (!IsConstant) {
4054           if (!IsAccess)
4055             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4056           if (Info.getLangOpts().CPlusPlus) {
4057             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4058             Info.Note(VD->getLocation(), diag::note_declared_at);
4059           } else {
4060             Info.FFDiag(E);
4061           }
4062           return CompleteObject();
4063         }
4064       } else if (!IsAccess) {
4065         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4066       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4067                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4068         // This variable might end up being constexpr. Don't diagnose it yet.
4069       } else if (IsConstant) {
4070         // Keep evaluating to see what we can do. In particular, we support
4071         // folding of const floating-point types, in order to make static const
4072         // data members of such types (supported as an extension) more useful.
4073         if (Info.getLangOpts().CPlusPlus) {
4074           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4075                               ? diag::note_constexpr_ltor_non_constexpr
4076                               : diag::note_constexpr_ltor_non_integral, 1)
4077               << VD << BaseType;
4078           Info.Note(VD->getLocation(), diag::note_declared_at);
4079         } else {
4080           Info.CCEDiag(E);
4081         }
4082       } else {
4083         // Never allow reading a non-const value.
4084         if (Info.getLangOpts().CPlusPlus) {
4085           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4086                              ? diag::note_constexpr_ltor_non_constexpr
4087                              : diag::note_constexpr_ltor_non_integral, 1)
4088               << VD << BaseType;
4089           Info.Note(VD->getLocation(), diag::note_declared_at);
4090         } else {
4091           Info.FFDiag(E);
4092         }
4093         return CompleteObject();
4094       }
4095     }
4096 
4097     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4098       return CompleteObject();
4099   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4100     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4101     if (!Alloc) {
4102       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4103       return CompleteObject();
4104     }
4105     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4106                           LVal.Base.getDynamicAllocType());
4107   } else {
4108     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4109 
4110     if (!Frame) {
4111       if (const MaterializeTemporaryExpr *MTE =
4112               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4113         assert(MTE->getStorageDuration() == SD_Static &&
4114                "should have a frame for a non-global materialized temporary");
4115 
4116         // C++20 [expr.const]p4: [DR2126]
4117         //   An object or reference is usable in constant expressions if it is
4118         //   - a temporary object of non-volatile const-qualified literal type
4119         //     whose lifetime is extended to that of a variable that is usable
4120         //     in constant expressions
4121         //
4122         // C++20 [expr.const]p5:
4123         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4124         //   - a non-volatile glvalue that refers to an object that is usable
4125         //     in constant expressions, or
4126         //   - a non-volatile glvalue of literal type that refers to a
4127         //     non-volatile object whose lifetime began within the evaluation
4128         //     of E;
4129         //
4130         // C++11 misses the 'began within the evaluation of e' check and
4131         // instead allows all temporaries, including things like:
4132         //   int &&r = 1;
4133         //   int x = ++r;
4134         //   constexpr int k = r;
4135         // Therefore we use the C++14-onwards rules in C++11 too.
4136         //
4137         // Note that temporaries whose lifetimes began while evaluating a
4138         // variable's constructor are not usable while evaluating the
4139         // corresponding destructor, not even if they're of const-qualified
4140         // types.
4141         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4142             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4143           if (!IsAccess)
4144             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4145           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4146           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4147           return CompleteObject();
4148         }
4149 
4150         BaseVal = MTE->getOrCreateValue(false);
4151         assert(BaseVal && "got reference to unevaluated temporary");
4152       } else {
4153         if (!IsAccess)
4154           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4155         APValue Val;
4156         LVal.moveInto(Val);
4157         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4158             << AK
4159             << Val.getAsString(Info.Ctx,
4160                                Info.Ctx.getLValueReferenceType(LValType));
4161         NoteLValueLocation(Info, LVal.Base);
4162         return CompleteObject();
4163       }
4164     } else {
4165       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4166       assert(BaseVal && "missing value for temporary");
4167     }
4168   }
4169 
4170   // In C++14, we can't safely access any mutable state when we might be
4171   // evaluating after an unmodeled side effect. Parameters are modeled as state
4172   // in the caller, but aren't visible once the call returns, so they can be
4173   // modified in a speculatively-evaluated call.
4174   //
4175   // FIXME: Not all local state is mutable. Allow local constant subobjects
4176   // to be read here (but take care with 'mutable' fields).
4177   unsigned VisibleDepth = Depth;
4178   if (llvm::isa_and_nonnull<ParmVarDecl>(
4179           LVal.Base.dyn_cast<const ValueDecl *>()))
4180     ++VisibleDepth;
4181   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4182        Info.EvalStatus.HasSideEffects) ||
4183       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4184     return CompleteObject();
4185 
4186   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4187 }
4188 
4189 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4190 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4191 /// glvalue referred to by an entity of reference type.
4192 ///
4193 /// \param Info - Information about the ongoing evaluation.
4194 /// \param Conv - The expression for which we are performing the conversion.
4195 ///               Used for diagnostics.
4196 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4197 ///               case of a non-class type).
4198 /// \param LVal - The glvalue on which we are attempting to perform this action.
4199 /// \param RVal - The produced value will be placed here.
4200 /// \param WantObjectRepresentation - If true, we're looking for the object
4201 ///               representation rather than the value, and in particular,
4202 ///               there is no requirement that the result be fully initialized.
4203 static bool
4204 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4205                                const LValue &LVal, APValue &RVal,
4206                                bool WantObjectRepresentation = false) {
4207   if (LVal.Designator.Invalid)
4208     return false;
4209 
4210   // Check for special cases where there is no existing APValue to look at.
4211   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4212 
4213   AccessKinds AK =
4214       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4215 
4216   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4217     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4218       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4219       // initializer until now for such expressions. Such an expression can't be
4220       // an ICE in C, so this only matters for fold.
4221       if (Type.isVolatileQualified()) {
4222         Info.FFDiag(Conv);
4223         return false;
4224       }
4225       APValue Lit;
4226       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4227         return false;
4228       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4229       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4230     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4231       // Special-case character extraction so we don't have to construct an
4232       // APValue for the whole string.
4233       assert(LVal.Designator.Entries.size() <= 1 &&
4234              "Can only read characters from string literals");
4235       if (LVal.Designator.Entries.empty()) {
4236         // Fail for now for LValue to RValue conversion of an array.
4237         // (This shouldn't show up in C/C++, but it could be triggered by a
4238         // weird EvaluateAsRValue call from a tool.)
4239         Info.FFDiag(Conv);
4240         return false;
4241       }
4242       if (LVal.Designator.isOnePastTheEnd()) {
4243         if (Info.getLangOpts().CPlusPlus11)
4244           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4245         else
4246           Info.FFDiag(Conv);
4247         return false;
4248       }
4249       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4250       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4251       return true;
4252     }
4253   }
4254 
4255   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4256   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4257 }
4258 
4259 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4260 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4261                              QualType LValType, APValue &Val) {
4262   if (LVal.Designator.Invalid)
4263     return false;
4264 
4265   if (!Info.getLangOpts().CPlusPlus14) {
4266     Info.FFDiag(E);
4267     return false;
4268   }
4269 
4270   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4271   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4272 }
4273 
4274 namespace {
4275 struct CompoundAssignSubobjectHandler {
4276   EvalInfo &Info;
4277   const CompoundAssignOperator *E;
4278   QualType PromotedLHSType;
4279   BinaryOperatorKind Opcode;
4280   const APValue &RHS;
4281 
4282   static const AccessKinds AccessKind = AK_Assign;
4283 
4284   typedef bool result_type;
4285 
4286   bool checkConst(QualType QT) {
4287     // Assigning to a const object has undefined behavior.
4288     if (QT.isConstQualified()) {
4289       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4290       return false;
4291     }
4292     return true;
4293   }
4294 
4295   bool failed() { return false; }
4296   bool found(APValue &Subobj, QualType SubobjType) {
4297     switch (Subobj.getKind()) {
4298     case APValue::Int:
4299       return found(Subobj.getInt(), SubobjType);
4300     case APValue::Float:
4301       return found(Subobj.getFloat(), SubobjType);
4302     case APValue::ComplexInt:
4303     case APValue::ComplexFloat:
4304       // FIXME: Implement complex compound assignment.
4305       Info.FFDiag(E);
4306       return false;
4307     case APValue::LValue:
4308       return foundPointer(Subobj, SubobjType);
4309     case APValue::Vector:
4310       return foundVector(Subobj, SubobjType);
4311     default:
4312       // FIXME: can this happen?
4313       Info.FFDiag(E);
4314       return false;
4315     }
4316   }
4317 
4318   bool foundVector(APValue &Value, QualType SubobjType) {
4319     if (!checkConst(SubobjType))
4320       return false;
4321 
4322     if (!SubobjType->isVectorType()) {
4323       Info.FFDiag(E);
4324       return false;
4325     }
4326     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4327   }
4328 
4329   bool found(APSInt &Value, QualType SubobjType) {
4330     if (!checkConst(SubobjType))
4331       return false;
4332 
4333     if (!SubobjType->isIntegerType()) {
4334       // We don't support compound assignment on integer-cast-to-pointer
4335       // values.
4336       Info.FFDiag(E);
4337       return false;
4338     }
4339 
4340     if (RHS.isInt()) {
4341       APSInt LHS =
4342           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4343       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4344         return false;
4345       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4346       return true;
4347     } else if (RHS.isFloat()) {
4348       const FPOptions FPO = E->getFPFeaturesInEffect(
4349                                     Info.Ctx.getLangOpts());
4350       APFloat FValue(0.0);
4351       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4352                                   PromotedLHSType, FValue) &&
4353              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4354              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4355                                   Value);
4356     }
4357 
4358     Info.FFDiag(E);
4359     return false;
4360   }
4361   bool found(APFloat &Value, QualType SubobjType) {
4362     return checkConst(SubobjType) &&
4363            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4364                                   Value) &&
4365            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4366            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4367   }
4368   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4369     if (!checkConst(SubobjType))
4370       return false;
4371 
4372     QualType PointeeType;
4373     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4374       PointeeType = PT->getPointeeType();
4375 
4376     if (PointeeType.isNull() || !RHS.isInt() ||
4377         (Opcode != BO_Add && Opcode != BO_Sub)) {
4378       Info.FFDiag(E);
4379       return false;
4380     }
4381 
4382     APSInt Offset = RHS.getInt();
4383     if (Opcode == BO_Sub)
4384       negateAsSigned(Offset);
4385 
4386     LValue LVal;
4387     LVal.setFrom(Info.Ctx, Subobj);
4388     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4389       return false;
4390     LVal.moveInto(Subobj);
4391     return true;
4392   }
4393 };
4394 } // end anonymous namespace
4395 
4396 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4397 
4398 /// Perform a compound assignment of LVal <op>= RVal.
4399 static bool handleCompoundAssignment(EvalInfo &Info,
4400                                      const CompoundAssignOperator *E,
4401                                      const LValue &LVal, QualType LValType,
4402                                      QualType PromotedLValType,
4403                                      BinaryOperatorKind Opcode,
4404                                      const APValue &RVal) {
4405   if (LVal.Designator.Invalid)
4406     return false;
4407 
4408   if (!Info.getLangOpts().CPlusPlus14) {
4409     Info.FFDiag(E);
4410     return false;
4411   }
4412 
4413   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4414   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4415                                              RVal };
4416   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4417 }
4418 
4419 namespace {
4420 struct IncDecSubobjectHandler {
4421   EvalInfo &Info;
4422   const UnaryOperator *E;
4423   AccessKinds AccessKind;
4424   APValue *Old;
4425 
4426   typedef bool result_type;
4427 
4428   bool checkConst(QualType QT) {
4429     // Assigning to a const object has undefined behavior.
4430     if (QT.isConstQualified()) {
4431       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4432       return false;
4433     }
4434     return true;
4435   }
4436 
4437   bool failed() { return false; }
4438   bool found(APValue &Subobj, QualType SubobjType) {
4439     // Stash the old value. Also clear Old, so we don't clobber it later
4440     // if we're post-incrementing a complex.
4441     if (Old) {
4442       *Old = Subobj;
4443       Old = nullptr;
4444     }
4445 
4446     switch (Subobj.getKind()) {
4447     case APValue::Int:
4448       return found(Subobj.getInt(), SubobjType);
4449     case APValue::Float:
4450       return found(Subobj.getFloat(), SubobjType);
4451     case APValue::ComplexInt:
4452       return found(Subobj.getComplexIntReal(),
4453                    SubobjType->castAs<ComplexType>()->getElementType()
4454                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4455     case APValue::ComplexFloat:
4456       return found(Subobj.getComplexFloatReal(),
4457                    SubobjType->castAs<ComplexType>()->getElementType()
4458                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4459     case APValue::LValue:
4460       return foundPointer(Subobj, SubobjType);
4461     default:
4462       // FIXME: can this happen?
4463       Info.FFDiag(E);
4464       return false;
4465     }
4466   }
4467   bool found(APSInt &Value, QualType SubobjType) {
4468     if (!checkConst(SubobjType))
4469       return false;
4470 
4471     if (!SubobjType->isIntegerType()) {
4472       // We don't support increment / decrement on integer-cast-to-pointer
4473       // values.
4474       Info.FFDiag(E);
4475       return false;
4476     }
4477 
4478     if (Old) *Old = APValue(Value);
4479 
4480     // bool arithmetic promotes to int, and the conversion back to bool
4481     // doesn't reduce mod 2^n, so special-case it.
4482     if (SubobjType->isBooleanType()) {
4483       if (AccessKind == AK_Increment)
4484         Value = 1;
4485       else
4486         Value = !Value;
4487       return true;
4488     }
4489 
4490     bool WasNegative = Value.isNegative();
4491     if (AccessKind == AK_Increment) {
4492       ++Value;
4493 
4494       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4495         APSInt ActualValue(Value, /*IsUnsigned*/true);
4496         return HandleOverflow(Info, E, ActualValue, SubobjType);
4497       }
4498     } else {
4499       --Value;
4500 
4501       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4502         unsigned BitWidth = Value.getBitWidth();
4503         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4504         ActualValue.setBit(BitWidth);
4505         return HandleOverflow(Info, E, ActualValue, SubobjType);
4506       }
4507     }
4508     return true;
4509   }
4510   bool found(APFloat &Value, QualType SubobjType) {
4511     if (!checkConst(SubobjType))
4512       return false;
4513 
4514     if (Old) *Old = APValue(Value);
4515 
4516     APFloat One(Value.getSemantics(), 1);
4517     if (AccessKind == AK_Increment)
4518       Value.add(One, APFloat::rmNearestTiesToEven);
4519     else
4520       Value.subtract(One, APFloat::rmNearestTiesToEven);
4521     return true;
4522   }
4523   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4524     if (!checkConst(SubobjType))
4525       return false;
4526 
4527     QualType PointeeType;
4528     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4529       PointeeType = PT->getPointeeType();
4530     else {
4531       Info.FFDiag(E);
4532       return false;
4533     }
4534 
4535     LValue LVal;
4536     LVal.setFrom(Info.Ctx, Subobj);
4537     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4538                                      AccessKind == AK_Increment ? 1 : -1))
4539       return false;
4540     LVal.moveInto(Subobj);
4541     return true;
4542   }
4543 };
4544 } // end anonymous namespace
4545 
4546 /// Perform an increment or decrement on LVal.
4547 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4548                          QualType LValType, bool IsIncrement, APValue *Old) {
4549   if (LVal.Designator.Invalid)
4550     return false;
4551 
4552   if (!Info.getLangOpts().CPlusPlus14) {
4553     Info.FFDiag(E);
4554     return false;
4555   }
4556 
4557   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4558   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4559   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4560   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4561 }
4562 
4563 /// Build an lvalue for the object argument of a member function call.
4564 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4565                                    LValue &This) {
4566   if (Object->getType()->isPointerType() && Object->isRValue())
4567     return EvaluatePointer(Object, This, Info);
4568 
4569   if (Object->isGLValue())
4570     return EvaluateLValue(Object, This, Info);
4571 
4572   if (Object->getType()->isLiteralType(Info.Ctx))
4573     return EvaluateTemporary(Object, This, Info);
4574 
4575   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4576   return false;
4577 }
4578 
4579 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4580 /// lvalue referring to the result.
4581 ///
4582 /// \param Info - Information about the ongoing evaluation.
4583 /// \param LV - An lvalue referring to the base of the member pointer.
4584 /// \param RHS - The member pointer expression.
4585 /// \param IncludeMember - Specifies whether the member itself is included in
4586 ///        the resulting LValue subobject designator. This is not possible when
4587 ///        creating a bound member function.
4588 /// \return The field or method declaration to which the member pointer refers,
4589 ///         or 0 if evaluation fails.
4590 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4591                                                   QualType LVType,
4592                                                   LValue &LV,
4593                                                   const Expr *RHS,
4594                                                   bool IncludeMember = true) {
4595   MemberPtr MemPtr;
4596   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4597     return nullptr;
4598 
4599   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4600   // member value, the behavior is undefined.
4601   if (!MemPtr.getDecl()) {
4602     // FIXME: Specific diagnostic.
4603     Info.FFDiag(RHS);
4604     return nullptr;
4605   }
4606 
4607   if (MemPtr.isDerivedMember()) {
4608     // This is a member of some derived class. Truncate LV appropriately.
4609     // The end of the derived-to-base path for the base object must match the
4610     // derived-to-base path for the member pointer.
4611     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4612         LV.Designator.Entries.size()) {
4613       Info.FFDiag(RHS);
4614       return nullptr;
4615     }
4616     unsigned PathLengthToMember =
4617         LV.Designator.Entries.size() - MemPtr.Path.size();
4618     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4619       const CXXRecordDecl *LVDecl = getAsBaseClass(
4620           LV.Designator.Entries[PathLengthToMember + I]);
4621       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4622       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4623         Info.FFDiag(RHS);
4624         return nullptr;
4625       }
4626     }
4627 
4628     // Truncate the lvalue to the appropriate derived class.
4629     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4630                             PathLengthToMember))
4631       return nullptr;
4632   } else if (!MemPtr.Path.empty()) {
4633     // Extend the LValue path with the member pointer's path.
4634     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4635                                   MemPtr.Path.size() + IncludeMember);
4636 
4637     // Walk down to the appropriate base class.
4638     if (const PointerType *PT = LVType->getAs<PointerType>())
4639       LVType = PT->getPointeeType();
4640     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4641     assert(RD && "member pointer access on non-class-type expression");
4642     // The first class in the path is that of the lvalue.
4643     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4644       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4645       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4646         return nullptr;
4647       RD = Base;
4648     }
4649     // Finally cast to the class containing the member.
4650     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4651                                 MemPtr.getContainingRecord()))
4652       return nullptr;
4653   }
4654 
4655   // Add the member. Note that we cannot build bound member functions here.
4656   if (IncludeMember) {
4657     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4658       if (!HandleLValueMember(Info, RHS, LV, FD))
4659         return nullptr;
4660     } else if (const IndirectFieldDecl *IFD =
4661                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4662       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4663         return nullptr;
4664     } else {
4665       llvm_unreachable("can't construct reference to bound member function");
4666     }
4667   }
4668 
4669   return MemPtr.getDecl();
4670 }
4671 
4672 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4673                                                   const BinaryOperator *BO,
4674                                                   LValue &LV,
4675                                                   bool IncludeMember = true) {
4676   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4677 
4678   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4679     if (Info.noteFailure()) {
4680       MemberPtr MemPtr;
4681       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4682     }
4683     return nullptr;
4684   }
4685 
4686   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4687                                    BO->getRHS(), IncludeMember);
4688 }
4689 
4690 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4691 /// the provided lvalue, which currently refers to the base object.
4692 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4693                                     LValue &Result) {
4694   SubobjectDesignator &D = Result.Designator;
4695   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4696     return false;
4697 
4698   QualType TargetQT = E->getType();
4699   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4700     TargetQT = PT->getPointeeType();
4701 
4702   // Check this cast lands within the final derived-to-base subobject path.
4703   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4704     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4705       << D.MostDerivedType << TargetQT;
4706     return false;
4707   }
4708 
4709   // Check the type of the final cast. We don't need to check the path,
4710   // since a cast can only be formed if the path is unique.
4711   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4712   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4713   const CXXRecordDecl *FinalType;
4714   if (NewEntriesSize == D.MostDerivedPathLength)
4715     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4716   else
4717     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4718   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4719     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4720       << D.MostDerivedType << TargetQT;
4721     return false;
4722   }
4723 
4724   // Truncate the lvalue to the appropriate derived class.
4725   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4726 }
4727 
4728 /// Get the value to use for a default-initialized object of type T.
4729 /// Return false if it encounters something invalid.
4730 static bool getDefaultInitValue(QualType T, APValue &Result) {
4731   bool Success = true;
4732   if (auto *RD = T->getAsCXXRecordDecl()) {
4733     if (RD->isInvalidDecl()) {
4734       Result = APValue();
4735       return false;
4736     }
4737     if (RD->isUnion()) {
4738       Result = APValue((const FieldDecl *)nullptr);
4739       return true;
4740     }
4741     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4742                      std::distance(RD->field_begin(), RD->field_end()));
4743 
4744     unsigned Index = 0;
4745     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4746                                                   End = RD->bases_end();
4747          I != End; ++I, ++Index)
4748       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4749 
4750     for (const auto *I : RD->fields()) {
4751       if (I->isUnnamedBitfield())
4752         continue;
4753       Success &= getDefaultInitValue(I->getType(),
4754                                      Result.getStructField(I->getFieldIndex()));
4755     }
4756     return Success;
4757   }
4758 
4759   if (auto *AT =
4760           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4761     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4762     if (Result.hasArrayFiller())
4763       Success &=
4764           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4765 
4766     return Success;
4767   }
4768 
4769   Result = APValue::IndeterminateValue();
4770   return true;
4771 }
4772 
4773 namespace {
4774 enum EvalStmtResult {
4775   /// Evaluation failed.
4776   ESR_Failed,
4777   /// Hit a 'return' statement.
4778   ESR_Returned,
4779   /// Evaluation succeeded.
4780   ESR_Succeeded,
4781   /// Hit a 'continue' statement.
4782   ESR_Continue,
4783   /// Hit a 'break' statement.
4784   ESR_Break,
4785   /// Still scanning for 'case' or 'default' statement.
4786   ESR_CaseNotFound
4787 };
4788 }
4789 
4790 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4791   // We don't need to evaluate the initializer for a static local.
4792   if (!VD->hasLocalStorage())
4793     return true;
4794 
4795   LValue Result;
4796   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4797                                                    ScopeKind::Block, Result);
4798 
4799   const Expr *InitE = VD->getInit();
4800   if (!InitE) {
4801     if (VD->getType()->isDependentType())
4802       return Info.noteSideEffect();
4803     return getDefaultInitValue(VD->getType(), Val);
4804   }
4805   if (InitE->isValueDependent())
4806     return false;
4807 
4808   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4809     // Wipe out any partially-computed value, to allow tracking that this
4810     // evaluation failed.
4811     Val = APValue();
4812     return false;
4813   }
4814 
4815   return true;
4816 }
4817 
4818 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4819   bool OK = true;
4820 
4821   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4822     OK &= EvaluateVarDecl(Info, VD);
4823 
4824   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4825     for (auto *BD : DD->bindings())
4826       if (auto *VD = BD->getHoldingVar())
4827         OK &= EvaluateDecl(Info, VD);
4828 
4829   return OK;
4830 }
4831 
4832 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4833   assert(E->isValueDependent());
4834   if (Info.noteSideEffect())
4835     return true;
4836   assert(E->containsErrors() && "valid value-dependent expression should never "
4837                                 "reach invalid code path.");
4838   return false;
4839 }
4840 
4841 /// Evaluate a condition (either a variable declaration or an expression).
4842 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4843                          const Expr *Cond, bool &Result) {
4844   if (Cond->isValueDependent())
4845     return false;
4846   FullExpressionRAII Scope(Info);
4847   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4848     return false;
4849   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4850     return false;
4851   return Scope.destroy();
4852 }
4853 
4854 namespace {
4855 /// A location where the result (returned value) of evaluating a
4856 /// statement should be stored.
4857 struct StmtResult {
4858   /// The APValue that should be filled in with the returned value.
4859   APValue &Value;
4860   /// The location containing the result, if any (used to support RVO).
4861   const LValue *Slot;
4862 };
4863 
4864 struct TempVersionRAII {
4865   CallStackFrame &Frame;
4866 
4867   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4868     Frame.pushTempVersion();
4869   }
4870 
4871   ~TempVersionRAII() {
4872     Frame.popTempVersion();
4873   }
4874 };
4875 
4876 }
4877 
4878 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4879                                    const Stmt *S,
4880                                    const SwitchCase *SC = nullptr);
4881 
4882 /// Evaluate the body of a loop, and translate the result as appropriate.
4883 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4884                                        const Stmt *Body,
4885                                        const SwitchCase *Case = nullptr) {
4886   BlockScopeRAII Scope(Info);
4887 
4888   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4889   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4890     ESR = ESR_Failed;
4891 
4892   switch (ESR) {
4893   case ESR_Break:
4894     return ESR_Succeeded;
4895   case ESR_Succeeded:
4896   case ESR_Continue:
4897     return ESR_Continue;
4898   case ESR_Failed:
4899   case ESR_Returned:
4900   case ESR_CaseNotFound:
4901     return ESR;
4902   }
4903   llvm_unreachable("Invalid EvalStmtResult!");
4904 }
4905 
4906 /// Evaluate a switch statement.
4907 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4908                                      const SwitchStmt *SS) {
4909   BlockScopeRAII Scope(Info);
4910 
4911   // Evaluate the switch condition.
4912   APSInt Value;
4913   {
4914     if (const Stmt *Init = SS->getInit()) {
4915       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4916       if (ESR != ESR_Succeeded) {
4917         if (ESR != ESR_Failed && !Scope.destroy())
4918           ESR = ESR_Failed;
4919         return ESR;
4920       }
4921     }
4922 
4923     FullExpressionRAII CondScope(Info);
4924     if (SS->getConditionVariable() &&
4925         !EvaluateDecl(Info, SS->getConditionVariable()))
4926       return ESR_Failed;
4927     if (!EvaluateInteger(SS->getCond(), Value, Info))
4928       return ESR_Failed;
4929     if (!CondScope.destroy())
4930       return ESR_Failed;
4931   }
4932 
4933   // Find the switch case corresponding to the value of the condition.
4934   // FIXME: Cache this lookup.
4935   const SwitchCase *Found = nullptr;
4936   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4937        SC = SC->getNextSwitchCase()) {
4938     if (isa<DefaultStmt>(SC)) {
4939       Found = SC;
4940       continue;
4941     }
4942 
4943     const CaseStmt *CS = cast<CaseStmt>(SC);
4944     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4945     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4946                               : LHS;
4947     if (LHS <= Value && Value <= RHS) {
4948       Found = SC;
4949       break;
4950     }
4951   }
4952 
4953   if (!Found)
4954     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4955 
4956   // Search the switch body for the switch case and evaluate it from there.
4957   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4958   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4959     return ESR_Failed;
4960 
4961   switch (ESR) {
4962   case ESR_Break:
4963     return ESR_Succeeded;
4964   case ESR_Succeeded:
4965   case ESR_Continue:
4966   case ESR_Failed:
4967   case ESR_Returned:
4968     return ESR;
4969   case ESR_CaseNotFound:
4970     // This can only happen if the switch case is nested within a statement
4971     // expression. We have no intention of supporting that.
4972     Info.FFDiag(Found->getBeginLoc(),
4973                 diag::note_constexpr_stmt_expr_unsupported);
4974     return ESR_Failed;
4975   }
4976   llvm_unreachable("Invalid EvalStmtResult!");
4977 }
4978 
4979 // Evaluate a statement.
4980 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4981                                    const Stmt *S, const SwitchCase *Case) {
4982   if (!Info.nextStep(S))
4983     return ESR_Failed;
4984 
4985   // If we're hunting down a 'case' or 'default' label, recurse through
4986   // substatements until we hit the label.
4987   if (Case) {
4988     switch (S->getStmtClass()) {
4989     case Stmt::CompoundStmtClass:
4990       // FIXME: Precompute which substatement of a compound statement we
4991       // would jump to, and go straight there rather than performing a
4992       // linear scan each time.
4993     case Stmt::LabelStmtClass:
4994     case Stmt::AttributedStmtClass:
4995     case Stmt::DoStmtClass:
4996       break;
4997 
4998     case Stmt::CaseStmtClass:
4999     case Stmt::DefaultStmtClass:
5000       if (Case == S)
5001         Case = nullptr;
5002       break;
5003 
5004     case Stmt::IfStmtClass: {
5005       // FIXME: Precompute which side of an 'if' we would jump to, and go
5006       // straight there rather than scanning both sides.
5007       const IfStmt *IS = cast<IfStmt>(S);
5008 
5009       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5010       // preceded by our switch label.
5011       BlockScopeRAII Scope(Info);
5012 
5013       // Step into the init statement in case it brings an (uninitialized)
5014       // variable into scope.
5015       if (const Stmt *Init = IS->getInit()) {
5016         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5017         if (ESR != ESR_CaseNotFound) {
5018           assert(ESR != ESR_Succeeded);
5019           return ESR;
5020         }
5021       }
5022 
5023       // Condition variable must be initialized if it exists.
5024       // FIXME: We can skip evaluating the body if there's a condition
5025       // variable, as there can't be any case labels within it.
5026       // (The same is true for 'for' statements.)
5027 
5028       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5029       if (ESR == ESR_Failed)
5030         return ESR;
5031       if (ESR != ESR_CaseNotFound)
5032         return Scope.destroy() ? ESR : ESR_Failed;
5033       if (!IS->getElse())
5034         return ESR_CaseNotFound;
5035 
5036       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5037       if (ESR == ESR_Failed)
5038         return ESR;
5039       if (ESR != ESR_CaseNotFound)
5040         return Scope.destroy() ? ESR : ESR_Failed;
5041       return ESR_CaseNotFound;
5042     }
5043 
5044     case Stmt::WhileStmtClass: {
5045       EvalStmtResult ESR =
5046           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5047       if (ESR != ESR_Continue)
5048         return ESR;
5049       break;
5050     }
5051 
5052     case Stmt::ForStmtClass: {
5053       const ForStmt *FS = cast<ForStmt>(S);
5054       BlockScopeRAII Scope(Info);
5055 
5056       // Step into the init statement in case it brings an (uninitialized)
5057       // variable into scope.
5058       if (const Stmt *Init = FS->getInit()) {
5059         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5060         if (ESR != ESR_CaseNotFound) {
5061           assert(ESR != ESR_Succeeded);
5062           return ESR;
5063         }
5064       }
5065 
5066       EvalStmtResult ESR =
5067           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5068       if (ESR != ESR_Continue)
5069         return ESR;
5070       if (const auto *Inc = FS->getInc()) {
5071         if (Inc->isValueDependent()) {
5072           if (!EvaluateDependentExpr(Inc, Info))
5073             return ESR_Failed;
5074         } else {
5075           FullExpressionRAII IncScope(Info);
5076           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5077             return ESR_Failed;
5078         }
5079       }
5080       break;
5081     }
5082 
5083     case Stmt::DeclStmtClass: {
5084       // Start the lifetime of any uninitialized variables we encounter. They
5085       // might be used by the selected branch of the switch.
5086       const DeclStmt *DS = cast<DeclStmt>(S);
5087       for (const auto *D : DS->decls()) {
5088         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5089           if (VD->hasLocalStorage() && !VD->getInit())
5090             if (!EvaluateVarDecl(Info, VD))
5091               return ESR_Failed;
5092           // FIXME: If the variable has initialization that can't be jumped
5093           // over, bail out of any immediately-surrounding compound-statement
5094           // too. There can't be any case labels here.
5095         }
5096       }
5097       return ESR_CaseNotFound;
5098     }
5099 
5100     default:
5101       return ESR_CaseNotFound;
5102     }
5103   }
5104 
5105   switch (S->getStmtClass()) {
5106   default:
5107     if (const Expr *E = dyn_cast<Expr>(S)) {
5108       if (E->isValueDependent()) {
5109         if (!EvaluateDependentExpr(E, Info))
5110           return ESR_Failed;
5111       } else {
5112         // Don't bother evaluating beyond an expression-statement which couldn't
5113         // be evaluated.
5114         // FIXME: Do we need the FullExpressionRAII object here?
5115         // VisitExprWithCleanups should create one when necessary.
5116         FullExpressionRAII Scope(Info);
5117         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5118           return ESR_Failed;
5119       }
5120       return ESR_Succeeded;
5121     }
5122 
5123     Info.FFDiag(S->getBeginLoc());
5124     return ESR_Failed;
5125 
5126   case Stmt::NullStmtClass:
5127     return ESR_Succeeded;
5128 
5129   case Stmt::DeclStmtClass: {
5130     const DeclStmt *DS = cast<DeclStmt>(S);
5131     for (const auto *D : DS->decls()) {
5132       // Each declaration initialization is its own full-expression.
5133       FullExpressionRAII Scope(Info);
5134       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5135         return ESR_Failed;
5136       if (!Scope.destroy())
5137         return ESR_Failed;
5138     }
5139     return ESR_Succeeded;
5140   }
5141 
5142   case Stmt::ReturnStmtClass: {
5143     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5144     FullExpressionRAII Scope(Info);
5145     if (RetExpr && RetExpr->isValueDependent()) {
5146       EvaluateDependentExpr(RetExpr, Info);
5147       // We know we returned, but we don't know what the value is.
5148       return ESR_Failed;
5149     }
5150     if (RetExpr &&
5151         !(Result.Slot
5152               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5153               : Evaluate(Result.Value, Info, RetExpr)))
5154       return ESR_Failed;
5155     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5156   }
5157 
5158   case Stmt::CompoundStmtClass: {
5159     BlockScopeRAII Scope(Info);
5160 
5161     const CompoundStmt *CS = cast<CompoundStmt>(S);
5162     for (const auto *BI : CS->body()) {
5163       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5164       if (ESR == ESR_Succeeded)
5165         Case = nullptr;
5166       else if (ESR != ESR_CaseNotFound) {
5167         if (ESR != ESR_Failed && !Scope.destroy())
5168           return ESR_Failed;
5169         return ESR;
5170       }
5171     }
5172     if (Case)
5173       return ESR_CaseNotFound;
5174     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5175   }
5176 
5177   case Stmt::IfStmtClass: {
5178     const IfStmt *IS = cast<IfStmt>(S);
5179 
5180     // Evaluate the condition, as either a var decl or as an expression.
5181     BlockScopeRAII Scope(Info);
5182     if (const Stmt *Init = IS->getInit()) {
5183       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5184       if (ESR != ESR_Succeeded) {
5185         if (ESR != ESR_Failed && !Scope.destroy())
5186           return ESR_Failed;
5187         return ESR;
5188       }
5189     }
5190     bool Cond;
5191     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
5192       return ESR_Failed;
5193 
5194     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5195       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5196       if (ESR != ESR_Succeeded) {
5197         if (ESR != ESR_Failed && !Scope.destroy())
5198           return ESR_Failed;
5199         return ESR;
5200       }
5201     }
5202     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5203   }
5204 
5205   case Stmt::WhileStmtClass: {
5206     const WhileStmt *WS = cast<WhileStmt>(S);
5207     while (true) {
5208       BlockScopeRAII Scope(Info);
5209       bool Continue;
5210       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5211                         Continue))
5212         return ESR_Failed;
5213       if (!Continue)
5214         break;
5215 
5216       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5217       if (ESR != ESR_Continue) {
5218         if (ESR != ESR_Failed && !Scope.destroy())
5219           return ESR_Failed;
5220         return ESR;
5221       }
5222       if (!Scope.destroy())
5223         return ESR_Failed;
5224     }
5225     return ESR_Succeeded;
5226   }
5227 
5228   case Stmt::DoStmtClass: {
5229     const DoStmt *DS = cast<DoStmt>(S);
5230     bool Continue;
5231     do {
5232       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5233       if (ESR != ESR_Continue)
5234         return ESR;
5235       Case = nullptr;
5236 
5237       if (DS->getCond()->isValueDependent()) {
5238         EvaluateDependentExpr(DS->getCond(), Info);
5239         // Bailout as we don't know whether to keep going or terminate the loop.
5240         return ESR_Failed;
5241       }
5242       FullExpressionRAII CondScope(Info);
5243       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5244           !CondScope.destroy())
5245         return ESR_Failed;
5246     } while (Continue);
5247     return ESR_Succeeded;
5248   }
5249 
5250   case Stmt::ForStmtClass: {
5251     const ForStmt *FS = cast<ForStmt>(S);
5252     BlockScopeRAII ForScope(Info);
5253     if (FS->getInit()) {
5254       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5255       if (ESR != ESR_Succeeded) {
5256         if (ESR != ESR_Failed && !ForScope.destroy())
5257           return ESR_Failed;
5258         return ESR;
5259       }
5260     }
5261     while (true) {
5262       BlockScopeRAII IterScope(Info);
5263       bool Continue = true;
5264       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5265                                          FS->getCond(), Continue))
5266         return ESR_Failed;
5267       if (!Continue)
5268         break;
5269 
5270       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5271       if (ESR != ESR_Continue) {
5272         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5273           return ESR_Failed;
5274         return ESR;
5275       }
5276 
5277       if (const auto *Inc = FS->getInc()) {
5278         if (Inc->isValueDependent()) {
5279           if (!EvaluateDependentExpr(Inc, Info))
5280             return ESR_Failed;
5281         } else {
5282           FullExpressionRAII IncScope(Info);
5283           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5284             return ESR_Failed;
5285         }
5286       }
5287 
5288       if (!IterScope.destroy())
5289         return ESR_Failed;
5290     }
5291     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5292   }
5293 
5294   case Stmt::CXXForRangeStmtClass: {
5295     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5296     BlockScopeRAII Scope(Info);
5297 
5298     // Evaluate the init-statement if present.
5299     if (FS->getInit()) {
5300       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5301       if (ESR != ESR_Succeeded) {
5302         if (ESR != ESR_Failed && !Scope.destroy())
5303           return ESR_Failed;
5304         return ESR;
5305       }
5306     }
5307 
5308     // Initialize the __range variable.
5309     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5310     if (ESR != ESR_Succeeded) {
5311       if (ESR != ESR_Failed && !Scope.destroy())
5312         return ESR_Failed;
5313       return ESR;
5314     }
5315 
5316     // Create the __begin and __end iterators.
5317     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5318     if (ESR != ESR_Succeeded) {
5319       if (ESR != ESR_Failed && !Scope.destroy())
5320         return ESR_Failed;
5321       return ESR;
5322     }
5323     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5324     if (ESR != ESR_Succeeded) {
5325       if (ESR != ESR_Failed && !Scope.destroy())
5326         return ESR_Failed;
5327       return ESR;
5328     }
5329 
5330     while (true) {
5331       // Condition: __begin != __end.
5332       {
5333         if (FS->getCond()->isValueDependent()) {
5334           EvaluateDependentExpr(FS->getCond(), Info);
5335           // We don't know whether to keep going or terminate the loop.
5336           return ESR_Failed;
5337         }
5338         bool Continue = true;
5339         FullExpressionRAII CondExpr(Info);
5340         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5341           return ESR_Failed;
5342         if (!Continue)
5343           break;
5344       }
5345 
5346       // User's variable declaration, initialized by *__begin.
5347       BlockScopeRAII InnerScope(Info);
5348       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5349       if (ESR != ESR_Succeeded) {
5350         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5351           return ESR_Failed;
5352         return ESR;
5353       }
5354 
5355       // Loop body.
5356       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5357       if (ESR != ESR_Continue) {
5358         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5359           return ESR_Failed;
5360         return ESR;
5361       }
5362       if (FS->getInc()->isValueDependent()) {
5363         if (!EvaluateDependentExpr(FS->getInc(), Info))
5364           return ESR_Failed;
5365       } else {
5366         // Increment: ++__begin
5367         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5368           return ESR_Failed;
5369       }
5370 
5371       if (!InnerScope.destroy())
5372         return ESR_Failed;
5373     }
5374 
5375     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5376   }
5377 
5378   case Stmt::SwitchStmtClass:
5379     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5380 
5381   case Stmt::ContinueStmtClass:
5382     return ESR_Continue;
5383 
5384   case Stmt::BreakStmtClass:
5385     return ESR_Break;
5386 
5387   case Stmt::LabelStmtClass:
5388     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5389 
5390   case Stmt::AttributedStmtClass:
5391     // As a general principle, C++11 attributes can be ignored without
5392     // any semantic impact.
5393     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5394                         Case);
5395 
5396   case Stmt::CaseStmtClass:
5397   case Stmt::DefaultStmtClass:
5398     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5399   case Stmt::CXXTryStmtClass:
5400     // Evaluate try blocks by evaluating all sub statements.
5401     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5402   }
5403 }
5404 
5405 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5406 /// default constructor. If so, we'll fold it whether or not it's marked as
5407 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5408 /// so we need special handling.
5409 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5410                                            const CXXConstructorDecl *CD,
5411                                            bool IsValueInitialization) {
5412   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5413     return false;
5414 
5415   // Value-initialization does not call a trivial default constructor, so such a
5416   // call is a core constant expression whether or not the constructor is
5417   // constexpr.
5418   if (!CD->isConstexpr() && !IsValueInitialization) {
5419     if (Info.getLangOpts().CPlusPlus11) {
5420       // FIXME: If DiagDecl is an implicitly-declared special member function,
5421       // we should be much more explicit about why it's not constexpr.
5422       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5423         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5424       Info.Note(CD->getLocation(), diag::note_declared_at);
5425     } else {
5426       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5427     }
5428   }
5429   return true;
5430 }
5431 
5432 /// CheckConstexprFunction - Check that a function can be called in a constant
5433 /// expression.
5434 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5435                                    const FunctionDecl *Declaration,
5436                                    const FunctionDecl *Definition,
5437                                    const Stmt *Body) {
5438   // Potential constant expressions can contain calls to declared, but not yet
5439   // defined, constexpr functions.
5440   if (Info.checkingPotentialConstantExpression() && !Definition &&
5441       Declaration->isConstexpr())
5442     return false;
5443 
5444   // Bail out if the function declaration itself is invalid.  We will
5445   // have produced a relevant diagnostic while parsing it, so just
5446   // note the problematic sub-expression.
5447   if (Declaration->isInvalidDecl()) {
5448     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5449     return false;
5450   }
5451 
5452   // DR1872: An instantiated virtual constexpr function can't be called in a
5453   // constant expression (prior to C++20). We can still constant-fold such a
5454   // call.
5455   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5456       cast<CXXMethodDecl>(Declaration)->isVirtual())
5457     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5458 
5459   if (Definition && Definition->isInvalidDecl()) {
5460     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5461     return false;
5462   }
5463 
5464   // Can we evaluate this function call?
5465   if (Definition && Definition->isConstexpr() && Body)
5466     return true;
5467 
5468   if (Info.getLangOpts().CPlusPlus11) {
5469     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5470 
5471     // If this function is not constexpr because it is an inherited
5472     // non-constexpr constructor, diagnose that directly.
5473     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5474     if (CD && CD->isInheritingConstructor()) {
5475       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5476       if (!Inherited->isConstexpr())
5477         DiagDecl = CD = Inherited;
5478     }
5479 
5480     // FIXME: If DiagDecl is an implicitly-declared special member function
5481     // or an inheriting constructor, we should be much more explicit about why
5482     // it's not constexpr.
5483     if (CD && CD->isInheritingConstructor())
5484       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5485         << CD->getInheritedConstructor().getConstructor()->getParent();
5486     else
5487       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5488         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5489     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5490   } else {
5491     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5492   }
5493   return false;
5494 }
5495 
5496 namespace {
5497 struct CheckDynamicTypeHandler {
5498   AccessKinds AccessKind;
5499   typedef bool result_type;
5500   bool failed() { return false; }
5501   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5502   bool found(APSInt &Value, QualType SubobjType) { return true; }
5503   bool found(APFloat &Value, QualType SubobjType) { return true; }
5504 };
5505 } // end anonymous namespace
5506 
5507 /// Check that we can access the notional vptr of an object / determine its
5508 /// dynamic type.
5509 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5510                              AccessKinds AK, bool Polymorphic) {
5511   if (This.Designator.Invalid)
5512     return false;
5513 
5514   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5515 
5516   if (!Obj)
5517     return false;
5518 
5519   if (!Obj.Value) {
5520     // The object is not usable in constant expressions, so we can't inspect
5521     // its value to see if it's in-lifetime or what the active union members
5522     // are. We can still check for a one-past-the-end lvalue.
5523     if (This.Designator.isOnePastTheEnd() ||
5524         This.Designator.isMostDerivedAnUnsizedArray()) {
5525       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5526                          ? diag::note_constexpr_access_past_end
5527                          : diag::note_constexpr_access_unsized_array)
5528           << AK;
5529       return false;
5530     } else if (Polymorphic) {
5531       // Conservatively refuse to perform a polymorphic operation if we would
5532       // not be able to read a notional 'vptr' value.
5533       APValue Val;
5534       This.moveInto(Val);
5535       QualType StarThisType =
5536           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5537       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5538           << AK << Val.getAsString(Info.Ctx, StarThisType);
5539       return false;
5540     }
5541     return true;
5542   }
5543 
5544   CheckDynamicTypeHandler Handler{AK};
5545   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5546 }
5547 
5548 /// Check that the pointee of the 'this' pointer in a member function call is
5549 /// either within its lifetime or in its period of construction or destruction.
5550 static bool
5551 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5552                                      const LValue &This,
5553                                      const CXXMethodDecl *NamedMember) {
5554   return checkDynamicType(
5555       Info, E, This,
5556       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5557 }
5558 
5559 struct DynamicType {
5560   /// The dynamic class type of the object.
5561   const CXXRecordDecl *Type;
5562   /// The corresponding path length in the lvalue.
5563   unsigned PathLength;
5564 };
5565 
5566 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5567                                              unsigned PathLength) {
5568   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5569       Designator.Entries.size() && "invalid path length");
5570   return (PathLength == Designator.MostDerivedPathLength)
5571              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5572              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5573 }
5574 
5575 /// Determine the dynamic type of an object.
5576 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5577                                                 LValue &This, AccessKinds AK) {
5578   // If we don't have an lvalue denoting an object of class type, there is no
5579   // meaningful dynamic type. (We consider objects of non-class type to have no
5580   // dynamic type.)
5581   if (!checkDynamicType(Info, E, This, AK, true))
5582     return None;
5583 
5584   // Refuse to compute a dynamic type in the presence of virtual bases. This
5585   // shouldn't happen other than in constant-folding situations, since literal
5586   // types can't have virtual bases.
5587   //
5588   // Note that consumers of DynamicType assume that the type has no virtual
5589   // bases, and will need modifications if this restriction is relaxed.
5590   const CXXRecordDecl *Class =
5591       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5592   if (!Class || Class->getNumVBases()) {
5593     Info.FFDiag(E);
5594     return None;
5595   }
5596 
5597   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5598   // binary search here instead. But the overwhelmingly common case is that
5599   // we're not in the middle of a constructor, so it probably doesn't matter
5600   // in practice.
5601   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5602   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5603        PathLength <= Path.size(); ++PathLength) {
5604     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5605                                       Path.slice(0, PathLength))) {
5606     case ConstructionPhase::Bases:
5607     case ConstructionPhase::DestroyingBases:
5608       // We're constructing or destroying a base class. This is not the dynamic
5609       // type.
5610       break;
5611 
5612     case ConstructionPhase::None:
5613     case ConstructionPhase::AfterBases:
5614     case ConstructionPhase::AfterFields:
5615     case ConstructionPhase::Destroying:
5616       // We've finished constructing the base classes and not yet started
5617       // destroying them again, so this is the dynamic type.
5618       return DynamicType{getBaseClassType(This.Designator, PathLength),
5619                          PathLength};
5620     }
5621   }
5622 
5623   // CWG issue 1517: we're constructing a base class of the object described by
5624   // 'This', so that object has not yet begun its period of construction and
5625   // any polymorphic operation on it results in undefined behavior.
5626   Info.FFDiag(E);
5627   return None;
5628 }
5629 
5630 /// Perform virtual dispatch.
5631 static const CXXMethodDecl *HandleVirtualDispatch(
5632     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5633     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5634   Optional<DynamicType> DynType = ComputeDynamicType(
5635       Info, E, This,
5636       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5637   if (!DynType)
5638     return nullptr;
5639 
5640   // Find the final overrider. It must be declared in one of the classes on the
5641   // path from the dynamic type to the static type.
5642   // FIXME: If we ever allow literal types to have virtual base classes, that
5643   // won't be true.
5644   const CXXMethodDecl *Callee = Found;
5645   unsigned PathLength = DynType->PathLength;
5646   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5647     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5648     const CXXMethodDecl *Overrider =
5649         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5650     if (Overrider) {
5651       Callee = Overrider;
5652       break;
5653     }
5654   }
5655 
5656   // C++2a [class.abstract]p6:
5657   //   the effect of making a virtual call to a pure virtual function [...] is
5658   //   undefined
5659   if (Callee->isPure()) {
5660     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5661     Info.Note(Callee->getLocation(), diag::note_declared_at);
5662     return nullptr;
5663   }
5664 
5665   // If necessary, walk the rest of the path to determine the sequence of
5666   // covariant adjustment steps to apply.
5667   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5668                                        Found->getReturnType())) {
5669     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5670     for (unsigned CovariantPathLength = PathLength + 1;
5671          CovariantPathLength != This.Designator.Entries.size();
5672          ++CovariantPathLength) {
5673       const CXXRecordDecl *NextClass =
5674           getBaseClassType(This.Designator, CovariantPathLength);
5675       const CXXMethodDecl *Next =
5676           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5677       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5678                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5679         CovariantAdjustmentPath.push_back(Next->getReturnType());
5680     }
5681     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5682                                          CovariantAdjustmentPath.back()))
5683       CovariantAdjustmentPath.push_back(Found->getReturnType());
5684   }
5685 
5686   // Perform 'this' adjustment.
5687   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5688     return nullptr;
5689 
5690   return Callee;
5691 }
5692 
5693 /// Perform the adjustment from a value returned by a virtual function to
5694 /// a value of the statically expected type, which may be a pointer or
5695 /// reference to a base class of the returned type.
5696 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5697                                             APValue &Result,
5698                                             ArrayRef<QualType> Path) {
5699   assert(Result.isLValue() &&
5700          "unexpected kind of APValue for covariant return");
5701   if (Result.isNullPointer())
5702     return true;
5703 
5704   LValue LVal;
5705   LVal.setFrom(Info.Ctx, Result);
5706 
5707   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5708   for (unsigned I = 1; I != Path.size(); ++I) {
5709     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5710     assert(OldClass && NewClass && "unexpected kind of covariant return");
5711     if (OldClass != NewClass &&
5712         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5713       return false;
5714     OldClass = NewClass;
5715   }
5716 
5717   LVal.moveInto(Result);
5718   return true;
5719 }
5720 
5721 /// Determine whether \p Base, which is known to be a direct base class of
5722 /// \p Derived, is a public base class.
5723 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5724                               const CXXRecordDecl *Base) {
5725   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5726     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5727     if (BaseClass && declaresSameEntity(BaseClass, Base))
5728       return BaseSpec.getAccessSpecifier() == AS_public;
5729   }
5730   llvm_unreachable("Base is not a direct base of Derived");
5731 }
5732 
5733 /// Apply the given dynamic cast operation on the provided lvalue.
5734 ///
5735 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5736 /// to find a suitable target subobject.
5737 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5738                               LValue &Ptr) {
5739   // We can't do anything with a non-symbolic pointer value.
5740   SubobjectDesignator &D = Ptr.Designator;
5741   if (D.Invalid)
5742     return false;
5743 
5744   // C++ [expr.dynamic.cast]p6:
5745   //   If v is a null pointer value, the result is a null pointer value.
5746   if (Ptr.isNullPointer() && !E->isGLValue())
5747     return true;
5748 
5749   // For all the other cases, we need the pointer to point to an object within
5750   // its lifetime / period of construction / destruction, and we need to know
5751   // its dynamic type.
5752   Optional<DynamicType> DynType =
5753       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5754   if (!DynType)
5755     return false;
5756 
5757   // C++ [expr.dynamic.cast]p7:
5758   //   If T is "pointer to cv void", then the result is a pointer to the most
5759   //   derived object
5760   if (E->getType()->isVoidPointerType())
5761     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5762 
5763   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5764   assert(C && "dynamic_cast target is not void pointer nor class");
5765   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5766 
5767   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5768     // C++ [expr.dynamic.cast]p9:
5769     if (!E->isGLValue()) {
5770       //   The value of a failed cast to pointer type is the null pointer value
5771       //   of the required result type.
5772       Ptr.setNull(Info.Ctx, E->getType());
5773       return true;
5774     }
5775 
5776     //   A failed cast to reference type throws [...] std::bad_cast.
5777     unsigned DiagKind;
5778     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5779                    DynType->Type->isDerivedFrom(C)))
5780       DiagKind = 0;
5781     else if (!Paths || Paths->begin() == Paths->end())
5782       DiagKind = 1;
5783     else if (Paths->isAmbiguous(CQT))
5784       DiagKind = 2;
5785     else {
5786       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5787       DiagKind = 3;
5788     }
5789     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5790         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5791         << Info.Ctx.getRecordType(DynType->Type)
5792         << E->getType().getUnqualifiedType();
5793     return false;
5794   };
5795 
5796   // Runtime check, phase 1:
5797   //   Walk from the base subobject towards the derived object looking for the
5798   //   target type.
5799   for (int PathLength = Ptr.Designator.Entries.size();
5800        PathLength >= (int)DynType->PathLength; --PathLength) {
5801     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5802     if (declaresSameEntity(Class, C))
5803       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5804     // We can only walk across public inheritance edges.
5805     if (PathLength > (int)DynType->PathLength &&
5806         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5807                            Class))
5808       return RuntimeCheckFailed(nullptr);
5809   }
5810 
5811   // Runtime check, phase 2:
5812   //   Search the dynamic type for an unambiguous public base of type C.
5813   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5814                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5815   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5816       Paths.front().Access == AS_public) {
5817     // Downcast to the dynamic type...
5818     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5819       return false;
5820     // ... then upcast to the chosen base class subobject.
5821     for (CXXBasePathElement &Elem : Paths.front())
5822       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5823         return false;
5824     return true;
5825   }
5826 
5827   // Otherwise, the runtime check fails.
5828   return RuntimeCheckFailed(&Paths);
5829 }
5830 
5831 namespace {
5832 struct StartLifetimeOfUnionMemberHandler {
5833   EvalInfo &Info;
5834   const Expr *LHSExpr;
5835   const FieldDecl *Field;
5836   bool DuringInit;
5837   bool Failed = false;
5838   static const AccessKinds AccessKind = AK_Assign;
5839 
5840   typedef bool result_type;
5841   bool failed() { return Failed; }
5842   bool found(APValue &Subobj, QualType SubobjType) {
5843     // We are supposed to perform no initialization but begin the lifetime of
5844     // the object. We interpret that as meaning to do what default
5845     // initialization of the object would do if all constructors involved were
5846     // trivial:
5847     //  * All base, non-variant member, and array element subobjects' lifetimes
5848     //    begin
5849     //  * No variant members' lifetimes begin
5850     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5851     assert(SubobjType->isUnionType());
5852     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5853       // This union member is already active. If it's also in-lifetime, there's
5854       // nothing to do.
5855       if (Subobj.getUnionValue().hasValue())
5856         return true;
5857     } else if (DuringInit) {
5858       // We're currently in the process of initializing a different union
5859       // member.  If we carried on, that initialization would attempt to
5860       // store to an inactive union member, resulting in undefined behavior.
5861       Info.FFDiag(LHSExpr,
5862                   diag::note_constexpr_union_member_change_during_init);
5863       return false;
5864     }
5865     APValue Result;
5866     Failed = !getDefaultInitValue(Field->getType(), Result);
5867     Subobj.setUnion(Field, Result);
5868     return true;
5869   }
5870   bool found(APSInt &Value, QualType SubobjType) {
5871     llvm_unreachable("wrong value kind for union object");
5872   }
5873   bool found(APFloat &Value, QualType SubobjType) {
5874     llvm_unreachable("wrong value kind for union object");
5875   }
5876 };
5877 } // end anonymous namespace
5878 
5879 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5880 
5881 /// Handle a builtin simple-assignment or a call to a trivial assignment
5882 /// operator whose left-hand side might involve a union member access. If it
5883 /// does, implicitly start the lifetime of any accessed union elements per
5884 /// C++20 [class.union]5.
5885 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5886                                           const LValue &LHS) {
5887   if (LHS.InvalidBase || LHS.Designator.Invalid)
5888     return false;
5889 
5890   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5891   // C++ [class.union]p5:
5892   //   define the set S(E) of subexpressions of E as follows:
5893   unsigned PathLength = LHS.Designator.Entries.size();
5894   for (const Expr *E = LHSExpr; E != nullptr;) {
5895     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5896     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5897       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5898       // Note that we can't implicitly start the lifetime of a reference,
5899       // so we don't need to proceed any further if we reach one.
5900       if (!FD || FD->getType()->isReferenceType())
5901         break;
5902 
5903       //    ... and also contains A.B if B names a union member ...
5904       if (FD->getParent()->isUnion()) {
5905         //    ... of a non-class, non-array type, or of a class type with a
5906         //    trivial default constructor that is not deleted, or an array of
5907         //    such types.
5908         auto *RD =
5909             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5910         if (!RD || RD->hasTrivialDefaultConstructor())
5911           UnionPathLengths.push_back({PathLength - 1, FD});
5912       }
5913 
5914       E = ME->getBase();
5915       --PathLength;
5916       assert(declaresSameEntity(FD,
5917                                 LHS.Designator.Entries[PathLength]
5918                                     .getAsBaseOrMember().getPointer()));
5919 
5920       //   -- If E is of the form A[B] and is interpreted as a built-in array
5921       //      subscripting operator, S(E) is [S(the array operand, if any)].
5922     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5923       // Step over an ArrayToPointerDecay implicit cast.
5924       auto *Base = ASE->getBase()->IgnoreImplicit();
5925       if (!Base->getType()->isArrayType())
5926         break;
5927 
5928       E = Base;
5929       --PathLength;
5930 
5931     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5932       // Step over a derived-to-base conversion.
5933       E = ICE->getSubExpr();
5934       if (ICE->getCastKind() == CK_NoOp)
5935         continue;
5936       if (ICE->getCastKind() != CK_DerivedToBase &&
5937           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5938         break;
5939       // Walk path backwards as we walk up from the base to the derived class.
5940       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5941         --PathLength;
5942         (void)Elt;
5943         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5944                                   LHS.Designator.Entries[PathLength]
5945                                       .getAsBaseOrMember().getPointer()));
5946       }
5947 
5948     //   -- Otherwise, S(E) is empty.
5949     } else {
5950       break;
5951     }
5952   }
5953 
5954   // Common case: no unions' lifetimes are started.
5955   if (UnionPathLengths.empty())
5956     return true;
5957 
5958   //   if modification of X [would access an inactive union member], an object
5959   //   of the type of X is implicitly created
5960   CompleteObject Obj =
5961       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5962   if (!Obj)
5963     return false;
5964   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5965            llvm::reverse(UnionPathLengths)) {
5966     // Form a designator for the union object.
5967     SubobjectDesignator D = LHS.Designator;
5968     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5969 
5970     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5971                       ConstructionPhase::AfterBases;
5972     StartLifetimeOfUnionMemberHandler StartLifetime{
5973         Info, LHSExpr, LengthAndField.second, DuringInit};
5974     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5975       return false;
5976   }
5977 
5978   return true;
5979 }
5980 
5981 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
5982                             CallRef Call, EvalInfo &Info,
5983                             bool NonNull = false) {
5984   LValue LV;
5985   // Create the parameter slot and register its destruction. For a vararg
5986   // argument, create a temporary.
5987   // FIXME: For calling conventions that destroy parameters in the callee,
5988   // should we consider performing destruction when the function returns
5989   // instead?
5990   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
5991                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
5992                                                        ScopeKind::Call, LV);
5993   if (!EvaluateInPlace(V, Info, LV, Arg))
5994     return false;
5995 
5996   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
5997   // undefined behavior, so is non-constant.
5998   if (NonNull && V.isLValue() && V.isNullPointer()) {
5999     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6000     return false;
6001   }
6002 
6003   return true;
6004 }
6005 
6006 /// Evaluate the arguments to a function call.
6007 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6008                          EvalInfo &Info, const FunctionDecl *Callee,
6009                          bool RightToLeft = false) {
6010   bool Success = true;
6011   llvm::SmallBitVector ForbiddenNullArgs;
6012   if (Callee->hasAttr<NonNullAttr>()) {
6013     ForbiddenNullArgs.resize(Args.size());
6014     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6015       if (!Attr->args_size()) {
6016         ForbiddenNullArgs.set();
6017         break;
6018       } else
6019         for (auto Idx : Attr->args()) {
6020           unsigned ASTIdx = Idx.getASTIndex();
6021           if (ASTIdx >= Args.size())
6022             continue;
6023           ForbiddenNullArgs[ASTIdx] = 1;
6024         }
6025     }
6026   }
6027   for (unsigned I = 0; I < Args.size(); I++) {
6028     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6029     const ParmVarDecl *PVD =
6030         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6031     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6032     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6033       // If we're checking for a potential constant expression, evaluate all
6034       // initializers even if some of them fail.
6035       if (!Info.noteFailure())
6036         return false;
6037       Success = false;
6038     }
6039   }
6040   return Success;
6041 }
6042 
6043 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6044 /// constructor or assignment operator.
6045 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6046                               const Expr *E, APValue &Result,
6047                               bool CopyObjectRepresentation) {
6048   // Find the reference argument.
6049   CallStackFrame *Frame = Info.CurrentCall;
6050   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6051   if (!RefValue) {
6052     Info.FFDiag(E);
6053     return false;
6054   }
6055 
6056   // Copy out the contents of the RHS object.
6057   LValue RefLValue;
6058   RefLValue.setFrom(Info.Ctx, *RefValue);
6059   return handleLValueToRValueConversion(
6060       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6061       CopyObjectRepresentation);
6062 }
6063 
6064 /// Evaluate a function call.
6065 static bool HandleFunctionCall(SourceLocation CallLoc,
6066                                const FunctionDecl *Callee, const LValue *This,
6067                                ArrayRef<const Expr *> Args, CallRef Call,
6068                                const Stmt *Body, EvalInfo &Info,
6069                                APValue &Result, const LValue *ResultSlot) {
6070   if (!Info.CheckCallLimit(CallLoc))
6071     return false;
6072 
6073   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6074 
6075   // For a trivial copy or move assignment, perform an APValue copy. This is
6076   // essential for unions, where the operations performed by the assignment
6077   // operator cannot be represented as statements.
6078   //
6079   // Skip this for non-union classes with no fields; in that case, the defaulted
6080   // copy/move does not actually read the object.
6081   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6082   if (MD && MD->isDefaulted() &&
6083       (MD->getParent()->isUnion() ||
6084        (MD->isTrivial() &&
6085         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6086     assert(This &&
6087            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6088     APValue RHSValue;
6089     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6090                            MD->getParent()->isUnion()))
6091       return false;
6092     if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
6093         !HandleUnionActiveMemberChange(Info, Args[0], *This))
6094       return false;
6095     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6096                           RHSValue))
6097       return false;
6098     This->moveInto(Result);
6099     return true;
6100   } else if (MD && isLambdaCallOperator(MD)) {
6101     // We're in a lambda; determine the lambda capture field maps unless we're
6102     // just constexpr checking a lambda's call operator. constexpr checking is
6103     // done before the captures have been added to the closure object (unless
6104     // we're inferring constexpr-ness), so we don't have access to them in this
6105     // case. But since we don't need the captures to constexpr check, we can
6106     // just ignore them.
6107     if (!Info.checkingPotentialConstantExpression())
6108       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6109                                         Frame.LambdaThisCaptureField);
6110   }
6111 
6112   StmtResult Ret = {Result, ResultSlot};
6113   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6114   if (ESR == ESR_Succeeded) {
6115     if (Callee->getReturnType()->isVoidType())
6116       return true;
6117     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6118   }
6119   return ESR == ESR_Returned;
6120 }
6121 
6122 /// Evaluate a constructor call.
6123 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6124                                   CallRef Call,
6125                                   const CXXConstructorDecl *Definition,
6126                                   EvalInfo &Info, APValue &Result) {
6127   SourceLocation CallLoc = E->getExprLoc();
6128   if (!Info.CheckCallLimit(CallLoc))
6129     return false;
6130 
6131   const CXXRecordDecl *RD = Definition->getParent();
6132   if (RD->getNumVBases()) {
6133     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6134     return false;
6135   }
6136 
6137   EvalInfo::EvaluatingConstructorRAII EvalObj(
6138       Info,
6139       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6140       RD->getNumBases());
6141   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6142 
6143   // FIXME: Creating an APValue just to hold a nonexistent return value is
6144   // wasteful.
6145   APValue RetVal;
6146   StmtResult Ret = {RetVal, nullptr};
6147 
6148   // If it's a delegating constructor, delegate.
6149   if (Definition->isDelegatingConstructor()) {
6150     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6151     if ((*I)->getInit()->isValueDependent()) {
6152       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6153         return false;
6154     } else {
6155       FullExpressionRAII InitScope(Info);
6156       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6157           !InitScope.destroy())
6158         return false;
6159     }
6160     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6161   }
6162 
6163   // For a trivial copy or move constructor, perform an APValue copy. This is
6164   // essential for unions (or classes with anonymous union members), where the
6165   // operations performed by the constructor cannot be represented by
6166   // ctor-initializers.
6167   //
6168   // Skip this for empty non-union classes; we should not perform an
6169   // lvalue-to-rvalue conversion on them because their copy constructor does not
6170   // actually read them.
6171   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6172       (Definition->getParent()->isUnion() ||
6173        (Definition->isTrivial() &&
6174         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6175     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6176                              Definition->getParent()->isUnion());
6177   }
6178 
6179   // Reserve space for the struct members.
6180   if (!Result.hasValue()) {
6181     if (!RD->isUnion())
6182       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6183                        std::distance(RD->field_begin(), RD->field_end()));
6184     else
6185       // A union starts with no active member.
6186       Result = APValue((const FieldDecl*)nullptr);
6187   }
6188 
6189   if (RD->isInvalidDecl()) return false;
6190   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6191 
6192   // A scope for temporaries lifetime-extended by reference members.
6193   BlockScopeRAII LifetimeExtendedScope(Info);
6194 
6195   bool Success = true;
6196   unsigned BasesSeen = 0;
6197 #ifndef NDEBUG
6198   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6199 #endif
6200   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6201   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6202     // We might be initializing the same field again if this is an indirect
6203     // field initialization.
6204     if (FieldIt == RD->field_end() ||
6205         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6206       assert(Indirect && "fields out of order?");
6207       return;
6208     }
6209 
6210     // Default-initialize any fields with no explicit initializer.
6211     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6212       assert(FieldIt != RD->field_end() && "missing field?");
6213       if (!FieldIt->isUnnamedBitfield())
6214         Success &= getDefaultInitValue(
6215             FieldIt->getType(),
6216             Result.getStructField(FieldIt->getFieldIndex()));
6217     }
6218     ++FieldIt;
6219   };
6220   for (const auto *I : Definition->inits()) {
6221     LValue Subobject = This;
6222     LValue SubobjectParent = This;
6223     APValue *Value = &Result;
6224 
6225     // Determine the subobject to initialize.
6226     FieldDecl *FD = nullptr;
6227     if (I->isBaseInitializer()) {
6228       QualType BaseType(I->getBaseClass(), 0);
6229 #ifndef NDEBUG
6230       // Non-virtual base classes are initialized in the order in the class
6231       // definition. We have already checked for virtual base classes.
6232       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6233       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6234              "base class initializers not in expected order");
6235       ++BaseIt;
6236 #endif
6237       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6238                                   BaseType->getAsCXXRecordDecl(), &Layout))
6239         return false;
6240       Value = &Result.getStructBase(BasesSeen++);
6241     } else if ((FD = I->getMember())) {
6242       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6243         return false;
6244       if (RD->isUnion()) {
6245         Result = APValue(FD);
6246         Value = &Result.getUnionValue();
6247       } else {
6248         SkipToField(FD, false);
6249         Value = &Result.getStructField(FD->getFieldIndex());
6250       }
6251     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6252       // Walk the indirect field decl's chain to find the object to initialize,
6253       // and make sure we've initialized every step along it.
6254       auto IndirectFieldChain = IFD->chain();
6255       for (auto *C : IndirectFieldChain) {
6256         FD = cast<FieldDecl>(C);
6257         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6258         // Switch the union field if it differs. This happens if we had
6259         // preceding zero-initialization, and we're now initializing a union
6260         // subobject other than the first.
6261         // FIXME: In this case, the values of the other subobjects are
6262         // specified, since zero-initialization sets all padding bits to zero.
6263         if (!Value->hasValue() ||
6264             (Value->isUnion() && Value->getUnionField() != FD)) {
6265           if (CD->isUnion())
6266             *Value = APValue(FD);
6267           else
6268             // FIXME: This immediately starts the lifetime of all members of
6269             // an anonymous struct. It would be preferable to strictly start
6270             // member lifetime in initialization order.
6271             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6272         }
6273         // Store Subobject as its parent before updating it for the last element
6274         // in the chain.
6275         if (C == IndirectFieldChain.back())
6276           SubobjectParent = Subobject;
6277         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6278           return false;
6279         if (CD->isUnion())
6280           Value = &Value->getUnionValue();
6281         else {
6282           if (C == IndirectFieldChain.front() && !RD->isUnion())
6283             SkipToField(FD, true);
6284           Value = &Value->getStructField(FD->getFieldIndex());
6285         }
6286       }
6287     } else {
6288       llvm_unreachable("unknown base initializer kind");
6289     }
6290 
6291     // Need to override This for implicit field initializers as in this case
6292     // This refers to innermost anonymous struct/union containing initializer,
6293     // not to currently constructed class.
6294     const Expr *Init = I->getInit();
6295     if (Init->isValueDependent()) {
6296       if (!EvaluateDependentExpr(Init, Info))
6297         return false;
6298     } else {
6299       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6300                                     isa<CXXDefaultInitExpr>(Init));
6301       FullExpressionRAII InitScope(Info);
6302       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6303           (FD && FD->isBitField() &&
6304            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6305         // If we're checking for a potential constant expression, evaluate all
6306         // initializers even if some of them fail.
6307         if (!Info.noteFailure())
6308           return false;
6309         Success = false;
6310       }
6311     }
6312 
6313     // This is the point at which the dynamic type of the object becomes this
6314     // class type.
6315     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6316       EvalObj.finishedConstructingBases();
6317   }
6318 
6319   // Default-initialize any remaining fields.
6320   if (!RD->isUnion()) {
6321     for (; FieldIt != RD->field_end(); ++FieldIt) {
6322       if (!FieldIt->isUnnamedBitfield())
6323         Success &= getDefaultInitValue(
6324             FieldIt->getType(),
6325             Result.getStructField(FieldIt->getFieldIndex()));
6326     }
6327   }
6328 
6329   EvalObj.finishedConstructingFields();
6330 
6331   return Success &&
6332          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6333          LifetimeExtendedScope.destroy();
6334 }
6335 
6336 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6337                                   ArrayRef<const Expr*> Args,
6338                                   const CXXConstructorDecl *Definition,
6339                                   EvalInfo &Info, APValue &Result) {
6340   CallScopeRAII CallScope(Info);
6341   CallRef Call = Info.CurrentCall->createCall(Definition);
6342   if (!EvaluateArgs(Args, Call, Info, Definition))
6343     return false;
6344 
6345   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6346          CallScope.destroy();
6347 }
6348 
6349 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6350                                   const LValue &This, APValue &Value,
6351                                   QualType T) {
6352   // Objects can only be destroyed while they're within their lifetimes.
6353   // FIXME: We have no representation for whether an object of type nullptr_t
6354   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6355   // as indeterminate instead?
6356   if (Value.isAbsent() && !T->isNullPtrType()) {
6357     APValue Printable;
6358     This.moveInto(Printable);
6359     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6360       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6361     return false;
6362   }
6363 
6364   // Invent an expression for location purposes.
6365   // FIXME: We shouldn't need to do this.
6366   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
6367 
6368   // For arrays, destroy elements right-to-left.
6369   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6370     uint64_t Size = CAT->getSize().getZExtValue();
6371     QualType ElemT = CAT->getElementType();
6372 
6373     LValue ElemLV = This;
6374     ElemLV.addArray(Info, &LocE, CAT);
6375     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6376       return false;
6377 
6378     // Ensure that we have actual array elements available to destroy; the
6379     // destructors might mutate the value, so we can't run them on the array
6380     // filler.
6381     if (Size && Size > Value.getArrayInitializedElts())
6382       expandArray(Value, Value.getArraySize() - 1);
6383 
6384     for (; Size != 0; --Size) {
6385       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6386       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6387           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6388         return false;
6389     }
6390 
6391     // End the lifetime of this array now.
6392     Value = APValue();
6393     return true;
6394   }
6395 
6396   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6397   if (!RD) {
6398     if (T.isDestructedType()) {
6399       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6400       return false;
6401     }
6402 
6403     Value = APValue();
6404     return true;
6405   }
6406 
6407   if (RD->getNumVBases()) {
6408     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6409     return false;
6410   }
6411 
6412   const CXXDestructorDecl *DD = RD->getDestructor();
6413   if (!DD && !RD->hasTrivialDestructor()) {
6414     Info.FFDiag(CallLoc);
6415     return false;
6416   }
6417 
6418   if (!DD || DD->isTrivial() ||
6419       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6420     // A trivial destructor just ends the lifetime of the object. Check for
6421     // this case before checking for a body, because we might not bother
6422     // building a body for a trivial destructor. Note that it doesn't matter
6423     // whether the destructor is constexpr in this case; all trivial
6424     // destructors are constexpr.
6425     //
6426     // If an anonymous union would be destroyed, some enclosing destructor must
6427     // have been explicitly defined, and the anonymous union destruction should
6428     // have no effect.
6429     Value = APValue();
6430     return true;
6431   }
6432 
6433   if (!Info.CheckCallLimit(CallLoc))
6434     return false;
6435 
6436   const FunctionDecl *Definition = nullptr;
6437   const Stmt *Body = DD->getBody(Definition);
6438 
6439   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6440     return false;
6441 
6442   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6443 
6444   // We're now in the period of destruction of this object.
6445   unsigned BasesLeft = RD->getNumBases();
6446   EvalInfo::EvaluatingDestructorRAII EvalObj(
6447       Info,
6448       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6449   if (!EvalObj.DidInsert) {
6450     // C++2a [class.dtor]p19:
6451     //   the behavior is undefined if the destructor is invoked for an object
6452     //   whose lifetime has ended
6453     // (Note that formally the lifetime ends when the period of destruction
6454     // begins, even though certain uses of the object remain valid until the
6455     // period of destruction ends.)
6456     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6457     return false;
6458   }
6459 
6460   // FIXME: Creating an APValue just to hold a nonexistent return value is
6461   // wasteful.
6462   APValue RetVal;
6463   StmtResult Ret = {RetVal, nullptr};
6464   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6465     return false;
6466 
6467   // A union destructor does not implicitly destroy its members.
6468   if (RD->isUnion())
6469     return true;
6470 
6471   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6472 
6473   // We don't have a good way to iterate fields in reverse, so collect all the
6474   // fields first and then walk them backwards.
6475   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6476   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6477     if (FD->isUnnamedBitfield())
6478       continue;
6479 
6480     LValue Subobject = This;
6481     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6482       return false;
6483 
6484     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6485     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6486                                FD->getType()))
6487       return false;
6488   }
6489 
6490   if (BasesLeft != 0)
6491     EvalObj.startedDestroyingBases();
6492 
6493   // Destroy base classes in reverse order.
6494   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6495     --BasesLeft;
6496 
6497     QualType BaseType = Base.getType();
6498     LValue Subobject = This;
6499     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6500                                 BaseType->getAsCXXRecordDecl(), &Layout))
6501       return false;
6502 
6503     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6504     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6505                                BaseType))
6506       return false;
6507   }
6508   assert(BasesLeft == 0 && "NumBases was wrong?");
6509 
6510   // The period of destruction ends now. The object is gone.
6511   Value = APValue();
6512   return true;
6513 }
6514 
6515 namespace {
6516 struct DestroyObjectHandler {
6517   EvalInfo &Info;
6518   const Expr *E;
6519   const LValue &This;
6520   const AccessKinds AccessKind;
6521 
6522   typedef bool result_type;
6523   bool failed() { return false; }
6524   bool found(APValue &Subobj, QualType SubobjType) {
6525     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6526                                  SubobjType);
6527   }
6528   bool found(APSInt &Value, QualType SubobjType) {
6529     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6530     return false;
6531   }
6532   bool found(APFloat &Value, QualType SubobjType) {
6533     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6534     return false;
6535   }
6536 };
6537 }
6538 
6539 /// Perform a destructor or pseudo-destructor call on the given object, which
6540 /// might in general not be a complete object.
6541 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6542                               const LValue &This, QualType ThisType) {
6543   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6544   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6545   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6546 }
6547 
6548 /// Destroy and end the lifetime of the given complete object.
6549 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6550                               APValue::LValueBase LVBase, APValue &Value,
6551                               QualType T) {
6552   // If we've had an unmodeled side-effect, we can't rely on mutable state
6553   // (such as the object we're about to destroy) being correct.
6554   if (Info.EvalStatus.HasSideEffects)
6555     return false;
6556 
6557   LValue LV;
6558   LV.set({LVBase});
6559   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6560 }
6561 
6562 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6563 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6564                                   LValue &Result) {
6565   if (Info.checkingPotentialConstantExpression() ||
6566       Info.SpeculativeEvaluationDepth)
6567     return false;
6568 
6569   // This is permitted only within a call to std::allocator<T>::allocate.
6570   auto Caller = Info.getStdAllocatorCaller("allocate");
6571   if (!Caller) {
6572     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6573                                      ? diag::note_constexpr_new_untyped
6574                                      : diag::note_constexpr_new);
6575     return false;
6576   }
6577 
6578   QualType ElemType = Caller.ElemType;
6579   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6580     Info.FFDiag(E->getExprLoc(),
6581                 diag::note_constexpr_new_not_complete_object_type)
6582         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6583     return false;
6584   }
6585 
6586   APSInt ByteSize;
6587   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6588     return false;
6589   bool IsNothrow = false;
6590   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6591     EvaluateIgnoredValue(Info, E->getArg(I));
6592     IsNothrow |= E->getType()->isNothrowT();
6593   }
6594 
6595   CharUnits ElemSize;
6596   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6597     return false;
6598   APInt Size, Remainder;
6599   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6600   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6601   if (Remainder != 0) {
6602     // This likely indicates a bug in the implementation of 'std::allocator'.
6603     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6604         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6605     return false;
6606   }
6607 
6608   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6609     if (IsNothrow) {
6610       Result.setNull(Info.Ctx, E->getType());
6611       return true;
6612     }
6613 
6614     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6615     return false;
6616   }
6617 
6618   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6619                                                      ArrayType::Normal, 0);
6620   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6621   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6622   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6623   return true;
6624 }
6625 
6626 static bool hasVirtualDestructor(QualType T) {
6627   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6628     if (CXXDestructorDecl *DD = RD->getDestructor())
6629       return DD->isVirtual();
6630   return false;
6631 }
6632 
6633 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6634   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6635     if (CXXDestructorDecl *DD = RD->getDestructor())
6636       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6637   return nullptr;
6638 }
6639 
6640 /// Check that the given object is a suitable pointer to a heap allocation that
6641 /// still exists and is of the right kind for the purpose of a deletion.
6642 ///
6643 /// On success, returns the heap allocation to deallocate. On failure, produces
6644 /// a diagnostic and returns None.
6645 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6646                                             const LValue &Pointer,
6647                                             DynAlloc::Kind DeallocKind) {
6648   auto PointerAsString = [&] {
6649     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6650   };
6651 
6652   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6653   if (!DA) {
6654     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6655         << PointerAsString();
6656     if (Pointer.Base)
6657       NoteLValueLocation(Info, Pointer.Base);
6658     return None;
6659   }
6660 
6661   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6662   if (!Alloc) {
6663     Info.FFDiag(E, diag::note_constexpr_double_delete);
6664     return None;
6665   }
6666 
6667   QualType AllocType = Pointer.Base.getDynamicAllocType();
6668   if (DeallocKind != (*Alloc)->getKind()) {
6669     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6670         << DeallocKind << (*Alloc)->getKind() << AllocType;
6671     NoteLValueLocation(Info, Pointer.Base);
6672     return None;
6673   }
6674 
6675   bool Subobject = false;
6676   if (DeallocKind == DynAlloc::New) {
6677     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6678                 Pointer.Designator.isOnePastTheEnd();
6679   } else {
6680     Subobject = Pointer.Designator.Entries.size() != 1 ||
6681                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6682   }
6683   if (Subobject) {
6684     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6685         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6686     return None;
6687   }
6688 
6689   return Alloc;
6690 }
6691 
6692 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6693 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6694   if (Info.checkingPotentialConstantExpression() ||
6695       Info.SpeculativeEvaluationDepth)
6696     return false;
6697 
6698   // This is permitted only within a call to std::allocator<T>::deallocate.
6699   if (!Info.getStdAllocatorCaller("deallocate")) {
6700     Info.FFDiag(E->getExprLoc());
6701     return true;
6702   }
6703 
6704   LValue Pointer;
6705   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6706     return false;
6707   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6708     EvaluateIgnoredValue(Info, E->getArg(I));
6709 
6710   if (Pointer.Designator.Invalid)
6711     return false;
6712 
6713   // Deleting a null pointer has no effect.
6714   if (Pointer.isNullPointer())
6715     return true;
6716 
6717   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6718     return false;
6719 
6720   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6721   return true;
6722 }
6723 
6724 //===----------------------------------------------------------------------===//
6725 // Generic Evaluation
6726 //===----------------------------------------------------------------------===//
6727 namespace {
6728 
6729 class BitCastBuffer {
6730   // FIXME: We're going to need bit-level granularity when we support
6731   // bit-fields.
6732   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6733   // we don't support a host or target where that is the case. Still, we should
6734   // use a more generic type in case we ever do.
6735   SmallVector<Optional<unsigned char>, 32> Bytes;
6736 
6737   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6738                 "Need at least 8 bit unsigned char");
6739 
6740   bool TargetIsLittleEndian;
6741 
6742 public:
6743   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6744       : Bytes(Width.getQuantity()),
6745         TargetIsLittleEndian(TargetIsLittleEndian) {}
6746 
6747   LLVM_NODISCARD
6748   bool readObject(CharUnits Offset, CharUnits Width,
6749                   SmallVectorImpl<unsigned char> &Output) const {
6750     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6751       // If a byte of an integer is uninitialized, then the whole integer is
6752       // uninitalized.
6753       if (!Bytes[I.getQuantity()])
6754         return false;
6755       Output.push_back(*Bytes[I.getQuantity()]);
6756     }
6757     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6758       std::reverse(Output.begin(), Output.end());
6759     return true;
6760   }
6761 
6762   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6763     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6764       std::reverse(Input.begin(), Input.end());
6765 
6766     size_t Index = 0;
6767     for (unsigned char Byte : Input) {
6768       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6769       Bytes[Offset.getQuantity() + Index] = Byte;
6770       ++Index;
6771     }
6772   }
6773 
6774   size_t size() { return Bytes.size(); }
6775 };
6776 
6777 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6778 /// target would represent the value at runtime.
6779 class APValueToBufferConverter {
6780   EvalInfo &Info;
6781   BitCastBuffer Buffer;
6782   const CastExpr *BCE;
6783 
6784   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6785                            const CastExpr *BCE)
6786       : Info(Info),
6787         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6788         BCE(BCE) {}
6789 
6790   bool visit(const APValue &Val, QualType Ty) {
6791     return visit(Val, Ty, CharUnits::fromQuantity(0));
6792   }
6793 
6794   // Write out Val with type Ty into Buffer starting at Offset.
6795   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6796     assert((size_t)Offset.getQuantity() <= Buffer.size());
6797 
6798     // As a special case, nullptr_t has an indeterminate value.
6799     if (Ty->isNullPtrType())
6800       return true;
6801 
6802     // Dig through Src to find the byte at SrcOffset.
6803     switch (Val.getKind()) {
6804     case APValue::Indeterminate:
6805     case APValue::None:
6806       return true;
6807 
6808     case APValue::Int:
6809       return visitInt(Val.getInt(), Ty, Offset);
6810     case APValue::Float:
6811       return visitFloat(Val.getFloat(), Ty, Offset);
6812     case APValue::Array:
6813       return visitArray(Val, Ty, Offset);
6814     case APValue::Struct:
6815       return visitRecord(Val, Ty, Offset);
6816 
6817     case APValue::ComplexInt:
6818     case APValue::ComplexFloat:
6819     case APValue::Vector:
6820     case APValue::FixedPoint:
6821       // FIXME: We should support these.
6822 
6823     case APValue::Union:
6824     case APValue::MemberPointer:
6825     case APValue::AddrLabelDiff: {
6826       Info.FFDiag(BCE->getBeginLoc(),
6827                   diag::note_constexpr_bit_cast_unsupported_type)
6828           << Ty;
6829       return false;
6830     }
6831 
6832     case APValue::LValue:
6833       llvm_unreachable("LValue subobject in bit_cast?");
6834     }
6835     llvm_unreachable("Unhandled APValue::ValueKind");
6836   }
6837 
6838   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6839     const RecordDecl *RD = Ty->getAsRecordDecl();
6840     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6841 
6842     // Visit the base classes.
6843     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6844       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6845         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6846         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6847 
6848         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6849                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6850           return false;
6851       }
6852     }
6853 
6854     // Visit the fields.
6855     unsigned FieldIdx = 0;
6856     for (FieldDecl *FD : RD->fields()) {
6857       if (FD->isBitField()) {
6858         Info.FFDiag(BCE->getBeginLoc(),
6859                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6860         return false;
6861       }
6862 
6863       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6864 
6865       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6866              "only bit-fields can have sub-char alignment");
6867       CharUnits FieldOffset =
6868           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6869       QualType FieldTy = FD->getType();
6870       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6871         return false;
6872       ++FieldIdx;
6873     }
6874 
6875     return true;
6876   }
6877 
6878   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6879     const auto *CAT =
6880         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6881     if (!CAT)
6882       return false;
6883 
6884     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6885     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6886     unsigned ArraySize = Val.getArraySize();
6887     // First, initialize the initialized elements.
6888     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6889       const APValue &SubObj = Val.getArrayInitializedElt(I);
6890       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6891         return false;
6892     }
6893 
6894     // Next, initialize the rest of the array using the filler.
6895     if (Val.hasArrayFiller()) {
6896       const APValue &Filler = Val.getArrayFiller();
6897       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6898         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6899           return false;
6900       }
6901     }
6902 
6903     return true;
6904   }
6905 
6906   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6907     APSInt AdjustedVal = Val;
6908     unsigned Width = AdjustedVal.getBitWidth();
6909     if (Ty->isBooleanType()) {
6910       Width = Info.Ctx.getTypeSize(Ty);
6911       AdjustedVal = AdjustedVal.extend(Width);
6912     }
6913 
6914     SmallVector<unsigned char, 8> Bytes(Width / 8);
6915     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6916     Buffer.writeObject(Offset, Bytes);
6917     return true;
6918   }
6919 
6920   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6921     APSInt AsInt(Val.bitcastToAPInt());
6922     return visitInt(AsInt, Ty, Offset);
6923   }
6924 
6925 public:
6926   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6927                                          const CastExpr *BCE) {
6928     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6929     APValueToBufferConverter Converter(Info, DstSize, BCE);
6930     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6931       return None;
6932     return Converter.Buffer;
6933   }
6934 };
6935 
6936 /// Write an BitCastBuffer into an APValue.
6937 class BufferToAPValueConverter {
6938   EvalInfo &Info;
6939   const BitCastBuffer &Buffer;
6940   const CastExpr *BCE;
6941 
6942   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6943                            const CastExpr *BCE)
6944       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6945 
6946   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6947   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6948   // Ideally this will be unreachable.
6949   llvm::NoneType unsupportedType(QualType Ty) {
6950     Info.FFDiag(BCE->getBeginLoc(),
6951                 diag::note_constexpr_bit_cast_unsupported_type)
6952         << Ty;
6953     return None;
6954   }
6955 
6956   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
6957     Info.FFDiag(BCE->getBeginLoc(),
6958                 diag::note_constexpr_bit_cast_unrepresentable_value)
6959         << Ty << Val.toString(/*Radix=*/10);
6960     return None;
6961   }
6962 
6963   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6964                           const EnumType *EnumSugar = nullptr) {
6965     if (T->isNullPtrType()) {
6966       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6967       return APValue((Expr *)nullptr,
6968                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6969                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6970     }
6971 
6972     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6973 
6974     // Work around floating point types that contain unused padding bytes. This
6975     // is really just `long double` on x86, which is the only fundamental type
6976     // with padding bytes.
6977     if (T->isRealFloatingType()) {
6978       const llvm::fltSemantics &Semantics =
6979           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6980       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
6981       assert(NumBits % 8 == 0);
6982       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
6983       if (NumBytes != SizeOf)
6984         SizeOf = NumBytes;
6985     }
6986 
6987     SmallVector<uint8_t, 8> Bytes;
6988     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6989       // If this is std::byte or unsigned char, then its okay to store an
6990       // indeterminate value.
6991       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6992       bool IsUChar =
6993           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6994                          T->isSpecificBuiltinType(BuiltinType::Char_U));
6995       if (!IsStdByte && !IsUChar) {
6996         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
6997         Info.FFDiag(BCE->getExprLoc(),
6998                     diag::note_constexpr_bit_cast_indet_dest)
6999             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7000         return None;
7001       }
7002 
7003       return APValue::IndeterminateValue();
7004     }
7005 
7006     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7007     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7008 
7009     if (T->isIntegralOrEnumerationType()) {
7010       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7011 
7012       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7013       if (IntWidth != Val.getBitWidth()) {
7014         APSInt Truncated = Val.trunc(IntWidth);
7015         if (Truncated.extend(Val.getBitWidth()) != Val)
7016           return unrepresentableValue(QualType(T, 0), Val);
7017         Val = Truncated;
7018       }
7019 
7020       return APValue(Val);
7021     }
7022 
7023     if (T->isRealFloatingType()) {
7024       const llvm::fltSemantics &Semantics =
7025           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7026       return APValue(APFloat(Semantics, Val));
7027     }
7028 
7029     return unsupportedType(QualType(T, 0));
7030   }
7031 
7032   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7033     const RecordDecl *RD = RTy->getAsRecordDecl();
7034     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7035 
7036     unsigned NumBases = 0;
7037     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7038       NumBases = CXXRD->getNumBases();
7039 
7040     APValue ResultVal(APValue::UninitStruct(), NumBases,
7041                       std::distance(RD->field_begin(), RD->field_end()));
7042 
7043     // Visit the base classes.
7044     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7045       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7046         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7047         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7048         if (BaseDecl->isEmpty() ||
7049             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7050           continue;
7051 
7052         Optional<APValue> SubObj = visitType(
7053             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7054         if (!SubObj)
7055           return None;
7056         ResultVal.getStructBase(I) = *SubObj;
7057       }
7058     }
7059 
7060     // Visit the fields.
7061     unsigned FieldIdx = 0;
7062     for (FieldDecl *FD : RD->fields()) {
7063       // FIXME: We don't currently support bit-fields. A lot of the logic for
7064       // this is in CodeGen, so we need to factor it around.
7065       if (FD->isBitField()) {
7066         Info.FFDiag(BCE->getBeginLoc(),
7067                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7068         return None;
7069       }
7070 
7071       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7072       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7073 
7074       CharUnits FieldOffset =
7075           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7076           Offset;
7077       QualType FieldTy = FD->getType();
7078       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7079       if (!SubObj)
7080         return None;
7081       ResultVal.getStructField(FieldIdx) = *SubObj;
7082       ++FieldIdx;
7083     }
7084 
7085     return ResultVal;
7086   }
7087 
7088   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7089     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7090     assert(!RepresentationType.isNull() &&
7091            "enum forward decl should be caught by Sema");
7092     const auto *AsBuiltin =
7093         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7094     // Recurse into the underlying type. Treat std::byte transparently as
7095     // unsigned char.
7096     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7097   }
7098 
7099   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7100     size_t Size = Ty->getSize().getLimitedValue();
7101     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7102 
7103     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7104     for (size_t I = 0; I != Size; ++I) {
7105       Optional<APValue> ElementValue =
7106           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7107       if (!ElementValue)
7108         return None;
7109       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7110     }
7111 
7112     return ArrayValue;
7113   }
7114 
7115   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7116     return unsupportedType(QualType(Ty, 0));
7117   }
7118 
7119   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7120     QualType Can = Ty.getCanonicalType();
7121 
7122     switch (Can->getTypeClass()) {
7123 #define TYPE(Class, Base)                                                      \
7124   case Type::Class:                                                            \
7125     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7126 #define ABSTRACT_TYPE(Class, Base)
7127 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7128   case Type::Class:                                                            \
7129     llvm_unreachable("non-canonical type should be impossible!");
7130 #define DEPENDENT_TYPE(Class, Base)                                            \
7131   case Type::Class:                                                            \
7132     llvm_unreachable(                                                          \
7133         "dependent types aren't supported in the constant evaluator!");
7134 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7135   case Type::Class:                                                            \
7136     llvm_unreachable("either dependent or not canonical!");
7137 #include "clang/AST/TypeNodes.inc"
7138     }
7139     llvm_unreachable("Unhandled Type::TypeClass");
7140   }
7141 
7142 public:
7143   // Pull out a full value of type DstType.
7144   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7145                                    const CastExpr *BCE) {
7146     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7147     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7148   }
7149 };
7150 
7151 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7152                                                  QualType Ty, EvalInfo *Info,
7153                                                  const ASTContext &Ctx,
7154                                                  bool CheckingDest) {
7155   Ty = Ty.getCanonicalType();
7156 
7157   auto diag = [&](int Reason) {
7158     if (Info)
7159       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7160           << CheckingDest << (Reason == 4) << Reason;
7161     return false;
7162   };
7163   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7164     if (Info)
7165       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7166           << NoteTy << Construct << Ty;
7167     return false;
7168   };
7169 
7170   if (Ty->isUnionType())
7171     return diag(0);
7172   if (Ty->isPointerType())
7173     return diag(1);
7174   if (Ty->isMemberPointerType())
7175     return diag(2);
7176   if (Ty.isVolatileQualified())
7177     return diag(3);
7178 
7179   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7180     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7181       for (CXXBaseSpecifier &BS : CXXRD->bases())
7182         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7183                                                   CheckingDest))
7184           return note(1, BS.getType(), BS.getBeginLoc());
7185     }
7186     for (FieldDecl *FD : Record->fields()) {
7187       if (FD->getType()->isReferenceType())
7188         return diag(4);
7189       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7190                                                 CheckingDest))
7191         return note(0, FD->getType(), FD->getBeginLoc());
7192     }
7193   }
7194 
7195   if (Ty->isArrayType() &&
7196       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7197                                             Info, Ctx, CheckingDest))
7198     return false;
7199 
7200   return true;
7201 }
7202 
7203 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7204                                              const ASTContext &Ctx,
7205                                              const CastExpr *BCE) {
7206   bool DestOK = checkBitCastConstexprEligibilityType(
7207       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7208   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7209                                 BCE->getBeginLoc(),
7210                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7211   return SourceOK;
7212 }
7213 
7214 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7215                                         APValue &SourceValue,
7216                                         const CastExpr *BCE) {
7217   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7218          "no host or target supports non 8-bit chars");
7219   assert(SourceValue.isLValue() &&
7220          "LValueToRValueBitcast requires an lvalue operand!");
7221 
7222   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7223     return false;
7224 
7225   LValue SourceLValue;
7226   APValue SourceRValue;
7227   SourceLValue.setFrom(Info.Ctx, SourceValue);
7228   if (!handleLValueToRValueConversion(
7229           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7230           SourceRValue, /*WantObjectRepresentation=*/true))
7231     return false;
7232 
7233   // Read out SourceValue into a char buffer.
7234   Optional<BitCastBuffer> Buffer =
7235       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7236   if (!Buffer)
7237     return false;
7238 
7239   // Write out the buffer into a new APValue.
7240   Optional<APValue> MaybeDestValue =
7241       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7242   if (!MaybeDestValue)
7243     return false;
7244 
7245   DestValue = std::move(*MaybeDestValue);
7246   return true;
7247 }
7248 
7249 template <class Derived>
7250 class ExprEvaluatorBase
7251   : public ConstStmtVisitor<Derived, bool> {
7252 private:
7253   Derived &getDerived() { return static_cast<Derived&>(*this); }
7254   bool DerivedSuccess(const APValue &V, const Expr *E) {
7255     return getDerived().Success(V, E);
7256   }
7257   bool DerivedZeroInitialization(const Expr *E) {
7258     return getDerived().ZeroInitialization(E);
7259   }
7260 
7261   // Check whether a conditional operator with a non-constant condition is a
7262   // potential constant expression. If neither arm is a potential constant
7263   // expression, then the conditional operator is not either.
7264   template<typename ConditionalOperator>
7265   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7266     assert(Info.checkingPotentialConstantExpression());
7267 
7268     // Speculatively evaluate both arms.
7269     SmallVector<PartialDiagnosticAt, 8> Diag;
7270     {
7271       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7272       StmtVisitorTy::Visit(E->getFalseExpr());
7273       if (Diag.empty())
7274         return;
7275     }
7276 
7277     {
7278       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7279       Diag.clear();
7280       StmtVisitorTy::Visit(E->getTrueExpr());
7281       if (Diag.empty())
7282         return;
7283     }
7284 
7285     Error(E, diag::note_constexpr_conditional_never_const);
7286   }
7287 
7288 
7289   template<typename ConditionalOperator>
7290   bool HandleConditionalOperator(const ConditionalOperator *E) {
7291     bool BoolResult;
7292     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7293       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7294         CheckPotentialConstantConditional(E);
7295         return false;
7296       }
7297       if (Info.noteFailure()) {
7298         StmtVisitorTy::Visit(E->getTrueExpr());
7299         StmtVisitorTy::Visit(E->getFalseExpr());
7300       }
7301       return false;
7302     }
7303 
7304     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7305     return StmtVisitorTy::Visit(EvalExpr);
7306   }
7307 
7308 protected:
7309   EvalInfo &Info;
7310   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7311   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7312 
7313   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7314     return Info.CCEDiag(E, D);
7315   }
7316 
7317   bool ZeroInitialization(const Expr *E) { return Error(E); }
7318 
7319 public:
7320   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7321 
7322   EvalInfo &getEvalInfo() { return Info; }
7323 
7324   /// Report an evaluation error. This should only be called when an error is
7325   /// first discovered. When propagating an error, just return false.
7326   bool Error(const Expr *E, diag::kind D) {
7327     Info.FFDiag(E, D);
7328     return false;
7329   }
7330   bool Error(const Expr *E) {
7331     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7332   }
7333 
7334   bool VisitStmt(const Stmt *) {
7335     llvm_unreachable("Expression evaluator should not be called on stmts");
7336   }
7337   bool VisitExpr(const Expr *E) {
7338     return Error(E);
7339   }
7340 
7341   bool VisitConstantExpr(const ConstantExpr *E) {
7342     if (E->hasAPValueResult())
7343       return DerivedSuccess(E->getAPValueResult(), E);
7344 
7345     return StmtVisitorTy::Visit(E->getSubExpr());
7346   }
7347 
7348   bool VisitParenExpr(const ParenExpr *E)
7349     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7350   bool VisitUnaryExtension(const UnaryOperator *E)
7351     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7352   bool VisitUnaryPlus(const UnaryOperator *E)
7353     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7354   bool VisitChooseExpr(const ChooseExpr *E)
7355     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7356   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7357     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7358   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7359     { return StmtVisitorTy::Visit(E->getReplacement()); }
7360   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7361     TempVersionRAII RAII(*Info.CurrentCall);
7362     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7363     return StmtVisitorTy::Visit(E->getExpr());
7364   }
7365   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7366     TempVersionRAII RAII(*Info.CurrentCall);
7367     // The initializer may not have been parsed yet, or might be erroneous.
7368     if (!E->getExpr())
7369       return Error(E);
7370     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7371     return StmtVisitorTy::Visit(E->getExpr());
7372   }
7373 
7374   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7375     FullExpressionRAII Scope(Info);
7376     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7377   }
7378 
7379   // Temporaries are registered when created, so we don't care about
7380   // CXXBindTemporaryExpr.
7381   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7382     return StmtVisitorTy::Visit(E->getSubExpr());
7383   }
7384 
7385   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7386     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7387     return static_cast<Derived*>(this)->VisitCastExpr(E);
7388   }
7389   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7390     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7391       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7392     return static_cast<Derived*>(this)->VisitCastExpr(E);
7393   }
7394   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7395     return static_cast<Derived*>(this)->VisitCastExpr(E);
7396   }
7397 
7398   bool VisitBinaryOperator(const BinaryOperator *E) {
7399     switch (E->getOpcode()) {
7400     default:
7401       return Error(E);
7402 
7403     case BO_Comma:
7404       VisitIgnoredValue(E->getLHS());
7405       return StmtVisitorTy::Visit(E->getRHS());
7406 
7407     case BO_PtrMemD:
7408     case BO_PtrMemI: {
7409       LValue Obj;
7410       if (!HandleMemberPointerAccess(Info, E, Obj))
7411         return false;
7412       APValue Result;
7413       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7414         return false;
7415       return DerivedSuccess(Result, E);
7416     }
7417     }
7418   }
7419 
7420   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7421     return StmtVisitorTy::Visit(E->getSemanticForm());
7422   }
7423 
7424   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7425     // Evaluate and cache the common expression. We treat it as a temporary,
7426     // even though it's not quite the same thing.
7427     LValue CommonLV;
7428     if (!Evaluate(Info.CurrentCall->createTemporary(
7429                       E->getOpaqueValue(),
7430                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7431                       ScopeKind::FullExpression, CommonLV),
7432                   Info, E->getCommon()))
7433       return false;
7434 
7435     return HandleConditionalOperator(E);
7436   }
7437 
7438   bool VisitConditionalOperator(const ConditionalOperator *E) {
7439     bool IsBcpCall = false;
7440     // If the condition (ignoring parens) is a __builtin_constant_p call,
7441     // the result is a constant expression if it can be folded without
7442     // side-effects. This is an important GNU extension. See GCC PR38377
7443     // for discussion.
7444     if (const CallExpr *CallCE =
7445           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7446       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7447         IsBcpCall = true;
7448 
7449     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7450     // constant expression; we can't check whether it's potentially foldable.
7451     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7452     // it would return 'false' in this mode.
7453     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7454       return false;
7455 
7456     FoldConstant Fold(Info, IsBcpCall);
7457     if (!HandleConditionalOperator(E)) {
7458       Fold.keepDiagnostics();
7459       return false;
7460     }
7461 
7462     return true;
7463   }
7464 
7465   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7466     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7467       return DerivedSuccess(*Value, E);
7468 
7469     const Expr *Source = E->getSourceExpr();
7470     if (!Source)
7471       return Error(E);
7472     if (Source == E) { // sanity checking.
7473       assert(0 && "OpaqueValueExpr recursively refers to itself");
7474       return Error(E);
7475     }
7476     return StmtVisitorTy::Visit(Source);
7477   }
7478 
7479   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7480     for (const Expr *SemE : E->semantics()) {
7481       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7482         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7483         // result expression: there could be two different LValues that would
7484         // refer to the same object in that case, and we can't model that.
7485         if (SemE == E->getResultExpr())
7486           return Error(E);
7487 
7488         // Unique OVEs get evaluated if and when we encounter them when
7489         // emitting the rest of the semantic form, rather than eagerly.
7490         if (OVE->isUnique())
7491           continue;
7492 
7493         LValue LV;
7494         if (!Evaluate(Info.CurrentCall->createTemporary(
7495                           OVE, getStorageType(Info.Ctx, OVE),
7496                           ScopeKind::FullExpression, LV),
7497                       Info, OVE->getSourceExpr()))
7498           return false;
7499       } else if (SemE == E->getResultExpr()) {
7500         if (!StmtVisitorTy::Visit(SemE))
7501           return false;
7502       } else {
7503         if (!EvaluateIgnoredValue(Info, SemE))
7504           return false;
7505       }
7506     }
7507     return true;
7508   }
7509 
7510   bool VisitCallExpr(const CallExpr *E) {
7511     APValue Result;
7512     if (!handleCallExpr(E, Result, nullptr))
7513       return false;
7514     return DerivedSuccess(Result, E);
7515   }
7516 
7517   bool handleCallExpr(const CallExpr *E, APValue &Result,
7518                      const LValue *ResultSlot) {
7519     CallScopeRAII CallScope(Info);
7520 
7521     const Expr *Callee = E->getCallee()->IgnoreParens();
7522     QualType CalleeType = Callee->getType();
7523 
7524     const FunctionDecl *FD = nullptr;
7525     LValue *This = nullptr, ThisVal;
7526     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7527     bool HasQualifier = false;
7528 
7529     CallRef Call;
7530 
7531     // Extract function decl and 'this' pointer from the callee.
7532     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7533       const CXXMethodDecl *Member = nullptr;
7534       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7535         // Explicit bound member calls, such as x.f() or p->g();
7536         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7537           return false;
7538         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7539         if (!Member)
7540           return Error(Callee);
7541         This = &ThisVal;
7542         HasQualifier = ME->hasQualifier();
7543       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7544         // Indirect bound member calls ('.*' or '->*').
7545         const ValueDecl *D =
7546             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7547         if (!D)
7548           return false;
7549         Member = dyn_cast<CXXMethodDecl>(D);
7550         if (!Member)
7551           return Error(Callee);
7552         This = &ThisVal;
7553       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7554         if (!Info.getLangOpts().CPlusPlus20)
7555           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7556         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7557                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7558       } else
7559         return Error(Callee);
7560       FD = Member;
7561     } else if (CalleeType->isFunctionPointerType()) {
7562       LValue CalleeLV;
7563       if (!EvaluatePointer(Callee, CalleeLV, Info))
7564         return false;
7565 
7566       if (!CalleeLV.getLValueOffset().isZero())
7567         return Error(Callee);
7568       FD = dyn_cast_or_null<FunctionDecl>(
7569           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7570       if (!FD)
7571         return Error(Callee);
7572       // Don't call function pointers which have been cast to some other type.
7573       // Per DR (no number yet), the caller and callee can differ in noexcept.
7574       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7575         CalleeType->getPointeeType(), FD->getType())) {
7576         return Error(E);
7577       }
7578 
7579       // For an (overloaded) assignment expression, evaluate the RHS before the
7580       // LHS.
7581       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7582       if (OCE && OCE->isAssignmentOp()) {
7583         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7584         Call = Info.CurrentCall->createCall(FD);
7585         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7586                           Info, FD, /*RightToLeft=*/true))
7587           return false;
7588       }
7589 
7590       // Overloaded operator calls to member functions are represented as normal
7591       // calls with '*this' as the first argument.
7592       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7593       if (MD && !MD->isStatic()) {
7594         // FIXME: When selecting an implicit conversion for an overloaded
7595         // operator delete, we sometimes try to evaluate calls to conversion
7596         // operators without a 'this' parameter!
7597         if (Args.empty())
7598           return Error(E);
7599 
7600         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7601           return false;
7602         This = &ThisVal;
7603         Args = Args.slice(1);
7604       } else if (MD && MD->isLambdaStaticInvoker()) {
7605         // Map the static invoker for the lambda back to the call operator.
7606         // Conveniently, we don't have to slice out the 'this' argument (as is
7607         // being done for the non-static case), since a static member function
7608         // doesn't have an implicit argument passed in.
7609         const CXXRecordDecl *ClosureClass = MD->getParent();
7610         assert(
7611             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7612             "Number of captures must be zero for conversion to function-ptr");
7613 
7614         const CXXMethodDecl *LambdaCallOp =
7615             ClosureClass->getLambdaCallOperator();
7616 
7617         // Set 'FD', the function that will be called below, to the call
7618         // operator.  If the closure object represents a generic lambda, find
7619         // the corresponding specialization of the call operator.
7620 
7621         if (ClosureClass->isGenericLambda()) {
7622           assert(MD->isFunctionTemplateSpecialization() &&
7623                  "A generic lambda's static-invoker function must be a "
7624                  "template specialization");
7625           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7626           FunctionTemplateDecl *CallOpTemplate =
7627               LambdaCallOp->getDescribedFunctionTemplate();
7628           void *InsertPos = nullptr;
7629           FunctionDecl *CorrespondingCallOpSpecialization =
7630               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7631           assert(CorrespondingCallOpSpecialization &&
7632                  "We must always have a function call operator specialization "
7633                  "that corresponds to our static invoker specialization");
7634           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7635         } else
7636           FD = LambdaCallOp;
7637       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7638         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7639             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7640           LValue Ptr;
7641           if (!HandleOperatorNewCall(Info, E, Ptr))
7642             return false;
7643           Ptr.moveInto(Result);
7644           return CallScope.destroy();
7645         } else {
7646           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7647         }
7648       }
7649     } else
7650       return Error(E);
7651 
7652     // Evaluate the arguments now if we've not already done so.
7653     if (!Call) {
7654       Call = Info.CurrentCall->createCall(FD);
7655       if (!EvaluateArgs(Args, Call, Info, FD))
7656         return false;
7657     }
7658 
7659     SmallVector<QualType, 4> CovariantAdjustmentPath;
7660     if (This) {
7661       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7662       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7663         // Perform virtual dispatch, if necessary.
7664         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7665                                    CovariantAdjustmentPath);
7666         if (!FD)
7667           return false;
7668       } else {
7669         // Check that the 'this' pointer points to an object of the right type.
7670         // FIXME: If this is an assignment operator call, we may need to change
7671         // the active union member before we check this.
7672         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7673           return false;
7674       }
7675     }
7676 
7677     // Destructor calls are different enough that they have their own codepath.
7678     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7679       assert(This && "no 'this' pointer for destructor call");
7680       return HandleDestruction(Info, E, *This,
7681                                Info.Ctx.getRecordType(DD->getParent())) &&
7682              CallScope.destroy();
7683     }
7684 
7685     const FunctionDecl *Definition = nullptr;
7686     Stmt *Body = FD->getBody(Definition);
7687 
7688     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7689         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7690                             Body, Info, Result, ResultSlot))
7691       return false;
7692 
7693     if (!CovariantAdjustmentPath.empty() &&
7694         !HandleCovariantReturnAdjustment(Info, E, Result,
7695                                          CovariantAdjustmentPath))
7696       return false;
7697 
7698     return CallScope.destroy();
7699   }
7700 
7701   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7702     return StmtVisitorTy::Visit(E->getInitializer());
7703   }
7704   bool VisitInitListExpr(const InitListExpr *E) {
7705     if (E->getNumInits() == 0)
7706       return DerivedZeroInitialization(E);
7707     if (E->getNumInits() == 1)
7708       return StmtVisitorTy::Visit(E->getInit(0));
7709     return Error(E);
7710   }
7711   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7712     return DerivedZeroInitialization(E);
7713   }
7714   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7715     return DerivedZeroInitialization(E);
7716   }
7717   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7718     return DerivedZeroInitialization(E);
7719   }
7720 
7721   /// A member expression where the object is a prvalue is itself a prvalue.
7722   bool VisitMemberExpr(const MemberExpr *E) {
7723     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7724            "missing temporary materialization conversion");
7725     assert(!E->isArrow() && "missing call to bound member function?");
7726 
7727     APValue Val;
7728     if (!Evaluate(Val, Info, E->getBase()))
7729       return false;
7730 
7731     QualType BaseTy = E->getBase()->getType();
7732 
7733     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7734     if (!FD) return Error(E);
7735     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7736     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7737            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7738 
7739     // Note: there is no lvalue base here. But this case should only ever
7740     // happen in C or in C++98, where we cannot be evaluating a constexpr
7741     // constructor, which is the only case the base matters.
7742     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7743     SubobjectDesignator Designator(BaseTy);
7744     Designator.addDeclUnchecked(FD);
7745 
7746     APValue Result;
7747     return extractSubobject(Info, E, Obj, Designator, Result) &&
7748            DerivedSuccess(Result, E);
7749   }
7750 
7751   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7752     APValue Val;
7753     if (!Evaluate(Val, Info, E->getBase()))
7754       return false;
7755 
7756     if (Val.isVector()) {
7757       SmallVector<uint32_t, 4> Indices;
7758       E->getEncodedElementAccess(Indices);
7759       if (Indices.size() == 1) {
7760         // Return scalar.
7761         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7762       } else {
7763         // Construct new APValue vector.
7764         SmallVector<APValue, 4> Elts;
7765         for (unsigned I = 0; I < Indices.size(); ++I) {
7766           Elts.push_back(Val.getVectorElt(Indices[I]));
7767         }
7768         APValue VecResult(Elts.data(), Indices.size());
7769         return DerivedSuccess(VecResult, E);
7770       }
7771     }
7772 
7773     return false;
7774   }
7775 
7776   bool VisitCastExpr(const CastExpr *E) {
7777     switch (E->getCastKind()) {
7778     default:
7779       break;
7780 
7781     case CK_AtomicToNonAtomic: {
7782       APValue AtomicVal;
7783       // This does not need to be done in place even for class/array types:
7784       // atomic-to-non-atomic conversion implies copying the object
7785       // representation.
7786       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7787         return false;
7788       return DerivedSuccess(AtomicVal, E);
7789     }
7790 
7791     case CK_NoOp:
7792     case CK_UserDefinedConversion:
7793       return StmtVisitorTy::Visit(E->getSubExpr());
7794 
7795     case CK_LValueToRValue: {
7796       LValue LVal;
7797       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7798         return false;
7799       APValue RVal;
7800       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7801       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7802                                           LVal, RVal))
7803         return false;
7804       return DerivedSuccess(RVal, E);
7805     }
7806     case CK_LValueToRValueBitCast: {
7807       APValue DestValue, SourceValue;
7808       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7809         return false;
7810       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7811         return false;
7812       return DerivedSuccess(DestValue, E);
7813     }
7814 
7815     case CK_AddressSpaceConversion: {
7816       APValue Value;
7817       if (!Evaluate(Value, Info, E->getSubExpr()))
7818         return false;
7819       return DerivedSuccess(Value, E);
7820     }
7821     }
7822 
7823     return Error(E);
7824   }
7825 
7826   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7827     return VisitUnaryPostIncDec(UO);
7828   }
7829   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7830     return VisitUnaryPostIncDec(UO);
7831   }
7832   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7833     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7834       return Error(UO);
7835 
7836     LValue LVal;
7837     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7838       return false;
7839     APValue RVal;
7840     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7841                       UO->isIncrementOp(), &RVal))
7842       return false;
7843     return DerivedSuccess(RVal, UO);
7844   }
7845 
7846   bool VisitStmtExpr(const StmtExpr *E) {
7847     // We will have checked the full-expressions inside the statement expression
7848     // when they were completed, and don't need to check them again now.
7849     if (Info.checkingForUndefinedBehavior())
7850       return Error(E);
7851 
7852     const CompoundStmt *CS = E->getSubStmt();
7853     if (CS->body_empty())
7854       return true;
7855 
7856     BlockScopeRAII Scope(Info);
7857     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7858                                            BE = CS->body_end();
7859          /**/; ++BI) {
7860       if (BI + 1 == BE) {
7861         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7862         if (!FinalExpr) {
7863           Info.FFDiag((*BI)->getBeginLoc(),
7864                       diag::note_constexpr_stmt_expr_unsupported);
7865           return false;
7866         }
7867         return this->Visit(FinalExpr) && Scope.destroy();
7868       }
7869 
7870       APValue ReturnValue;
7871       StmtResult Result = { ReturnValue, nullptr };
7872       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7873       if (ESR != ESR_Succeeded) {
7874         // FIXME: If the statement-expression terminated due to 'return',
7875         // 'break', or 'continue', it would be nice to propagate that to
7876         // the outer statement evaluation rather than bailing out.
7877         if (ESR != ESR_Failed)
7878           Info.FFDiag((*BI)->getBeginLoc(),
7879                       diag::note_constexpr_stmt_expr_unsupported);
7880         return false;
7881       }
7882     }
7883 
7884     llvm_unreachable("Return from function from the loop above.");
7885   }
7886 
7887   /// Visit a value which is evaluated, but whose value is ignored.
7888   void VisitIgnoredValue(const Expr *E) {
7889     EvaluateIgnoredValue(Info, E);
7890   }
7891 
7892   /// Potentially visit a MemberExpr's base expression.
7893   void VisitIgnoredBaseExpression(const Expr *E) {
7894     // While MSVC doesn't evaluate the base expression, it does diagnose the
7895     // presence of side-effecting behavior.
7896     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7897       return;
7898     VisitIgnoredValue(E);
7899   }
7900 };
7901 
7902 } // namespace
7903 
7904 //===----------------------------------------------------------------------===//
7905 // Common base class for lvalue and temporary evaluation.
7906 //===----------------------------------------------------------------------===//
7907 namespace {
7908 template<class Derived>
7909 class LValueExprEvaluatorBase
7910   : public ExprEvaluatorBase<Derived> {
7911 protected:
7912   LValue &Result;
7913   bool InvalidBaseOK;
7914   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7915   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7916 
7917   bool Success(APValue::LValueBase B) {
7918     Result.set(B);
7919     return true;
7920   }
7921 
7922   bool evaluatePointer(const Expr *E, LValue &Result) {
7923     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7924   }
7925 
7926 public:
7927   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7928       : ExprEvaluatorBaseTy(Info), Result(Result),
7929         InvalidBaseOK(InvalidBaseOK) {}
7930 
7931   bool Success(const APValue &V, const Expr *E) {
7932     Result.setFrom(this->Info.Ctx, V);
7933     return true;
7934   }
7935 
7936   bool VisitMemberExpr(const MemberExpr *E) {
7937     // Handle non-static data members.
7938     QualType BaseTy;
7939     bool EvalOK;
7940     if (E->isArrow()) {
7941       EvalOK = evaluatePointer(E->getBase(), Result);
7942       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7943     } else if (E->getBase()->isRValue()) {
7944       assert(E->getBase()->getType()->isRecordType());
7945       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7946       BaseTy = E->getBase()->getType();
7947     } else {
7948       EvalOK = this->Visit(E->getBase());
7949       BaseTy = E->getBase()->getType();
7950     }
7951     if (!EvalOK) {
7952       if (!InvalidBaseOK)
7953         return false;
7954       Result.setInvalid(E);
7955       return true;
7956     }
7957 
7958     const ValueDecl *MD = E->getMemberDecl();
7959     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7960       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7961              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7962       (void)BaseTy;
7963       if (!HandleLValueMember(this->Info, E, Result, FD))
7964         return false;
7965     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7966       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7967         return false;
7968     } else
7969       return this->Error(E);
7970 
7971     if (MD->getType()->isReferenceType()) {
7972       APValue RefValue;
7973       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7974                                           RefValue))
7975         return false;
7976       return Success(RefValue, E);
7977     }
7978     return true;
7979   }
7980 
7981   bool VisitBinaryOperator(const BinaryOperator *E) {
7982     switch (E->getOpcode()) {
7983     default:
7984       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7985 
7986     case BO_PtrMemD:
7987     case BO_PtrMemI:
7988       return HandleMemberPointerAccess(this->Info, E, Result);
7989     }
7990   }
7991 
7992   bool VisitCastExpr(const CastExpr *E) {
7993     switch (E->getCastKind()) {
7994     default:
7995       return ExprEvaluatorBaseTy::VisitCastExpr(E);
7996 
7997     case CK_DerivedToBase:
7998     case CK_UncheckedDerivedToBase:
7999       if (!this->Visit(E->getSubExpr()))
8000         return false;
8001 
8002       // Now figure out the necessary offset to add to the base LV to get from
8003       // the derived class to the base class.
8004       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8005                                   Result);
8006     }
8007   }
8008 };
8009 }
8010 
8011 //===----------------------------------------------------------------------===//
8012 // LValue Evaluation
8013 //
8014 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8015 // function designators (in C), decl references to void objects (in C), and
8016 // temporaries (if building with -Wno-address-of-temporary).
8017 //
8018 // LValue evaluation produces values comprising a base expression of one of the
8019 // following types:
8020 // - Declarations
8021 //  * VarDecl
8022 //  * FunctionDecl
8023 // - Literals
8024 //  * CompoundLiteralExpr in C (and in global scope in C++)
8025 //  * StringLiteral
8026 //  * PredefinedExpr
8027 //  * ObjCStringLiteralExpr
8028 //  * ObjCEncodeExpr
8029 //  * AddrLabelExpr
8030 //  * BlockExpr
8031 //  * CallExpr for a MakeStringConstant builtin
8032 // - typeid(T) expressions, as TypeInfoLValues
8033 // - Locals and temporaries
8034 //  * MaterializeTemporaryExpr
8035 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8036 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8037 //    from the AST (FIXME).
8038 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8039 //    CallIndex, for a lifetime-extended temporary.
8040 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8041 //    immediate invocation.
8042 // plus an offset in bytes.
8043 //===----------------------------------------------------------------------===//
8044 namespace {
8045 class LValueExprEvaluator
8046   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8047 public:
8048   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8049     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8050 
8051   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8052   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8053 
8054   bool VisitDeclRefExpr(const DeclRefExpr *E);
8055   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8056   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8057   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8058   bool VisitMemberExpr(const MemberExpr *E);
8059   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8060   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8061   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8062   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8063   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8064   bool VisitUnaryDeref(const UnaryOperator *E);
8065   bool VisitUnaryReal(const UnaryOperator *E);
8066   bool VisitUnaryImag(const UnaryOperator *E);
8067   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8068     return VisitUnaryPreIncDec(UO);
8069   }
8070   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8071     return VisitUnaryPreIncDec(UO);
8072   }
8073   bool VisitBinAssign(const BinaryOperator *BO);
8074   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8075 
8076   bool VisitCastExpr(const CastExpr *E) {
8077     switch (E->getCastKind()) {
8078     default:
8079       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8080 
8081     case CK_LValueBitCast:
8082       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8083       if (!Visit(E->getSubExpr()))
8084         return false;
8085       Result.Designator.setInvalid();
8086       return true;
8087 
8088     case CK_BaseToDerived:
8089       if (!Visit(E->getSubExpr()))
8090         return false;
8091       return HandleBaseToDerivedCast(Info, E, Result);
8092 
8093     case CK_Dynamic:
8094       if (!Visit(E->getSubExpr()))
8095         return false;
8096       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8097     }
8098   }
8099 };
8100 } // end anonymous namespace
8101 
8102 /// Evaluate an expression as an lvalue. This can be legitimately called on
8103 /// expressions which are not glvalues, in three cases:
8104 ///  * function designators in C, and
8105 ///  * "extern void" objects
8106 ///  * @selector() expressions in Objective-C
8107 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8108                            bool InvalidBaseOK) {
8109   assert(!E->isValueDependent());
8110   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8111          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8112   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8113 }
8114 
8115 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8116   const NamedDecl *D = E->getDecl();
8117   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D))
8118     return Success(cast<ValueDecl>(D));
8119   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8120     return VisitVarDecl(E, VD);
8121   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8122     return Visit(BD->getBinding());
8123   return Error(E);
8124 }
8125 
8126 
8127 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8128 
8129   // If we are within a lambda's call operator, check whether the 'VD' referred
8130   // to within 'E' actually represents a lambda-capture that maps to a
8131   // data-member/field within the closure object, and if so, evaluate to the
8132   // field or what the field refers to.
8133   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8134       isa<DeclRefExpr>(E) &&
8135       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8136     // We don't always have a complete capture-map when checking or inferring if
8137     // the function call operator meets the requirements of a constexpr function
8138     // - but we don't need to evaluate the captures to determine constexprness
8139     // (dcl.constexpr C++17).
8140     if (Info.checkingPotentialConstantExpression())
8141       return false;
8142 
8143     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8144       // Start with 'Result' referring to the complete closure object...
8145       Result = *Info.CurrentCall->This;
8146       // ... then update it to refer to the field of the closure object
8147       // that represents the capture.
8148       if (!HandleLValueMember(Info, E, Result, FD))
8149         return false;
8150       // And if the field is of reference type, update 'Result' to refer to what
8151       // the field refers to.
8152       if (FD->getType()->isReferenceType()) {
8153         APValue RVal;
8154         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8155                                             RVal))
8156           return false;
8157         Result.setFrom(Info.Ctx, RVal);
8158       }
8159       return true;
8160     }
8161   }
8162 
8163   CallStackFrame *Frame = nullptr;
8164   unsigned Version = 0;
8165   if (VD->hasLocalStorage()) {
8166     // Only if a local variable was declared in the function currently being
8167     // evaluated, do we expect to be able to find its value in the current
8168     // frame. (Otherwise it was likely declared in an enclosing context and
8169     // could either have a valid evaluatable value (for e.g. a constexpr
8170     // variable) or be ill-formed (and trigger an appropriate evaluation
8171     // diagnostic)).
8172     CallStackFrame *CurrFrame = Info.CurrentCall;
8173     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8174       // Function parameters are stored in some caller's frame. (Usually the
8175       // immediate caller, but for an inherited constructor they may be more
8176       // distant.)
8177       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8178         if (CurrFrame->Arguments) {
8179           VD = CurrFrame->Arguments.getOrigParam(PVD);
8180           Frame =
8181               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8182           Version = CurrFrame->Arguments.Version;
8183         }
8184       } else {
8185         Frame = CurrFrame;
8186         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8187       }
8188     }
8189   }
8190 
8191   if (!VD->getType()->isReferenceType()) {
8192     if (Frame) {
8193       Result.set({VD, Frame->Index, Version});
8194       return true;
8195     }
8196     return Success(VD);
8197   }
8198 
8199   if (!Info.getLangOpts().CPlusPlus11) {
8200     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8201         << VD << VD->getType();
8202     Info.Note(VD->getLocation(), diag::note_declared_at);
8203   }
8204 
8205   APValue *V;
8206   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8207     return false;
8208   if (!V->hasValue()) {
8209     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8210     // adjust the diagnostic to say that.
8211     if (!Info.checkingPotentialConstantExpression())
8212       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8213     return false;
8214   }
8215   return Success(*V, E);
8216 }
8217 
8218 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8219     const MaterializeTemporaryExpr *E) {
8220   // Walk through the expression to find the materialized temporary itself.
8221   SmallVector<const Expr *, 2> CommaLHSs;
8222   SmallVector<SubobjectAdjustment, 2> Adjustments;
8223   const Expr *Inner =
8224       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8225 
8226   // If we passed any comma operators, evaluate their LHSs.
8227   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8228     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8229       return false;
8230 
8231   // A materialized temporary with static storage duration can appear within the
8232   // result of a constant expression evaluation, so we need to preserve its
8233   // value for use outside this evaluation.
8234   APValue *Value;
8235   if (E->getStorageDuration() == SD_Static) {
8236     // FIXME: What about SD_Thread?
8237     Value = E->getOrCreateValue(true);
8238     *Value = APValue();
8239     Result.set(E);
8240   } else {
8241     Value = &Info.CurrentCall->createTemporary(
8242         E, E->getType(),
8243         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8244                                                      : ScopeKind::Block,
8245         Result);
8246   }
8247 
8248   QualType Type = Inner->getType();
8249 
8250   // Materialize the temporary itself.
8251   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8252     *Value = APValue();
8253     return false;
8254   }
8255 
8256   // Adjust our lvalue to refer to the desired subobject.
8257   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8258     --I;
8259     switch (Adjustments[I].Kind) {
8260     case SubobjectAdjustment::DerivedToBaseAdjustment:
8261       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8262                                 Type, Result))
8263         return false;
8264       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8265       break;
8266 
8267     case SubobjectAdjustment::FieldAdjustment:
8268       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8269         return false;
8270       Type = Adjustments[I].Field->getType();
8271       break;
8272 
8273     case SubobjectAdjustment::MemberPointerAdjustment:
8274       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8275                                      Adjustments[I].Ptr.RHS))
8276         return false;
8277       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8278       break;
8279     }
8280   }
8281 
8282   return true;
8283 }
8284 
8285 bool
8286 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8287   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8288          "lvalue compound literal in c++?");
8289   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8290   // only see this when folding in C, so there's no standard to follow here.
8291   return Success(E);
8292 }
8293 
8294 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8295   TypeInfoLValue TypeInfo;
8296 
8297   if (!E->isPotentiallyEvaluated()) {
8298     if (E->isTypeOperand())
8299       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8300     else
8301       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8302   } else {
8303     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8304       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8305         << E->getExprOperand()->getType()
8306         << E->getExprOperand()->getSourceRange();
8307     }
8308 
8309     if (!Visit(E->getExprOperand()))
8310       return false;
8311 
8312     Optional<DynamicType> DynType =
8313         ComputeDynamicType(Info, E, Result, AK_TypeId);
8314     if (!DynType)
8315       return false;
8316 
8317     TypeInfo =
8318         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8319   }
8320 
8321   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8322 }
8323 
8324 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8325   return Success(E->getGuidDecl());
8326 }
8327 
8328 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8329   // Handle static data members.
8330   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8331     VisitIgnoredBaseExpression(E->getBase());
8332     return VisitVarDecl(E, VD);
8333   }
8334 
8335   // Handle static member functions.
8336   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8337     if (MD->isStatic()) {
8338       VisitIgnoredBaseExpression(E->getBase());
8339       return Success(MD);
8340     }
8341   }
8342 
8343   // Handle non-static data members.
8344   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8345 }
8346 
8347 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8348   // FIXME: Deal with vectors as array subscript bases.
8349   if (E->getBase()->getType()->isVectorType())
8350     return Error(E);
8351 
8352   APSInt Index;
8353   bool Success = true;
8354 
8355   // C++17's rules require us to evaluate the LHS first, regardless of which
8356   // side is the base.
8357   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8358     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8359                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8360       if (!Info.noteFailure())
8361         return false;
8362       Success = false;
8363     }
8364   }
8365 
8366   return Success &&
8367          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8368 }
8369 
8370 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8371   return evaluatePointer(E->getSubExpr(), Result);
8372 }
8373 
8374 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8375   if (!Visit(E->getSubExpr()))
8376     return false;
8377   // __real is a no-op on scalar lvalues.
8378   if (E->getSubExpr()->getType()->isAnyComplexType())
8379     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8380   return true;
8381 }
8382 
8383 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8384   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8385          "lvalue __imag__ on scalar?");
8386   if (!Visit(E->getSubExpr()))
8387     return false;
8388   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8389   return true;
8390 }
8391 
8392 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8393   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8394     return Error(UO);
8395 
8396   if (!this->Visit(UO->getSubExpr()))
8397     return false;
8398 
8399   return handleIncDec(
8400       this->Info, UO, Result, UO->getSubExpr()->getType(),
8401       UO->isIncrementOp(), nullptr);
8402 }
8403 
8404 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8405     const CompoundAssignOperator *CAO) {
8406   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8407     return Error(CAO);
8408 
8409   bool Success = true;
8410 
8411   // C++17 onwards require that we evaluate the RHS first.
8412   APValue RHS;
8413   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8414     if (!Info.noteFailure())
8415       return false;
8416     Success = false;
8417   }
8418 
8419   // The overall lvalue result is the result of evaluating the LHS.
8420   if (!this->Visit(CAO->getLHS()) || !Success)
8421     return false;
8422 
8423   return handleCompoundAssignment(
8424       this->Info, CAO,
8425       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8426       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8427 }
8428 
8429 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8430   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8431     return Error(E);
8432 
8433   bool Success = true;
8434 
8435   // C++17 onwards require that we evaluate the RHS first.
8436   APValue NewVal;
8437   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8438     if (!Info.noteFailure())
8439       return false;
8440     Success = false;
8441   }
8442 
8443   if (!this->Visit(E->getLHS()) || !Success)
8444     return false;
8445 
8446   if (Info.getLangOpts().CPlusPlus20 &&
8447       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8448     return false;
8449 
8450   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8451                           NewVal);
8452 }
8453 
8454 //===----------------------------------------------------------------------===//
8455 // Pointer Evaluation
8456 //===----------------------------------------------------------------------===//
8457 
8458 /// Attempts to compute the number of bytes available at the pointer
8459 /// returned by a function with the alloc_size attribute. Returns true if we
8460 /// were successful. Places an unsigned number into `Result`.
8461 ///
8462 /// This expects the given CallExpr to be a call to a function with an
8463 /// alloc_size attribute.
8464 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8465                                             const CallExpr *Call,
8466                                             llvm::APInt &Result) {
8467   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8468 
8469   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8470   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8471   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8472   if (Call->getNumArgs() <= SizeArgNo)
8473     return false;
8474 
8475   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8476     Expr::EvalResult ExprResult;
8477     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8478       return false;
8479     Into = ExprResult.Val.getInt();
8480     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8481       return false;
8482     Into = Into.zextOrSelf(BitsInSizeT);
8483     return true;
8484   };
8485 
8486   APSInt SizeOfElem;
8487   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8488     return false;
8489 
8490   if (!AllocSize->getNumElemsParam().isValid()) {
8491     Result = std::move(SizeOfElem);
8492     return true;
8493   }
8494 
8495   APSInt NumberOfElems;
8496   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8497   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8498     return false;
8499 
8500   bool Overflow;
8501   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8502   if (Overflow)
8503     return false;
8504 
8505   Result = std::move(BytesAvailable);
8506   return true;
8507 }
8508 
8509 /// Convenience function. LVal's base must be a call to an alloc_size
8510 /// function.
8511 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8512                                             const LValue &LVal,
8513                                             llvm::APInt &Result) {
8514   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8515          "Can't get the size of a non alloc_size function");
8516   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8517   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8518   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8519 }
8520 
8521 /// Attempts to evaluate the given LValueBase as the result of a call to
8522 /// a function with the alloc_size attribute. If it was possible to do so, this
8523 /// function will return true, make Result's Base point to said function call,
8524 /// and mark Result's Base as invalid.
8525 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8526                                       LValue &Result) {
8527   if (Base.isNull())
8528     return false;
8529 
8530   // Because we do no form of static analysis, we only support const variables.
8531   //
8532   // Additionally, we can't support parameters, nor can we support static
8533   // variables (in the latter case, use-before-assign isn't UB; in the former,
8534   // we have no clue what they'll be assigned to).
8535   const auto *VD =
8536       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8537   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8538     return false;
8539 
8540   const Expr *Init = VD->getAnyInitializer();
8541   if (!Init)
8542     return false;
8543 
8544   const Expr *E = Init->IgnoreParens();
8545   if (!tryUnwrapAllocSizeCall(E))
8546     return false;
8547 
8548   // Store E instead of E unwrapped so that the type of the LValue's base is
8549   // what the user wanted.
8550   Result.setInvalid(E);
8551 
8552   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8553   Result.addUnsizedArray(Info, E, Pointee);
8554   return true;
8555 }
8556 
8557 namespace {
8558 class PointerExprEvaluator
8559   : public ExprEvaluatorBase<PointerExprEvaluator> {
8560   LValue &Result;
8561   bool InvalidBaseOK;
8562 
8563   bool Success(const Expr *E) {
8564     Result.set(E);
8565     return true;
8566   }
8567 
8568   bool evaluateLValue(const Expr *E, LValue &Result) {
8569     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8570   }
8571 
8572   bool evaluatePointer(const Expr *E, LValue &Result) {
8573     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8574   }
8575 
8576   bool visitNonBuiltinCallExpr(const CallExpr *E);
8577 public:
8578 
8579   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8580       : ExprEvaluatorBaseTy(info), Result(Result),
8581         InvalidBaseOK(InvalidBaseOK) {}
8582 
8583   bool Success(const APValue &V, const Expr *E) {
8584     Result.setFrom(Info.Ctx, V);
8585     return true;
8586   }
8587   bool ZeroInitialization(const Expr *E) {
8588     Result.setNull(Info.Ctx, E->getType());
8589     return true;
8590   }
8591 
8592   bool VisitBinaryOperator(const BinaryOperator *E);
8593   bool VisitCastExpr(const CastExpr* E);
8594   bool VisitUnaryAddrOf(const UnaryOperator *E);
8595   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8596       { return Success(E); }
8597   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8598     if (E->isExpressibleAsConstantInitializer())
8599       return Success(E);
8600     if (Info.noteFailure())
8601       EvaluateIgnoredValue(Info, E->getSubExpr());
8602     return Error(E);
8603   }
8604   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8605       { return Success(E); }
8606   bool VisitCallExpr(const CallExpr *E);
8607   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8608   bool VisitBlockExpr(const BlockExpr *E) {
8609     if (!E->getBlockDecl()->hasCaptures())
8610       return Success(E);
8611     return Error(E);
8612   }
8613   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8614     // Can't look at 'this' when checking a potential constant expression.
8615     if (Info.checkingPotentialConstantExpression())
8616       return false;
8617     if (!Info.CurrentCall->This) {
8618       if (Info.getLangOpts().CPlusPlus11)
8619         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8620       else
8621         Info.FFDiag(E);
8622       return false;
8623     }
8624     Result = *Info.CurrentCall->This;
8625     // If we are inside a lambda's call operator, the 'this' expression refers
8626     // to the enclosing '*this' object (either by value or reference) which is
8627     // either copied into the closure object's field that represents the '*this'
8628     // or refers to '*this'.
8629     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8630       // Ensure we actually have captured 'this'. (an error will have
8631       // been previously reported if not).
8632       if (!Info.CurrentCall->LambdaThisCaptureField)
8633         return false;
8634 
8635       // Update 'Result' to refer to the data member/field of the closure object
8636       // that represents the '*this' capture.
8637       if (!HandleLValueMember(Info, E, Result,
8638                              Info.CurrentCall->LambdaThisCaptureField))
8639         return false;
8640       // If we captured '*this' by reference, replace the field with its referent.
8641       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8642               ->isPointerType()) {
8643         APValue RVal;
8644         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8645                                             RVal))
8646           return false;
8647 
8648         Result.setFrom(Info.Ctx, RVal);
8649       }
8650     }
8651     return true;
8652   }
8653 
8654   bool VisitCXXNewExpr(const CXXNewExpr *E);
8655 
8656   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8657     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8658     APValue LValResult = E->EvaluateInContext(
8659         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8660     Result.setFrom(Info.Ctx, LValResult);
8661     return true;
8662   }
8663 
8664   // FIXME: Missing: @protocol, @selector
8665 };
8666 } // end anonymous namespace
8667 
8668 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8669                             bool InvalidBaseOK) {
8670   assert(!E->isValueDependent());
8671   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8672   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8673 }
8674 
8675 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8676   if (E->getOpcode() != BO_Add &&
8677       E->getOpcode() != BO_Sub)
8678     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8679 
8680   const Expr *PExp = E->getLHS();
8681   const Expr *IExp = E->getRHS();
8682   if (IExp->getType()->isPointerType())
8683     std::swap(PExp, IExp);
8684 
8685   bool EvalPtrOK = evaluatePointer(PExp, Result);
8686   if (!EvalPtrOK && !Info.noteFailure())
8687     return false;
8688 
8689   llvm::APSInt Offset;
8690   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8691     return false;
8692 
8693   if (E->getOpcode() == BO_Sub)
8694     negateAsSigned(Offset);
8695 
8696   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8697   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8698 }
8699 
8700 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8701   return evaluateLValue(E->getSubExpr(), Result);
8702 }
8703 
8704 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8705   const Expr *SubExpr = E->getSubExpr();
8706 
8707   switch (E->getCastKind()) {
8708   default:
8709     break;
8710   case CK_BitCast:
8711   case CK_CPointerToObjCPointerCast:
8712   case CK_BlockPointerToObjCPointerCast:
8713   case CK_AnyPointerToBlockPointerCast:
8714   case CK_AddressSpaceConversion:
8715     if (!Visit(SubExpr))
8716       return false;
8717     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8718     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8719     // also static_casts, but we disallow them as a resolution to DR1312.
8720     if (!E->getType()->isVoidPointerType()) {
8721       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8722           !Result.IsNullPtr &&
8723           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8724                                           E->getType()->getPointeeType()) &&
8725           Info.getStdAllocatorCaller("allocate")) {
8726         // Inside a call to std::allocator::allocate and friends, we permit
8727         // casting from void* back to cv1 T* for a pointer that points to a
8728         // cv2 T.
8729       } else {
8730         Result.Designator.setInvalid();
8731         if (SubExpr->getType()->isVoidPointerType())
8732           CCEDiag(E, diag::note_constexpr_invalid_cast)
8733             << 3 << SubExpr->getType();
8734         else
8735           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8736       }
8737     }
8738     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8739       ZeroInitialization(E);
8740     return true;
8741 
8742   case CK_DerivedToBase:
8743   case CK_UncheckedDerivedToBase:
8744     if (!evaluatePointer(E->getSubExpr(), Result))
8745       return false;
8746     if (!Result.Base && Result.Offset.isZero())
8747       return true;
8748 
8749     // Now figure out the necessary offset to add to the base LV to get from
8750     // the derived class to the base class.
8751     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8752                                   castAs<PointerType>()->getPointeeType(),
8753                                 Result);
8754 
8755   case CK_BaseToDerived:
8756     if (!Visit(E->getSubExpr()))
8757       return false;
8758     if (!Result.Base && Result.Offset.isZero())
8759       return true;
8760     return HandleBaseToDerivedCast(Info, E, Result);
8761 
8762   case CK_Dynamic:
8763     if (!Visit(E->getSubExpr()))
8764       return false;
8765     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8766 
8767   case CK_NullToPointer:
8768     VisitIgnoredValue(E->getSubExpr());
8769     return ZeroInitialization(E);
8770 
8771   case CK_IntegralToPointer: {
8772     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8773 
8774     APValue Value;
8775     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8776       break;
8777 
8778     if (Value.isInt()) {
8779       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8780       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8781       Result.Base = (Expr*)nullptr;
8782       Result.InvalidBase = false;
8783       Result.Offset = CharUnits::fromQuantity(N);
8784       Result.Designator.setInvalid();
8785       Result.IsNullPtr = false;
8786       return true;
8787     } else {
8788       // Cast is of an lvalue, no need to change value.
8789       Result.setFrom(Info.Ctx, Value);
8790       return true;
8791     }
8792   }
8793 
8794   case CK_ArrayToPointerDecay: {
8795     if (SubExpr->isGLValue()) {
8796       if (!evaluateLValue(SubExpr, Result))
8797         return false;
8798     } else {
8799       APValue &Value = Info.CurrentCall->createTemporary(
8800           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8801       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8802         return false;
8803     }
8804     // The result is a pointer to the first element of the array.
8805     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8806     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8807       Result.addArray(Info, E, CAT);
8808     else
8809       Result.addUnsizedArray(Info, E, AT->getElementType());
8810     return true;
8811   }
8812 
8813   case CK_FunctionToPointerDecay:
8814     return evaluateLValue(SubExpr, Result);
8815 
8816   case CK_LValueToRValue: {
8817     LValue LVal;
8818     if (!evaluateLValue(E->getSubExpr(), LVal))
8819       return false;
8820 
8821     APValue RVal;
8822     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8823     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8824                                         LVal, RVal))
8825       return InvalidBaseOK &&
8826              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8827     return Success(RVal, E);
8828   }
8829   }
8830 
8831   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8832 }
8833 
8834 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8835                                 UnaryExprOrTypeTrait ExprKind) {
8836   // C++ [expr.alignof]p3:
8837   //     When alignof is applied to a reference type, the result is the
8838   //     alignment of the referenced type.
8839   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8840     T = Ref->getPointeeType();
8841 
8842   if (T.getQualifiers().hasUnaligned())
8843     return CharUnits::One();
8844 
8845   const bool AlignOfReturnsPreferred =
8846       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8847 
8848   // __alignof is defined to return the preferred alignment.
8849   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8850   // as well.
8851   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8852     return Info.Ctx.toCharUnitsFromBits(
8853       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8854   // alignof and _Alignof are defined to return the ABI alignment.
8855   else if (ExprKind == UETT_AlignOf)
8856     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8857   else
8858     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8859 }
8860 
8861 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8862                                 UnaryExprOrTypeTrait ExprKind) {
8863   E = E->IgnoreParens();
8864 
8865   // The kinds of expressions that we have special-case logic here for
8866   // should be kept up to date with the special checks for those
8867   // expressions in Sema.
8868 
8869   // alignof decl is always accepted, even if it doesn't make sense: we default
8870   // to 1 in those cases.
8871   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8872     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8873                                  /*RefAsPointee*/true);
8874 
8875   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8876     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8877                                  /*RefAsPointee*/true);
8878 
8879   return GetAlignOfType(Info, E->getType(), ExprKind);
8880 }
8881 
8882 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8883   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8884     return Info.Ctx.getDeclAlign(VD);
8885   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8886     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8887   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8888 }
8889 
8890 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8891 /// __builtin_is_aligned and __builtin_assume_aligned.
8892 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8893                                  EvalInfo &Info, APSInt &Alignment) {
8894   if (!EvaluateInteger(E, Alignment, Info))
8895     return false;
8896   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8897     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8898     return false;
8899   }
8900   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8901   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8902   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8903     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8904         << MaxValue << ForType << Alignment;
8905     return false;
8906   }
8907   // Ensure both alignment and source value have the same bit width so that we
8908   // don't assert when computing the resulting value.
8909   APSInt ExtAlignment =
8910       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8911   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8912          "Alignment should not be changed by ext/trunc");
8913   Alignment = ExtAlignment;
8914   assert(Alignment.getBitWidth() == SrcWidth);
8915   return true;
8916 }
8917 
8918 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8919 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8920   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8921     return true;
8922 
8923   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8924     return false;
8925 
8926   Result.setInvalid(E);
8927   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8928   Result.addUnsizedArray(Info, E, PointeeTy);
8929   return true;
8930 }
8931 
8932 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8933   if (IsStringLiteralCall(E))
8934     return Success(E);
8935 
8936   if (unsigned BuiltinOp = E->getBuiltinCallee())
8937     return VisitBuiltinCallExpr(E, BuiltinOp);
8938 
8939   return visitNonBuiltinCallExpr(E);
8940 }
8941 
8942 // Determine if T is a character type for which we guarantee that
8943 // sizeof(T) == 1.
8944 static bool isOneByteCharacterType(QualType T) {
8945   return T->isCharType() || T->isChar8Type();
8946 }
8947 
8948 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8949                                                 unsigned BuiltinOp) {
8950   switch (BuiltinOp) {
8951   case Builtin::BI__builtin_addressof:
8952     return evaluateLValue(E->getArg(0), Result);
8953   case Builtin::BI__builtin_assume_aligned: {
8954     // We need to be very careful here because: if the pointer does not have the
8955     // asserted alignment, then the behavior is undefined, and undefined
8956     // behavior is non-constant.
8957     if (!evaluatePointer(E->getArg(0), Result))
8958       return false;
8959 
8960     LValue OffsetResult(Result);
8961     APSInt Alignment;
8962     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8963                               Alignment))
8964       return false;
8965     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8966 
8967     if (E->getNumArgs() > 2) {
8968       APSInt Offset;
8969       if (!EvaluateInteger(E->getArg(2), Offset, Info))
8970         return false;
8971 
8972       int64_t AdditionalOffset = -Offset.getZExtValue();
8973       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8974     }
8975 
8976     // If there is a base object, then it must have the correct alignment.
8977     if (OffsetResult.Base) {
8978       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
8979 
8980       if (BaseAlignment < Align) {
8981         Result.Designator.setInvalid();
8982         // FIXME: Add support to Diagnostic for long / long long.
8983         CCEDiag(E->getArg(0),
8984                 diag::note_constexpr_baa_insufficient_alignment) << 0
8985           << (unsigned)BaseAlignment.getQuantity()
8986           << (unsigned)Align.getQuantity();
8987         return false;
8988       }
8989     }
8990 
8991     // The offset must also have the correct alignment.
8992     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
8993       Result.Designator.setInvalid();
8994 
8995       (OffsetResult.Base
8996            ? CCEDiag(E->getArg(0),
8997                      diag::note_constexpr_baa_insufficient_alignment) << 1
8998            : CCEDiag(E->getArg(0),
8999                      diag::note_constexpr_baa_value_insufficient_alignment))
9000         << (int)OffsetResult.Offset.getQuantity()
9001         << (unsigned)Align.getQuantity();
9002       return false;
9003     }
9004 
9005     return true;
9006   }
9007   case Builtin::BI__builtin_align_up:
9008   case Builtin::BI__builtin_align_down: {
9009     if (!evaluatePointer(E->getArg(0), Result))
9010       return false;
9011     APSInt Alignment;
9012     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9013                               Alignment))
9014       return false;
9015     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9016     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9017     // For align_up/align_down, we can return the same value if the alignment
9018     // is known to be greater or equal to the requested value.
9019     if (PtrAlign.getQuantity() >= Alignment)
9020       return true;
9021 
9022     // The alignment could be greater than the minimum at run-time, so we cannot
9023     // infer much about the resulting pointer value. One case is possible:
9024     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9025     // can infer the correct index if the requested alignment is smaller than
9026     // the base alignment so we can perform the computation on the offset.
9027     if (BaseAlignment.getQuantity() >= Alignment) {
9028       assert(Alignment.getBitWidth() <= 64 &&
9029              "Cannot handle > 64-bit address-space");
9030       uint64_t Alignment64 = Alignment.getZExtValue();
9031       CharUnits NewOffset = CharUnits::fromQuantity(
9032           BuiltinOp == Builtin::BI__builtin_align_down
9033               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9034               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9035       Result.adjustOffset(NewOffset - Result.Offset);
9036       // TODO: diagnose out-of-bounds values/only allow for arrays?
9037       return true;
9038     }
9039     // Otherwise, we cannot constant-evaluate the result.
9040     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9041         << Alignment;
9042     return false;
9043   }
9044   case Builtin::BI__builtin_operator_new:
9045     return HandleOperatorNewCall(Info, E, Result);
9046   case Builtin::BI__builtin_launder:
9047     return evaluatePointer(E->getArg(0), Result);
9048   case Builtin::BIstrchr:
9049   case Builtin::BIwcschr:
9050   case Builtin::BImemchr:
9051   case Builtin::BIwmemchr:
9052     if (Info.getLangOpts().CPlusPlus11)
9053       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9054         << /*isConstexpr*/0 << /*isConstructor*/0
9055         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9056     else
9057       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9058     LLVM_FALLTHROUGH;
9059   case Builtin::BI__builtin_strchr:
9060   case Builtin::BI__builtin_wcschr:
9061   case Builtin::BI__builtin_memchr:
9062   case Builtin::BI__builtin_char_memchr:
9063   case Builtin::BI__builtin_wmemchr: {
9064     if (!Visit(E->getArg(0)))
9065       return false;
9066     APSInt Desired;
9067     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9068       return false;
9069     uint64_t MaxLength = uint64_t(-1);
9070     if (BuiltinOp != Builtin::BIstrchr &&
9071         BuiltinOp != Builtin::BIwcschr &&
9072         BuiltinOp != Builtin::BI__builtin_strchr &&
9073         BuiltinOp != Builtin::BI__builtin_wcschr) {
9074       APSInt N;
9075       if (!EvaluateInteger(E->getArg(2), N, Info))
9076         return false;
9077       MaxLength = N.getExtValue();
9078     }
9079     // We cannot find the value if there are no candidates to match against.
9080     if (MaxLength == 0u)
9081       return ZeroInitialization(E);
9082     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9083         Result.Designator.Invalid)
9084       return false;
9085     QualType CharTy = Result.Designator.getType(Info.Ctx);
9086     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9087                      BuiltinOp == Builtin::BI__builtin_memchr;
9088     assert(IsRawByte ||
9089            Info.Ctx.hasSameUnqualifiedType(
9090                CharTy, E->getArg(0)->getType()->getPointeeType()));
9091     // Pointers to const void may point to objects of incomplete type.
9092     if (IsRawByte && CharTy->isIncompleteType()) {
9093       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9094       return false;
9095     }
9096     // Give up on byte-oriented matching against multibyte elements.
9097     // FIXME: We can compare the bytes in the correct order.
9098     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9099       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9100           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9101           << CharTy;
9102       return false;
9103     }
9104     // Figure out what value we're actually looking for (after converting to
9105     // the corresponding unsigned type if necessary).
9106     uint64_t DesiredVal;
9107     bool StopAtNull = false;
9108     switch (BuiltinOp) {
9109     case Builtin::BIstrchr:
9110     case Builtin::BI__builtin_strchr:
9111       // strchr compares directly to the passed integer, and therefore
9112       // always fails if given an int that is not a char.
9113       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9114                                                   E->getArg(1)->getType(),
9115                                                   Desired),
9116                                Desired))
9117         return ZeroInitialization(E);
9118       StopAtNull = true;
9119       LLVM_FALLTHROUGH;
9120     case Builtin::BImemchr:
9121     case Builtin::BI__builtin_memchr:
9122     case Builtin::BI__builtin_char_memchr:
9123       // memchr compares by converting both sides to unsigned char. That's also
9124       // correct for strchr if we get this far (to cope with plain char being
9125       // unsigned in the strchr case).
9126       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9127       break;
9128 
9129     case Builtin::BIwcschr:
9130     case Builtin::BI__builtin_wcschr:
9131       StopAtNull = true;
9132       LLVM_FALLTHROUGH;
9133     case Builtin::BIwmemchr:
9134     case Builtin::BI__builtin_wmemchr:
9135       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9136       DesiredVal = Desired.getZExtValue();
9137       break;
9138     }
9139 
9140     for (; MaxLength; --MaxLength) {
9141       APValue Char;
9142       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9143           !Char.isInt())
9144         return false;
9145       if (Char.getInt().getZExtValue() == DesiredVal)
9146         return true;
9147       if (StopAtNull && !Char.getInt())
9148         break;
9149       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9150         return false;
9151     }
9152     // Not found: return nullptr.
9153     return ZeroInitialization(E);
9154   }
9155 
9156   case Builtin::BImemcpy:
9157   case Builtin::BImemmove:
9158   case Builtin::BIwmemcpy:
9159   case Builtin::BIwmemmove:
9160     if (Info.getLangOpts().CPlusPlus11)
9161       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9162         << /*isConstexpr*/0 << /*isConstructor*/0
9163         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9164     else
9165       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9166     LLVM_FALLTHROUGH;
9167   case Builtin::BI__builtin_memcpy:
9168   case Builtin::BI__builtin_memmove:
9169   case Builtin::BI__builtin_wmemcpy:
9170   case Builtin::BI__builtin_wmemmove: {
9171     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9172                  BuiltinOp == Builtin::BIwmemmove ||
9173                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9174                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9175     bool Move = BuiltinOp == Builtin::BImemmove ||
9176                 BuiltinOp == Builtin::BIwmemmove ||
9177                 BuiltinOp == Builtin::BI__builtin_memmove ||
9178                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9179 
9180     // The result of mem* is the first argument.
9181     if (!Visit(E->getArg(0)))
9182       return false;
9183     LValue Dest = Result;
9184 
9185     LValue Src;
9186     if (!EvaluatePointer(E->getArg(1), Src, Info))
9187       return false;
9188 
9189     APSInt N;
9190     if (!EvaluateInteger(E->getArg(2), N, Info))
9191       return false;
9192     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9193 
9194     // If the size is zero, we treat this as always being a valid no-op.
9195     // (Even if one of the src and dest pointers is null.)
9196     if (!N)
9197       return true;
9198 
9199     // Otherwise, if either of the operands is null, we can't proceed. Don't
9200     // try to determine the type of the copied objects, because there aren't
9201     // any.
9202     if (!Src.Base || !Dest.Base) {
9203       APValue Val;
9204       (!Src.Base ? Src : Dest).moveInto(Val);
9205       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9206           << Move << WChar << !!Src.Base
9207           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9208       return false;
9209     }
9210     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9211       return false;
9212 
9213     // We require that Src and Dest are both pointers to arrays of
9214     // trivially-copyable type. (For the wide version, the designator will be
9215     // invalid if the designated object is not a wchar_t.)
9216     QualType T = Dest.Designator.getType(Info.Ctx);
9217     QualType SrcT = Src.Designator.getType(Info.Ctx);
9218     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9219       // FIXME: Consider using our bit_cast implementation to support this.
9220       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9221       return false;
9222     }
9223     if (T->isIncompleteType()) {
9224       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9225       return false;
9226     }
9227     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9228       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9229       return false;
9230     }
9231 
9232     // Figure out how many T's we're copying.
9233     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9234     if (!WChar) {
9235       uint64_t Remainder;
9236       llvm::APInt OrigN = N;
9237       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9238       if (Remainder) {
9239         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9240             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
9241             << (unsigned)TSize;
9242         return false;
9243       }
9244     }
9245 
9246     // Check that the copying will remain within the arrays, just so that we
9247     // can give a more meaningful diagnostic. This implicitly also checks that
9248     // N fits into 64 bits.
9249     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9250     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9251     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9252       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9253           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9254           << N.toString(10, /*Signed*/false);
9255       return false;
9256     }
9257     uint64_t NElems = N.getZExtValue();
9258     uint64_t NBytes = NElems * TSize;
9259 
9260     // Check for overlap.
9261     int Direction = 1;
9262     if (HasSameBase(Src, Dest)) {
9263       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9264       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9265       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9266         // Dest is inside the source region.
9267         if (!Move) {
9268           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9269           return false;
9270         }
9271         // For memmove and friends, copy backwards.
9272         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9273             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9274           return false;
9275         Direction = -1;
9276       } else if (!Move && SrcOffset >= DestOffset &&
9277                  SrcOffset - DestOffset < NBytes) {
9278         // Src is inside the destination region for memcpy: invalid.
9279         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9280         return false;
9281       }
9282     }
9283 
9284     while (true) {
9285       APValue Val;
9286       // FIXME: Set WantObjectRepresentation to true if we're copying a
9287       // char-like type?
9288       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9289           !handleAssignment(Info, E, Dest, T, Val))
9290         return false;
9291       // Do not iterate past the last element; if we're copying backwards, that
9292       // might take us off the start of the array.
9293       if (--NElems == 0)
9294         return true;
9295       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9296           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9297         return false;
9298     }
9299   }
9300 
9301   default:
9302     break;
9303   }
9304 
9305   return visitNonBuiltinCallExpr(E);
9306 }
9307 
9308 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9309                                      APValue &Result, const InitListExpr *ILE,
9310                                      QualType AllocType);
9311 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9312                                           APValue &Result,
9313                                           const CXXConstructExpr *CCE,
9314                                           QualType AllocType);
9315 
9316 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9317   if (!Info.getLangOpts().CPlusPlus20)
9318     Info.CCEDiag(E, diag::note_constexpr_new);
9319 
9320   // We cannot speculatively evaluate a delete expression.
9321   if (Info.SpeculativeEvaluationDepth)
9322     return false;
9323 
9324   FunctionDecl *OperatorNew = E->getOperatorNew();
9325 
9326   bool IsNothrow = false;
9327   bool IsPlacement = false;
9328   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9329       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9330     // FIXME Support array placement new.
9331     assert(E->getNumPlacementArgs() == 1);
9332     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9333       return false;
9334     if (Result.Designator.Invalid)
9335       return false;
9336     IsPlacement = true;
9337   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9338     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9339         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9340     return false;
9341   } else if (E->getNumPlacementArgs()) {
9342     // The only new-placement list we support is of the form (std::nothrow).
9343     //
9344     // FIXME: There is no restriction on this, but it's not clear that any
9345     // other form makes any sense. We get here for cases such as:
9346     //
9347     //   new (std::align_val_t{N}) X(int)
9348     //
9349     // (which should presumably be valid only if N is a multiple of
9350     // alignof(int), and in any case can't be deallocated unless N is
9351     // alignof(X) and X has new-extended alignment).
9352     if (E->getNumPlacementArgs() != 1 ||
9353         !E->getPlacementArg(0)->getType()->isNothrowT())
9354       return Error(E, diag::note_constexpr_new_placement);
9355 
9356     LValue Nothrow;
9357     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9358       return false;
9359     IsNothrow = true;
9360   }
9361 
9362   const Expr *Init = E->getInitializer();
9363   const InitListExpr *ResizedArrayILE = nullptr;
9364   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9365   bool ValueInit = false;
9366 
9367   QualType AllocType = E->getAllocatedType();
9368   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
9369     const Expr *Stripped = *ArraySize;
9370     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9371          Stripped = ICE->getSubExpr())
9372       if (ICE->getCastKind() != CK_NoOp &&
9373           ICE->getCastKind() != CK_IntegralCast)
9374         break;
9375 
9376     llvm::APSInt ArrayBound;
9377     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9378       return false;
9379 
9380     // C++ [expr.new]p9:
9381     //   The expression is erroneous if:
9382     //   -- [...] its value before converting to size_t [or] applying the
9383     //      second standard conversion sequence is less than zero
9384     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9385       if (IsNothrow)
9386         return ZeroInitialization(E);
9387 
9388       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9389           << ArrayBound << (*ArraySize)->getSourceRange();
9390       return false;
9391     }
9392 
9393     //   -- its value is such that the size of the allocated object would
9394     //      exceed the implementation-defined limit
9395     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9396                                                 ArrayBound) >
9397         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9398       if (IsNothrow)
9399         return ZeroInitialization(E);
9400 
9401       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9402         << ArrayBound << (*ArraySize)->getSourceRange();
9403       return false;
9404     }
9405 
9406     //   -- the new-initializer is a braced-init-list and the number of
9407     //      array elements for which initializers are provided [...]
9408     //      exceeds the number of elements to initialize
9409     if (!Init) {
9410       // No initialization is performed.
9411     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9412                isa<ImplicitValueInitExpr>(Init)) {
9413       ValueInit = true;
9414     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9415       ResizedArrayCCE = CCE;
9416     } else {
9417       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9418       assert(CAT && "unexpected type for array initializer");
9419 
9420       unsigned Bits =
9421           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9422       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9423       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9424       if (InitBound.ugt(AllocBound)) {
9425         if (IsNothrow)
9426           return ZeroInitialization(E);
9427 
9428         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9429             << AllocBound.toString(10, /*Signed=*/false)
9430             << InitBound.toString(10, /*Signed=*/false)
9431             << (*ArraySize)->getSourceRange();
9432         return false;
9433       }
9434 
9435       // If the sizes differ, we must have an initializer list, and we need
9436       // special handling for this case when we initialize.
9437       if (InitBound != AllocBound)
9438         ResizedArrayILE = cast<InitListExpr>(Init);
9439     }
9440 
9441     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9442                                               ArrayType::Normal, 0);
9443   } else {
9444     assert(!AllocType->isArrayType() &&
9445            "array allocation with non-array new");
9446   }
9447 
9448   APValue *Val;
9449   if (IsPlacement) {
9450     AccessKinds AK = AK_Construct;
9451     struct FindObjectHandler {
9452       EvalInfo &Info;
9453       const Expr *E;
9454       QualType AllocType;
9455       const AccessKinds AccessKind;
9456       APValue *Value;
9457 
9458       typedef bool result_type;
9459       bool failed() { return false; }
9460       bool found(APValue &Subobj, QualType SubobjType) {
9461         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9462         // old name of the object to be used to name the new object.
9463         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9464           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9465             SubobjType << AllocType;
9466           return false;
9467         }
9468         Value = &Subobj;
9469         return true;
9470       }
9471       bool found(APSInt &Value, QualType SubobjType) {
9472         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9473         return false;
9474       }
9475       bool found(APFloat &Value, QualType SubobjType) {
9476         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9477         return false;
9478       }
9479     } Handler = {Info, E, AllocType, AK, nullptr};
9480 
9481     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9482     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9483       return false;
9484 
9485     Val = Handler.Value;
9486 
9487     // [basic.life]p1:
9488     //   The lifetime of an object o of type T ends when [...] the storage
9489     //   which the object occupies is [...] reused by an object that is not
9490     //   nested within o (6.6.2).
9491     *Val = APValue();
9492   } else {
9493     // Perform the allocation and obtain a pointer to the resulting object.
9494     Val = Info.createHeapAlloc(E, AllocType, Result);
9495     if (!Val)
9496       return false;
9497   }
9498 
9499   if (ValueInit) {
9500     ImplicitValueInitExpr VIE(AllocType);
9501     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9502       return false;
9503   } else if (ResizedArrayILE) {
9504     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9505                                   AllocType))
9506       return false;
9507   } else if (ResizedArrayCCE) {
9508     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9509                                        AllocType))
9510       return false;
9511   } else if (Init) {
9512     if (!EvaluateInPlace(*Val, Info, Result, Init))
9513       return false;
9514   } else if (!getDefaultInitValue(AllocType, *Val)) {
9515     return false;
9516   }
9517 
9518   // Array new returns a pointer to the first element, not a pointer to the
9519   // array.
9520   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9521     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9522 
9523   return true;
9524 }
9525 //===----------------------------------------------------------------------===//
9526 // Member Pointer Evaluation
9527 //===----------------------------------------------------------------------===//
9528 
9529 namespace {
9530 class MemberPointerExprEvaluator
9531   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9532   MemberPtr &Result;
9533 
9534   bool Success(const ValueDecl *D) {
9535     Result = MemberPtr(D);
9536     return true;
9537   }
9538 public:
9539 
9540   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9541     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9542 
9543   bool Success(const APValue &V, const Expr *E) {
9544     Result.setFrom(V);
9545     return true;
9546   }
9547   bool ZeroInitialization(const Expr *E) {
9548     return Success((const ValueDecl*)nullptr);
9549   }
9550 
9551   bool VisitCastExpr(const CastExpr *E);
9552   bool VisitUnaryAddrOf(const UnaryOperator *E);
9553 };
9554 } // end anonymous namespace
9555 
9556 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9557                                   EvalInfo &Info) {
9558   assert(!E->isValueDependent());
9559   assert(E->isRValue() && E->getType()->isMemberPointerType());
9560   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9561 }
9562 
9563 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9564   switch (E->getCastKind()) {
9565   default:
9566     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9567 
9568   case CK_NullToMemberPointer:
9569     VisitIgnoredValue(E->getSubExpr());
9570     return ZeroInitialization(E);
9571 
9572   case CK_BaseToDerivedMemberPointer: {
9573     if (!Visit(E->getSubExpr()))
9574       return false;
9575     if (E->path_empty())
9576       return true;
9577     // Base-to-derived member pointer casts store the path in derived-to-base
9578     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9579     // the wrong end of the derived->base arc, so stagger the path by one class.
9580     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9581     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9582          PathI != PathE; ++PathI) {
9583       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9584       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9585       if (!Result.castToDerived(Derived))
9586         return Error(E);
9587     }
9588     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9589     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9590       return Error(E);
9591     return true;
9592   }
9593 
9594   case CK_DerivedToBaseMemberPointer:
9595     if (!Visit(E->getSubExpr()))
9596       return false;
9597     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9598          PathE = E->path_end(); PathI != PathE; ++PathI) {
9599       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9600       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9601       if (!Result.castToBase(Base))
9602         return Error(E);
9603     }
9604     return true;
9605   }
9606 }
9607 
9608 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9609   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9610   // member can be formed.
9611   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9612 }
9613 
9614 //===----------------------------------------------------------------------===//
9615 // Record Evaluation
9616 //===----------------------------------------------------------------------===//
9617 
9618 namespace {
9619   class RecordExprEvaluator
9620   : public ExprEvaluatorBase<RecordExprEvaluator> {
9621     const LValue &This;
9622     APValue &Result;
9623   public:
9624 
9625     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9626       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9627 
9628     bool Success(const APValue &V, const Expr *E) {
9629       Result = V;
9630       return true;
9631     }
9632     bool ZeroInitialization(const Expr *E) {
9633       return ZeroInitialization(E, E->getType());
9634     }
9635     bool ZeroInitialization(const Expr *E, QualType T);
9636 
9637     bool VisitCallExpr(const CallExpr *E) {
9638       return handleCallExpr(E, Result, &This);
9639     }
9640     bool VisitCastExpr(const CastExpr *E);
9641     bool VisitInitListExpr(const InitListExpr *E);
9642     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9643       return VisitCXXConstructExpr(E, E->getType());
9644     }
9645     bool VisitLambdaExpr(const LambdaExpr *E);
9646     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9647     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9648     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9649     bool VisitBinCmp(const BinaryOperator *E);
9650   };
9651 }
9652 
9653 /// Perform zero-initialization on an object of non-union class type.
9654 /// C++11 [dcl.init]p5:
9655 ///  To zero-initialize an object or reference of type T means:
9656 ///    [...]
9657 ///    -- if T is a (possibly cv-qualified) non-union class type,
9658 ///       each non-static data member and each base-class subobject is
9659 ///       zero-initialized
9660 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9661                                           const RecordDecl *RD,
9662                                           const LValue &This, APValue &Result) {
9663   assert(!RD->isUnion() && "Expected non-union class type");
9664   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9665   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9666                    std::distance(RD->field_begin(), RD->field_end()));
9667 
9668   if (RD->isInvalidDecl()) return false;
9669   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9670 
9671   if (CD) {
9672     unsigned Index = 0;
9673     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9674            End = CD->bases_end(); I != End; ++I, ++Index) {
9675       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9676       LValue Subobject = This;
9677       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9678         return false;
9679       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9680                                          Result.getStructBase(Index)))
9681         return false;
9682     }
9683   }
9684 
9685   for (const auto *I : RD->fields()) {
9686     // -- if T is a reference type, no initialization is performed.
9687     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9688       continue;
9689 
9690     LValue Subobject = This;
9691     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9692       return false;
9693 
9694     ImplicitValueInitExpr VIE(I->getType());
9695     if (!EvaluateInPlace(
9696           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9697       return false;
9698   }
9699 
9700   return true;
9701 }
9702 
9703 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9704   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9705   if (RD->isInvalidDecl()) return false;
9706   if (RD->isUnion()) {
9707     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9708     // object's first non-static named data member is zero-initialized
9709     RecordDecl::field_iterator I = RD->field_begin();
9710     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9711       ++I;
9712     if (I == RD->field_end()) {
9713       Result = APValue((const FieldDecl*)nullptr);
9714       return true;
9715     }
9716 
9717     LValue Subobject = This;
9718     if (!HandleLValueMember(Info, E, Subobject, *I))
9719       return false;
9720     Result = APValue(*I);
9721     ImplicitValueInitExpr VIE(I->getType());
9722     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9723   }
9724 
9725   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9726     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9727     return false;
9728   }
9729 
9730   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9731 }
9732 
9733 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9734   switch (E->getCastKind()) {
9735   default:
9736     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9737 
9738   case CK_ConstructorConversion:
9739     return Visit(E->getSubExpr());
9740 
9741   case CK_DerivedToBase:
9742   case CK_UncheckedDerivedToBase: {
9743     APValue DerivedObject;
9744     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9745       return false;
9746     if (!DerivedObject.isStruct())
9747       return Error(E->getSubExpr());
9748 
9749     // Derived-to-base rvalue conversion: just slice off the derived part.
9750     APValue *Value = &DerivedObject;
9751     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9752     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9753          PathE = E->path_end(); PathI != PathE; ++PathI) {
9754       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9755       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9756       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9757       RD = Base;
9758     }
9759     Result = *Value;
9760     return true;
9761   }
9762   }
9763 }
9764 
9765 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9766   if (E->isTransparent())
9767     return Visit(E->getInit(0));
9768 
9769   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9770   if (RD->isInvalidDecl()) return false;
9771   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9772   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9773 
9774   EvalInfo::EvaluatingConstructorRAII EvalObj(
9775       Info,
9776       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9777       CXXRD && CXXRD->getNumBases());
9778 
9779   if (RD->isUnion()) {
9780     const FieldDecl *Field = E->getInitializedFieldInUnion();
9781     Result = APValue(Field);
9782     if (!Field)
9783       return true;
9784 
9785     // If the initializer list for a union does not contain any elements, the
9786     // first element of the union is value-initialized.
9787     // FIXME: The element should be initialized from an initializer list.
9788     //        Is this difference ever observable for initializer lists which
9789     //        we don't build?
9790     ImplicitValueInitExpr VIE(Field->getType());
9791     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9792 
9793     LValue Subobject = This;
9794     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9795       return false;
9796 
9797     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9798     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9799                                   isa<CXXDefaultInitExpr>(InitExpr));
9800 
9801     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
9802       if (Field->isBitField())
9803         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
9804                                      Field);
9805       return true;
9806     }
9807 
9808     return false;
9809   }
9810 
9811   if (!Result.hasValue())
9812     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9813                      std::distance(RD->field_begin(), RD->field_end()));
9814   unsigned ElementNo = 0;
9815   bool Success = true;
9816 
9817   // Initialize base classes.
9818   if (CXXRD && CXXRD->getNumBases()) {
9819     for (const auto &Base : CXXRD->bases()) {
9820       assert(ElementNo < E->getNumInits() && "missing init for base class");
9821       const Expr *Init = E->getInit(ElementNo);
9822 
9823       LValue Subobject = This;
9824       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9825         return false;
9826 
9827       APValue &FieldVal = Result.getStructBase(ElementNo);
9828       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9829         if (!Info.noteFailure())
9830           return false;
9831         Success = false;
9832       }
9833       ++ElementNo;
9834     }
9835 
9836     EvalObj.finishedConstructingBases();
9837   }
9838 
9839   // Initialize members.
9840   for (const auto *Field : RD->fields()) {
9841     // Anonymous bit-fields are not considered members of the class for
9842     // purposes of aggregate initialization.
9843     if (Field->isUnnamedBitfield())
9844       continue;
9845 
9846     LValue Subobject = This;
9847 
9848     bool HaveInit = ElementNo < E->getNumInits();
9849 
9850     // FIXME: Diagnostics here should point to the end of the initializer
9851     // list, not the start.
9852     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9853                             Subobject, Field, &Layout))
9854       return false;
9855 
9856     // Perform an implicit value-initialization for members beyond the end of
9857     // the initializer list.
9858     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9859     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9860 
9861     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9862     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9863                                   isa<CXXDefaultInitExpr>(Init));
9864 
9865     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9866     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9867         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9868                                                        FieldVal, Field))) {
9869       if (!Info.noteFailure())
9870         return false;
9871       Success = false;
9872     }
9873   }
9874 
9875   EvalObj.finishedConstructingFields();
9876 
9877   return Success;
9878 }
9879 
9880 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9881                                                 QualType T) {
9882   // Note that E's type is not necessarily the type of our class here; we might
9883   // be initializing an array element instead.
9884   const CXXConstructorDecl *FD = E->getConstructor();
9885   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9886 
9887   bool ZeroInit = E->requiresZeroInitialization();
9888   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9889     // If we've already performed zero-initialization, we're already done.
9890     if (Result.hasValue())
9891       return true;
9892 
9893     if (ZeroInit)
9894       return ZeroInitialization(E, T);
9895 
9896     return getDefaultInitValue(T, Result);
9897   }
9898 
9899   const FunctionDecl *Definition = nullptr;
9900   auto Body = FD->getBody(Definition);
9901 
9902   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9903     return false;
9904 
9905   // Avoid materializing a temporary for an elidable copy/move constructor.
9906   if (E->isElidable() && !ZeroInit)
9907     if (const MaterializeTemporaryExpr *ME
9908           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9909       return Visit(ME->getSubExpr());
9910 
9911   if (ZeroInit && !ZeroInitialization(E, T))
9912     return false;
9913 
9914   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9915   return HandleConstructorCall(E, This, Args,
9916                                cast<CXXConstructorDecl>(Definition), Info,
9917                                Result);
9918 }
9919 
9920 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9921     const CXXInheritedCtorInitExpr *E) {
9922   if (!Info.CurrentCall) {
9923     assert(Info.checkingPotentialConstantExpression());
9924     return false;
9925   }
9926 
9927   const CXXConstructorDecl *FD = E->getConstructor();
9928   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9929     return false;
9930 
9931   const FunctionDecl *Definition = nullptr;
9932   auto Body = FD->getBody(Definition);
9933 
9934   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9935     return false;
9936 
9937   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9938                                cast<CXXConstructorDecl>(Definition), Info,
9939                                Result);
9940 }
9941 
9942 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9943     const CXXStdInitializerListExpr *E) {
9944   const ConstantArrayType *ArrayType =
9945       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9946 
9947   LValue Array;
9948   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9949     return false;
9950 
9951   // Get a pointer to the first element of the array.
9952   Array.addArray(Info, E, ArrayType);
9953 
9954   auto InvalidType = [&] {
9955     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
9956       << E->getType();
9957     return false;
9958   };
9959 
9960   // FIXME: Perform the checks on the field types in SemaInit.
9961   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9962   RecordDecl::field_iterator Field = Record->field_begin();
9963   if (Field == Record->field_end())
9964     return InvalidType();
9965 
9966   // Start pointer.
9967   if (!Field->getType()->isPointerType() ||
9968       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9969                             ArrayType->getElementType()))
9970     return InvalidType();
9971 
9972   // FIXME: What if the initializer_list type has base classes, etc?
9973   Result = APValue(APValue::UninitStruct(), 0, 2);
9974   Array.moveInto(Result.getStructField(0));
9975 
9976   if (++Field == Record->field_end())
9977     return InvalidType();
9978 
9979   if (Field->getType()->isPointerType() &&
9980       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9981                            ArrayType->getElementType())) {
9982     // End pointer.
9983     if (!HandleLValueArrayAdjustment(Info, E, Array,
9984                                      ArrayType->getElementType(),
9985                                      ArrayType->getSize().getZExtValue()))
9986       return false;
9987     Array.moveInto(Result.getStructField(1));
9988   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9989     // Length.
9990     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9991   else
9992     return InvalidType();
9993 
9994   if (++Field != Record->field_end())
9995     return InvalidType();
9996 
9997   return true;
9998 }
9999 
10000 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10001   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10002   if (ClosureClass->isInvalidDecl())
10003     return false;
10004 
10005   const size_t NumFields =
10006       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10007 
10008   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10009                                             E->capture_init_end()) &&
10010          "The number of lambda capture initializers should equal the number of "
10011          "fields within the closure type");
10012 
10013   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10014   // Iterate through all the lambda's closure object's fields and initialize
10015   // them.
10016   auto *CaptureInitIt = E->capture_init_begin();
10017   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
10018   bool Success = true;
10019   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10020   for (const auto *Field : ClosureClass->fields()) {
10021     assert(CaptureInitIt != E->capture_init_end());
10022     // Get the initializer for this field
10023     Expr *const CurFieldInit = *CaptureInitIt++;
10024 
10025     // If there is no initializer, either this is a VLA or an error has
10026     // occurred.
10027     if (!CurFieldInit)
10028       return Error(E);
10029 
10030     LValue Subobject = This;
10031 
10032     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10033       return false;
10034 
10035     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10036     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10037       if (!Info.keepEvaluatingAfterFailure())
10038         return false;
10039       Success = false;
10040     }
10041     ++CaptureIt;
10042   }
10043   return Success;
10044 }
10045 
10046 static bool EvaluateRecord(const Expr *E, const LValue &This,
10047                            APValue &Result, EvalInfo &Info) {
10048   assert(!E->isValueDependent());
10049   assert(E->isRValue() && E->getType()->isRecordType() &&
10050          "can't evaluate expression as a record rvalue");
10051   return RecordExprEvaluator(Info, This, Result).Visit(E);
10052 }
10053 
10054 //===----------------------------------------------------------------------===//
10055 // Temporary Evaluation
10056 //
10057 // Temporaries are represented in the AST as rvalues, but generally behave like
10058 // lvalues. The full-object of which the temporary is a subobject is implicitly
10059 // materialized so that a reference can bind to it.
10060 //===----------------------------------------------------------------------===//
10061 namespace {
10062 class TemporaryExprEvaluator
10063   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10064 public:
10065   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10066     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10067 
10068   /// Visit an expression which constructs the value of this temporary.
10069   bool VisitConstructExpr(const Expr *E) {
10070     APValue &Value = Info.CurrentCall->createTemporary(
10071         E, E->getType(), ScopeKind::FullExpression, Result);
10072     return EvaluateInPlace(Value, Info, Result, E);
10073   }
10074 
10075   bool VisitCastExpr(const CastExpr *E) {
10076     switch (E->getCastKind()) {
10077     default:
10078       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10079 
10080     case CK_ConstructorConversion:
10081       return VisitConstructExpr(E->getSubExpr());
10082     }
10083   }
10084   bool VisitInitListExpr(const InitListExpr *E) {
10085     return VisitConstructExpr(E);
10086   }
10087   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10088     return VisitConstructExpr(E);
10089   }
10090   bool VisitCallExpr(const CallExpr *E) {
10091     return VisitConstructExpr(E);
10092   }
10093   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10094     return VisitConstructExpr(E);
10095   }
10096   bool VisitLambdaExpr(const LambdaExpr *E) {
10097     return VisitConstructExpr(E);
10098   }
10099 };
10100 } // end anonymous namespace
10101 
10102 /// Evaluate an expression of record type as a temporary.
10103 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10104   assert(!E->isValueDependent());
10105   assert(E->isRValue() && E->getType()->isRecordType());
10106   return TemporaryExprEvaluator(Info, Result).Visit(E);
10107 }
10108 
10109 //===----------------------------------------------------------------------===//
10110 // Vector Evaluation
10111 //===----------------------------------------------------------------------===//
10112 
10113 namespace {
10114   class VectorExprEvaluator
10115   : public ExprEvaluatorBase<VectorExprEvaluator> {
10116     APValue &Result;
10117   public:
10118 
10119     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10120       : ExprEvaluatorBaseTy(info), Result(Result) {}
10121 
10122     bool Success(ArrayRef<APValue> V, const Expr *E) {
10123       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10124       // FIXME: remove this APValue copy.
10125       Result = APValue(V.data(), V.size());
10126       return true;
10127     }
10128     bool Success(const APValue &V, const Expr *E) {
10129       assert(V.isVector());
10130       Result = V;
10131       return true;
10132     }
10133     bool ZeroInitialization(const Expr *E);
10134 
10135     bool VisitUnaryReal(const UnaryOperator *E)
10136       { return Visit(E->getSubExpr()); }
10137     bool VisitCastExpr(const CastExpr* E);
10138     bool VisitInitListExpr(const InitListExpr *E);
10139     bool VisitUnaryImag(const UnaryOperator *E);
10140     bool VisitBinaryOperator(const BinaryOperator *E);
10141     // FIXME: Missing: unary -, unary ~, conditional operator (for GNU
10142     //                 conditional select), shufflevector, ExtVectorElementExpr
10143   };
10144 } // end anonymous namespace
10145 
10146 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10147   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
10148   return VectorExprEvaluator(Info, Result).Visit(E);
10149 }
10150 
10151 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10152   const VectorType *VTy = E->getType()->castAs<VectorType>();
10153   unsigned NElts = VTy->getNumElements();
10154 
10155   const Expr *SE = E->getSubExpr();
10156   QualType SETy = SE->getType();
10157 
10158   switch (E->getCastKind()) {
10159   case CK_VectorSplat: {
10160     APValue Val = APValue();
10161     if (SETy->isIntegerType()) {
10162       APSInt IntResult;
10163       if (!EvaluateInteger(SE, IntResult, Info))
10164         return false;
10165       Val = APValue(std::move(IntResult));
10166     } else if (SETy->isRealFloatingType()) {
10167       APFloat FloatResult(0.0);
10168       if (!EvaluateFloat(SE, FloatResult, Info))
10169         return false;
10170       Val = APValue(std::move(FloatResult));
10171     } else {
10172       return Error(E);
10173     }
10174 
10175     // Splat and create vector APValue.
10176     SmallVector<APValue, 4> Elts(NElts, Val);
10177     return Success(Elts, E);
10178   }
10179   case CK_BitCast: {
10180     // Evaluate the operand into an APInt we can extract from.
10181     llvm::APInt SValInt;
10182     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10183       return false;
10184     // Extract the elements
10185     QualType EltTy = VTy->getElementType();
10186     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10187     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10188     SmallVector<APValue, 4> Elts;
10189     if (EltTy->isRealFloatingType()) {
10190       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10191       unsigned FloatEltSize = EltSize;
10192       if (&Sem == &APFloat::x87DoubleExtended())
10193         FloatEltSize = 80;
10194       for (unsigned i = 0; i < NElts; i++) {
10195         llvm::APInt Elt;
10196         if (BigEndian)
10197           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
10198         else
10199           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
10200         Elts.push_back(APValue(APFloat(Sem, Elt)));
10201       }
10202     } else if (EltTy->isIntegerType()) {
10203       for (unsigned i = 0; i < NElts; i++) {
10204         llvm::APInt Elt;
10205         if (BigEndian)
10206           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10207         else
10208           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10209         Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10210       }
10211     } else {
10212       return Error(E);
10213     }
10214     return Success(Elts, E);
10215   }
10216   default:
10217     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10218   }
10219 }
10220 
10221 bool
10222 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10223   const VectorType *VT = E->getType()->castAs<VectorType>();
10224   unsigned NumInits = E->getNumInits();
10225   unsigned NumElements = VT->getNumElements();
10226 
10227   QualType EltTy = VT->getElementType();
10228   SmallVector<APValue, 4> Elements;
10229 
10230   // The number of initializers can be less than the number of
10231   // vector elements. For OpenCL, this can be due to nested vector
10232   // initialization. For GCC compatibility, missing trailing elements
10233   // should be initialized with zeroes.
10234   unsigned CountInits = 0, CountElts = 0;
10235   while (CountElts < NumElements) {
10236     // Handle nested vector initialization.
10237     if (CountInits < NumInits
10238         && E->getInit(CountInits)->getType()->isVectorType()) {
10239       APValue v;
10240       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10241         return Error(E);
10242       unsigned vlen = v.getVectorLength();
10243       for (unsigned j = 0; j < vlen; j++)
10244         Elements.push_back(v.getVectorElt(j));
10245       CountElts += vlen;
10246     } else if (EltTy->isIntegerType()) {
10247       llvm::APSInt sInt(32);
10248       if (CountInits < NumInits) {
10249         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10250           return false;
10251       } else // trailing integer zero.
10252         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10253       Elements.push_back(APValue(sInt));
10254       CountElts++;
10255     } else {
10256       llvm::APFloat f(0.0);
10257       if (CountInits < NumInits) {
10258         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10259           return false;
10260       } else // trailing float zero.
10261         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10262       Elements.push_back(APValue(f));
10263       CountElts++;
10264     }
10265     CountInits++;
10266   }
10267   return Success(Elements, E);
10268 }
10269 
10270 bool
10271 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10272   const auto *VT = E->getType()->castAs<VectorType>();
10273   QualType EltTy = VT->getElementType();
10274   APValue ZeroElement;
10275   if (EltTy->isIntegerType())
10276     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10277   else
10278     ZeroElement =
10279         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10280 
10281   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10282   return Success(Elements, E);
10283 }
10284 
10285 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10286   VisitIgnoredValue(E->getSubExpr());
10287   return ZeroInitialization(E);
10288 }
10289 
10290 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10291   BinaryOperatorKind Op = E->getOpcode();
10292   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10293          "Operation not supported on vector types");
10294 
10295   if (Op == BO_Comma)
10296     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10297 
10298   Expr *LHS = E->getLHS();
10299   Expr *RHS = E->getRHS();
10300 
10301   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10302          "Must both be vector types");
10303   // Checking JUST the types are the same would be fine, except shifts don't
10304   // need to have their types be the same (since you always shift by an int).
10305   assert(LHS->getType()->getAs<VectorType>()->getNumElements() ==
10306              E->getType()->getAs<VectorType>()->getNumElements() &&
10307          RHS->getType()->getAs<VectorType>()->getNumElements() ==
10308              E->getType()->getAs<VectorType>()->getNumElements() &&
10309          "All operands must be the same size.");
10310 
10311   APValue LHSValue;
10312   APValue RHSValue;
10313   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10314   if (!LHSOK && !Info.noteFailure())
10315     return false;
10316   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10317     return false;
10318 
10319   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10320     return false;
10321 
10322   return Success(LHSValue, E);
10323 }
10324 
10325 //===----------------------------------------------------------------------===//
10326 // Array Evaluation
10327 //===----------------------------------------------------------------------===//
10328 
10329 namespace {
10330   class ArrayExprEvaluator
10331   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10332     const LValue &This;
10333     APValue &Result;
10334   public:
10335 
10336     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10337       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10338 
10339     bool Success(const APValue &V, const Expr *E) {
10340       assert(V.isArray() && "expected array");
10341       Result = V;
10342       return true;
10343     }
10344 
10345     bool ZeroInitialization(const Expr *E) {
10346       const ConstantArrayType *CAT =
10347           Info.Ctx.getAsConstantArrayType(E->getType());
10348       if (!CAT) {
10349         if (E->getType()->isIncompleteArrayType()) {
10350           // We can be asked to zero-initialize a flexible array member; this
10351           // is represented as an ImplicitValueInitExpr of incomplete array
10352           // type. In this case, the array has zero elements.
10353           Result = APValue(APValue::UninitArray(), 0, 0);
10354           return true;
10355         }
10356         // FIXME: We could handle VLAs here.
10357         return Error(E);
10358       }
10359 
10360       Result = APValue(APValue::UninitArray(), 0,
10361                        CAT->getSize().getZExtValue());
10362       if (!Result.hasArrayFiller()) return true;
10363 
10364       // Zero-initialize all elements.
10365       LValue Subobject = This;
10366       Subobject.addArray(Info, E, CAT);
10367       ImplicitValueInitExpr VIE(CAT->getElementType());
10368       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10369     }
10370 
10371     bool VisitCallExpr(const CallExpr *E) {
10372       return handleCallExpr(E, Result, &This);
10373     }
10374     bool VisitInitListExpr(const InitListExpr *E,
10375                            QualType AllocType = QualType());
10376     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10377     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10378     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10379                                const LValue &Subobject,
10380                                APValue *Value, QualType Type);
10381     bool VisitStringLiteral(const StringLiteral *E,
10382                             QualType AllocType = QualType()) {
10383       expandStringLiteral(Info, E, Result, AllocType);
10384       return true;
10385     }
10386   };
10387 } // end anonymous namespace
10388 
10389 static bool EvaluateArray(const Expr *E, const LValue &This,
10390                           APValue &Result, EvalInfo &Info) {
10391   assert(!E->isValueDependent());
10392   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
10393   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10394 }
10395 
10396 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10397                                      APValue &Result, const InitListExpr *ILE,
10398                                      QualType AllocType) {
10399   assert(!ILE->isValueDependent());
10400   assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
10401          "not an array rvalue");
10402   return ArrayExprEvaluator(Info, This, Result)
10403       .VisitInitListExpr(ILE, AllocType);
10404 }
10405 
10406 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10407                                           APValue &Result,
10408                                           const CXXConstructExpr *CCE,
10409                                           QualType AllocType) {
10410   assert(!CCE->isValueDependent());
10411   assert(CCE->isRValue() && CCE->getType()->isArrayType() &&
10412          "not an array rvalue");
10413   return ArrayExprEvaluator(Info, This, Result)
10414       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10415 }
10416 
10417 // Return true iff the given array filler may depend on the element index.
10418 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10419   // For now, just allow non-class value-initialization and initialization
10420   // lists comprised of them.
10421   if (isa<ImplicitValueInitExpr>(FillerExpr))
10422     return false;
10423   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10424     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10425       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10426         return true;
10427     }
10428     return false;
10429   }
10430   return true;
10431 }
10432 
10433 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10434                                            QualType AllocType) {
10435   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10436       AllocType.isNull() ? E->getType() : AllocType);
10437   if (!CAT)
10438     return Error(E);
10439 
10440   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10441   // an appropriately-typed string literal enclosed in braces.
10442   if (E->isStringLiteralInit()) {
10443     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
10444     // FIXME: Support ObjCEncodeExpr here once we support it in
10445     // ArrayExprEvaluator generally.
10446     if (!SL)
10447       return Error(E);
10448     return VisitStringLiteral(SL, AllocType);
10449   }
10450 
10451   bool Success = true;
10452 
10453   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10454          "zero-initialized array shouldn't have any initialized elts");
10455   APValue Filler;
10456   if (Result.isArray() && Result.hasArrayFiller())
10457     Filler = Result.getArrayFiller();
10458 
10459   unsigned NumEltsToInit = E->getNumInits();
10460   unsigned NumElts = CAT->getSize().getZExtValue();
10461   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10462 
10463   // If the initializer might depend on the array index, run it for each
10464   // array element.
10465   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10466     NumEltsToInit = NumElts;
10467 
10468   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10469                           << NumEltsToInit << ".\n");
10470 
10471   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10472 
10473   // If the array was previously zero-initialized, preserve the
10474   // zero-initialized values.
10475   if (Filler.hasValue()) {
10476     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10477       Result.getArrayInitializedElt(I) = Filler;
10478     if (Result.hasArrayFiller())
10479       Result.getArrayFiller() = Filler;
10480   }
10481 
10482   LValue Subobject = This;
10483   Subobject.addArray(Info, E, CAT);
10484   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10485     const Expr *Init =
10486         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10487     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10488                          Info, Subobject, Init) ||
10489         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10490                                      CAT->getElementType(), 1)) {
10491       if (!Info.noteFailure())
10492         return false;
10493       Success = false;
10494     }
10495   }
10496 
10497   if (!Result.hasArrayFiller())
10498     return Success;
10499 
10500   // If we get here, we have a trivial filler, which we can just evaluate
10501   // once and splat over the rest of the array elements.
10502   assert(FillerExpr && "no array filler for incomplete init list");
10503   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10504                          FillerExpr) && Success;
10505 }
10506 
10507 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10508   LValue CommonLV;
10509   if (E->getCommonExpr() &&
10510       !Evaluate(Info.CurrentCall->createTemporary(
10511                     E->getCommonExpr(),
10512                     getStorageType(Info.Ctx, E->getCommonExpr()),
10513                     ScopeKind::FullExpression, CommonLV),
10514                 Info, E->getCommonExpr()->getSourceExpr()))
10515     return false;
10516 
10517   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10518 
10519   uint64_t Elements = CAT->getSize().getZExtValue();
10520   Result = APValue(APValue::UninitArray(), Elements, Elements);
10521 
10522   LValue Subobject = This;
10523   Subobject.addArray(Info, E, CAT);
10524 
10525   bool Success = true;
10526   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10527     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10528                          Info, Subobject, E->getSubExpr()) ||
10529         !HandleLValueArrayAdjustment(Info, E, Subobject,
10530                                      CAT->getElementType(), 1)) {
10531       if (!Info.noteFailure())
10532         return false;
10533       Success = false;
10534     }
10535   }
10536 
10537   return Success;
10538 }
10539 
10540 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10541   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10542 }
10543 
10544 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10545                                                const LValue &Subobject,
10546                                                APValue *Value,
10547                                                QualType Type) {
10548   bool HadZeroInit = Value->hasValue();
10549 
10550   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10551     unsigned N = CAT->getSize().getZExtValue();
10552 
10553     // Preserve the array filler if we had prior zero-initialization.
10554     APValue Filler =
10555       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10556                                              : APValue();
10557 
10558     *Value = APValue(APValue::UninitArray(), N, N);
10559 
10560     if (HadZeroInit)
10561       for (unsigned I = 0; I != N; ++I)
10562         Value->getArrayInitializedElt(I) = Filler;
10563 
10564     // Initialize the elements.
10565     LValue ArrayElt = Subobject;
10566     ArrayElt.addArray(Info, E, CAT);
10567     for (unsigned I = 0; I != N; ++I)
10568       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
10569                                  CAT->getElementType()) ||
10570           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10571                                        CAT->getElementType(), 1))
10572         return false;
10573 
10574     return true;
10575   }
10576 
10577   if (!Type->isRecordType())
10578     return Error(E);
10579 
10580   return RecordExprEvaluator(Info, Subobject, *Value)
10581              .VisitCXXConstructExpr(E, Type);
10582 }
10583 
10584 //===----------------------------------------------------------------------===//
10585 // Integer Evaluation
10586 //
10587 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10588 // types and back in constant folding. Integer values are thus represented
10589 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10590 //===----------------------------------------------------------------------===//
10591 
10592 namespace {
10593 class IntExprEvaluator
10594         : public ExprEvaluatorBase<IntExprEvaluator> {
10595   APValue &Result;
10596 public:
10597   IntExprEvaluator(EvalInfo &info, APValue &result)
10598       : ExprEvaluatorBaseTy(info), Result(result) {}
10599 
10600   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10601     assert(E->getType()->isIntegralOrEnumerationType() &&
10602            "Invalid evaluation result.");
10603     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10604            "Invalid evaluation result.");
10605     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10606            "Invalid evaluation result.");
10607     Result = APValue(SI);
10608     return true;
10609   }
10610   bool Success(const llvm::APSInt &SI, const Expr *E) {
10611     return Success(SI, E, Result);
10612   }
10613 
10614   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10615     assert(E->getType()->isIntegralOrEnumerationType() &&
10616            "Invalid evaluation result.");
10617     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10618            "Invalid evaluation result.");
10619     Result = APValue(APSInt(I));
10620     Result.getInt().setIsUnsigned(
10621                             E->getType()->isUnsignedIntegerOrEnumerationType());
10622     return true;
10623   }
10624   bool Success(const llvm::APInt &I, const Expr *E) {
10625     return Success(I, E, Result);
10626   }
10627 
10628   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10629     assert(E->getType()->isIntegralOrEnumerationType() &&
10630            "Invalid evaluation result.");
10631     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10632     return true;
10633   }
10634   bool Success(uint64_t Value, const Expr *E) {
10635     return Success(Value, E, Result);
10636   }
10637 
10638   bool Success(CharUnits Size, const Expr *E) {
10639     return Success(Size.getQuantity(), E);
10640   }
10641 
10642   bool Success(const APValue &V, const Expr *E) {
10643     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10644       Result = V;
10645       return true;
10646     }
10647     return Success(V.getInt(), E);
10648   }
10649 
10650   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10651 
10652   //===--------------------------------------------------------------------===//
10653   //                            Visitor Methods
10654   //===--------------------------------------------------------------------===//
10655 
10656   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10657     return Success(E->getValue(), E);
10658   }
10659   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10660     return Success(E->getValue(), E);
10661   }
10662 
10663   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10664   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10665     if (CheckReferencedDecl(E, E->getDecl()))
10666       return true;
10667 
10668     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10669   }
10670   bool VisitMemberExpr(const MemberExpr *E) {
10671     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10672       VisitIgnoredBaseExpression(E->getBase());
10673       return true;
10674     }
10675 
10676     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10677   }
10678 
10679   bool VisitCallExpr(const CallExpr *E);
10680   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10681   bool VisitBinaryOperator(const BinaryOperator *E);
10682   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10683   bool VisitUnaryOperator(const UnaryOperator *E);
10684 
10685   bool VisitCastExpr(const CastExpr* E);
10686   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10687 
10688   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10689     return Success(E->getValue(), E);
10690   }
10691 
10692   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10693     return Success(E->getValue(), E);
10694   }
10695 
10696   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10697     if (Info.ArrayInitIndex == uint64_t(-1)) {
10698       // We were asked to evaluate this subexpression independent of the
10699       // enclosing ArrayInitLoopExpr. We can't do that.
10700       Info.FFDiag(E);
10701       return false;
10702     }
10703     return Success(Info.ArrayInitIndex, E);
10704   }
10705 
10706   // Note, GNU defines __null as an integer, not a pointer.
10707   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10708     return ZeroInitialization(E);
10709   }
10710 
10711   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10712     return Success(E->getValue(), E);
10713   }
10714 
10715   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10716     return Success(E->getValue(), E);
10717   }
10718 
10719   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10720     return Success(E->getValue(), E);
10721   }
10722 
10723   bool VisitUnaryReal(const UnaryOperator *E);
10724   bool VisitUnaryImag(const UnaryOperator *E);
10725 
10726   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10727   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10728   bool VisitSourceLocExpr(const SourceLocExpr *E);
10729   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10730   bool VisitRequiresExpr(const RequiresExpr *E);
10731   // FIXME: Missing: array subscript of vector, member of vector
10732 };
10733 
10734 class FixedPointExprEvaluator
10735     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10736   APValue &Result;
10737 
10738  public:
10739   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10740       : ExprEvaluatorBaseTy(info), Result(result) {}
10741 
10742   bool Success(const llvm::APInt &I, const Expr *E) {
10743     return Success(
10744         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10745   }
10746 
10747   bool Success(uint64_t Value, const Expr *E) {
10748     return Success(
10749         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10750   }
10751 
10752   bool Success(const APValue &V, const Expr *E) {
10753     return Success(V.getFixedPoint(), E);
10754   }
10755 
10756   bool Success(const APFixedPoint &V, const Expr *E) {
10757     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10758     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10759            "Invalid evaluation result.");
10760     Result = APValue(V);
10761     return true;
10762   }
10763 
10764   //===--------------------------------------------------------------------===//
10765   //                            Visitor Methods
10766   //===--------------------------------------------------------------------===//
10767 
10768   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10769     return Success(E->getValue(), E);
10770   }
10771 
10772   bool VisitCastExpr(const CastExpr *E);
10773   bool VisitUnaryOperator(const UnaryOperator *E);
10774   bool VisitBinaryOperator(const BinaryOperator *E);
10775 };
10776 } // end anonymous namespace
10777 
10778 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10779 /// produce either the integer value or a pointer.
10780 ///
10781 /// GCC has a heinous extension which folds casts between pointer types and
10782 /// pointer-sized integral types. We support this by allowing the evaluation of
10783 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10784 /// Some simple arithmetic on such values is supported (they are treated much
10785 /// like char*).
10786 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10787                                     EvalInfo &Info) {
10788   assert(!E->isValueDependent());
10789   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
10790   return IntExprEvaluator(Info, Result).Visit(E);
10791 }
10792 
10793 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10794   assert(!E->isValueDependent());
10795   APValue Val;
10796   if (!EvaluateIntegerOrLValue(E, Val, Info))
10797     return false;
10798   if (!Val.isInt()) {
10799     // FIXME: It would be better to produce the diagnostic for casting
10800     //        a pointer to an integer.
10801     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10802     return false;
10803   }
10804   Result = Val.getInt();
10805   return true;
10806 }
10807 
10808 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10809   APValue Evaluated = E->EvaluateInContext(
10810       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10811   return Success(Evaluated, E);
10812 }
10813 
10814 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10815                                EvalInfo &Info) {
10816   assert(!E->isValueDependent());
10817   if (E->getType()->isFixedPointType()) {
10818     APValue Val;
10819     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10820       return false;
10821     if (!Val.isFixedPoint())
10822       return false;
10823 
10824     Result = Val.getFixedPoint();
10825     return true;
10826   }
10827   return false;
10828 }
10829 
10830 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10831                                         EvalInfo &Info) {
10832   assert(!E->isValueDependent());
10833   if (E->getType()->isIntegerType()) {
10834     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10835     APSInt Val;
10836     if (!EvaluateInteger(E, Val, Info))
10837       return false;
10838     Result = APFixedPoint(Val, FXSema);
10839     return true;
10840   } else if (E->getType()->isFixedPointType()) {
10841     return EvaluateFixedPoint(E, Result, Info);
10842   }
10843   return false;
10844 }
10845 
10846 /// Check whether the given declaration can be directly converted to an integral
10847 /// rvalue. If not, no diagnostic is produced; there are other things we can
10848 /// try.
10849 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10850   // Enums are integer constant exprs.
10851   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10852     // Check for signedness/width mismatches between E type and ECD value.
10853     bool SameSign = (ECD->getInitVal().isSigned()
10854                      == E->getType()->isSignedIntegerOrEnumerationType());
10855     bool SameWidth = (ECD->getInitVal().getBitWidth()
10856                       == Info.Ctx.getIntWidth(E->getType()));
10857     if (SameSign && SameWidth)
10858       return Success(ECD->getInitVal(), E);
10859     else {
10860       // Get rid of mismatch (otherwise Success assertions will fail)
10861       // by computing a new value matching the type of E.
10862       llvm::APSInt Val = ECD->getInitVal();
10863       if (!SameSign)
10864         Val.setIsSigned(!ECD->getInitVal().isSigned());
10865       if (!SameWidth)
10866         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10867       return Success(Val, E);
10868     }
10869   }
10870   return false;
10871 }
10872 
10873 /// Values returned by __builtin_classify_type, chosen to match the values
10874 /// produced by GCC's builtin.
10875 enum class GCCTypeClass {
10876   None = -1,
10877   Void = 0,
10878   Integer = 1,
10879   // GCC reserves 2 for character types, but instead classifies them as
10880   // integers.
10881   Enum = 3,
10882   Bool = 4,
10883   Pointer = 5,
10884   // GCC reserves 6 for references, but appears to never use it (because
10885   // expressions never have reference type, presumably).
10886   PointerToDataMember = 7,
10887   RealFloat = 8,
10888   Complex = 9,
10889   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10890   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10891   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10892   // uses 12 for that purpose, same as for a class or struct. Maybe it
10893   // internally implements a pointer to member as a struct?  Who knows.
10894   PointerToMemberFunction = 12, // Not a bug, see above.
10895   ClassOrStruct = 12,
10896   Union = 13,
10897   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10898   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10899   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10900   // literals.
10901 };
10902 
10903 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10904 /// as GCC.
10905 static GCCTypeClass
10906 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10907   assert(!T->isDependentType() && "unexpected dependent type");
10908 
10909   QualType CanTy = T.getCanonicalType();
10910   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10911 
10912   switch (CanTy->getTypeClass()) {
10913 #define TYPE(ID, BASE)
10914 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10915 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10916 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10917 #include "clang/AST/TypeNodes.inc"
10918   case Type::Auto:
10919   case Type::DeducedTemplateSpecialization:
10920       llvm_unreachable("unexpected non-canonical or dependent type");
10921 
10922   case Type::Builtin:
10923     switch (BT->getKind()) {
10924 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10925 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10926     case BuiltinType::ID: return GCCTypeClass::Integer;
10927 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10928     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10929 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10930     case BuiltinType::ID: break;
10931 #include "clang/AST/BuiltinTypes.def"
10932     case BuiltinType::Void:
10933       return GCCTypeClass::Void;
10934 
10935     case BuiltinType::Bool:
10936       return GCCTypeClass::Bool;
10937 
10938     case BuiltinType::Char_U:
10939     case BuiltinType::UChar:
10940     case BuiltinType::WChar_U:
10941     case BuiltinType::Char8:
10942     case BuiltinType::Char16:
10943     case BuiltinType::Char32:
10944     case BuiltinType::UShort:
10945     case BuiltinType::UInt:
10946     case BuiltinType::ULong:
10947     case BuiltinType::ULongLong:
10948     case BuiltinType::UInt128:
10949       return GCCTypeClass::Integer;
10950 
10951     case BuiltinType::UShortAccum:
10952     case BuiltinType::UAccum:
10953     case BuiltinType::ULongAccum:
10954     case BuiltinType::UShortFract:
10955     case BuiltinType::UFract:
10956     case BuiltinType::ULongFract:
10957     case BuiltinType::SatUShortAccum:
10958     case BuiltinType::SatUAccum:
10959     case BuiltinType::SatULongAccum:
10960     case BuiltinType::SatUShortFract:
10961     case BuiltinType::SatUFract:
10962     case BuiltinType::SatULongFract:
10963       return GCCTypeClass::None;
10964 
10965     case BuiltinType::NullPtr:
10966 
10967     case BuiltinType::ObjCId:
10968     case BuiltinType::ObjCClass:
10969     case BuiltinType::ObjCSel:
10970 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10971     case BuiltinType::Id:
10972 #include "clang/Basic/OpenCLImageTypes.def"
10973 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10974     case BuiltinType::Id:
10975 #include "clang/Basic/OpenCLExtensionTypes.def"
10976     case BuiltinType::OCLSampler:
10977     case BuiltinType::OCLEvent:
10978     case BuiltinType::OCLClkEvent:
10979     case BuiltinType::OCLQueue:
10980     case BuiltinType::OCLReserveID:
10981 #define SVE_TYPE(Name, Id, SingletonId) \
10982     case BuiltinType::Id:
10983 #include "clang/Basic/AArch64SVEACLETypes.def"
10984 #define PPC_VECTOR_TYPE(Name, Id, Size) \
10985     case BuiltinType::Id:
10986 #include "clang/Basic/PPCTypes.def"
10987 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
10988 #include "clang/Basic/RISCVVTypes.def"
10989       return GCCTypeClass::None;
10990 
10991     case BuiltinType::Dependent:
10992       llvm_unreachable("unexpected dependent type");
10993     };
10994     llvm_unreachable("unexpected placeholder type");
10995 
10996   case Type::Enum:
10997     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
10998 
10999   case Type::Pointer:
11000   case Type::ConstantArray:
11001   case Type::VariableArray:
11002   case Type::IncompleteArray:
11003   case Type::FunctionNoProto:
11004   case Type::FunctionProto:
11005     return GCCTypeClass::Pointer;
11006 
11007   case Type::MemberPointer:
11008     return CanTy->isMemberDataPointerType()
11009                ? GCCTypeClass::PointerToDataMember
11010                : GCCTypeClass::PointerToMemberFunction;
11011 
11012   case Type::Complex:
11013     return GCCTypeClass::Complex;
11014 
11015   case Type::Record:
11016     return CanTy->isUnionType() ? GCCTypeClass::Union
11017                                 : GCCTypeClass::ClassOrStruct;
11018 
11019   case Type::Atomic:
11020     // GCC classifies _Atomic T the same as T.
11021     return EvaluateBuiltinClassifyType(
11022         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11023 
11024   case Type::BlockPointer:
11025   case Type::Vector:
11026   case Type::ExtVector:
11027   case Type::ConstantMatrix:
11028   case Type::ObjCObject:
11029   case Type::ObjCInterface:
11030   case Type::ObjCObjectPointer:
11031   case Type::Pipe:
11032   case Type::ExtInt:
11033     // GCC classifies vectors as None. We follow its lead and classify all
11034     // other types that don't fit into the regular classification the same way.
11035     return GCCTypeClass::None;
11036 
11037   case Type::LValueReference:
11038   case Type::RValueReference:
11039     llvm_unreachable("invalid type for expression");
11040   }
11041 
11042   llvm_unreachable("unexpected type class");
11043 }
11044 
11045 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11046 /// as GCC.
11047 static GCCTypeClass
11048 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11049   // If no argument was supplied, default to None. This isn't
11050   // ideal, however it is what gcc does.
11051   if (E->getNumArgs() == 0)
11052     return GCCTypeClass::None;
11053 
11054   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11055   // being an ICE, but still folds it to a constant using the type of the first
11056   // argument.
11057   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11058 }
11059 
11060 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11061 /// __builtin_constant_p when applied to the given pointer.
11062 ///
11063 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11064 /// or it points to the first character of a string literal.
11065 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11066   APValue::LValueBase Base = LV.getLValueBase();
11067   if (Base.isNull()) {
11068     // A null base is acceptable.
11069     return true;
11070   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11071     if (!isa<StringLiteral>(E))
11072       return false;
11073     return LV.getLValueOffset().isZero();
11074   } else if (Base.is<TypeInfoLValue>()) {
11075     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11076     // evaluate to true.
11077     return true;
11078   } else {
11079     // Any other base is not constant enough for GCC.
11080     return false;
11081   }
11082 }
11083 
11084 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11085 /// GCC as we can manage.
11086 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11087   // This evaluation is not permitted to have side-effects, so evaluate it in
11088   // a speculative evaluation context.
11089   SpeculativeEvaluationRAII SpeculativeEval(Info);
11090 
11091   // Constant-folding is always enabled for the operand of __builtin_constant_p
11092   // (even when the enclosing evaluation context otherwise requires a strict
11093   // language-specific constant expression).
11094   FoldConstant Fold(Info, true);
11095 
11096   QualType ArgType = Arg->getType();
11097 
11098   // __builtin_constant_p always has one operand. The rules which gcc follows
11099   // are not precisely documented, but are as follows:
11100   //
11101   //  - If the operand is of integral, floating, complex or enumeration type,
11102   //    and can be folded to a known value of that type, it returns 1.
11103   //  - If the operand can be folded to a pointer to the first character
11104   //    of a string literal (or such a pointer cast to an integral type)
11105   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11106   //
11107   // Otherwise, it returns 0.
11108   //
11109   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11110   // its support for this did not work prior to GCC 9 and is not yet well
11111   // understood.
11112   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11113       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11114       ArgType->isNullPtrType()) {
11115     APValue V;
11116     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11117       Fold.keepDiagnostics();
11118       return false;
11119     }
11120 
11121     // For a pointer (possibly cast to integer), there are special rules.
11122     if (V.getKind() == APValue::LValue)
11123       return EvaluateBuiltinConstantPForLValue(V);
11124 
11125     // Otherwise, any constant value is good enough.
11126     return V.hasValue();
11127   }
11128 
11129   // Anything else isn't considered to be sufficiently constant.
11130   return false;
11131 }
11132 
11133 /// Retrieves the "underlying object type" of the given expression,
11134 /// as used by __builtin_object_size.
11135 static QualType getObjectType(APValue::LValueBase B) {
11136   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11137     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11138       return VD->getType();
11139   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11140     if (isa<CompoundLiteralExpr>(E))
11141       return E->getType();
11142   } else if (B.is<TypeInfoLValue>()) {
11143     return B.getTypeInfoType();
11144   } else if (B.is<DynamicAllocLValue>()) {
11145     return B.getDynamicAllocType();
11146   }
11147 
11148   return QualType();
11149 }
11150 
11151 /// A more selective version of E->IgnoreParenCasts for
11152 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11153 /// to change the type of E.
11154 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11155 ///
11156 /// Always returns an RValue with a pointer representation.
11157 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11158   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
11159 
11160   auto *NoParens = E->IgnoreParens();
11161   auto *Cast = dyn_cast<CastExpr>(NoParens);
11162   if (Cast == nullptr)
11163     return NoParens;
11164 
11165   // We only conservatively allow a few kinds of casts, because this code is
11166   // inherently a simple solution that seeks to support the common case.
11167   auto CastKind = Cast->getCastKind();
11168   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11169       CastKind != CK_AddressSpaceConversion)
11170     return NoParens;
11171 
11172   auto *SubExpr = Cast->getSubExpr();
11173   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
11174     return NoParens;
11175   return ignorePointerCastsAndParens(SubExpr);
11176 }
11177 
11178 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11179 /// record layout. e.g.
11180 ///   struct { struct { int a, b; } fst, snd; } obj;
11181 ///   obj.fst   // no
11182 ///   obj.snd   // yes
11183 ///   obj.fst.a // no
11184 ///   obj.fst.b // no
11185 ///   obj.snd.a // no
11186 ///   obj.snd.b // yes
11187 ///
11188 /// Please note: this function is specialized for how __builtin_object_size
11189 /// views "objects".
11190 ///
11191 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11192 /// correct result, it will always return true.
11193 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11194   assert(!LVal.Designator.Invalid);
11195 
11196   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11197     const RecordDecl *Parent = FD->getParent();
11198     Invalid = Parent->isInvalidDecl();
11199     if (Invalid || Parent->isUnion())
11200       return true;
11201     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11202     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11203   };
11204 
11205   auto &Base = LVal.getLValueBase();
11206   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11207     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11208       bool Invalid;
11209       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11210         return Invalid;
11211     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11212       for (auto *FD : IFD->chain()) {
11213         bool Invalid;
11214         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11215           return Invalid;
11216       }
11217     }
11218   }
11219 
11220   unsigned I = 0;
11221   QualType BaseType = getType(Base);
11222   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11223     // If we don't know the array bound, conservatively assume we're looking at
11224     // the final array element.
11225     ++I;
11226     if (BaseType->isIncompleteArrayType())
11227       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11228     else
11229       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11230   }
11231 
11232   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11233     const auto &Entry = LVal.Designator.Entries[I];
11234     if (BaseType->isArrayType()) {
11235       // Because __builtin_object_size treats arrays as objects, we can ignore
11236       // the index iff this is the last array in the Designator.
11237       if (I + 1 == E)
11238         return true;
11239       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11240       uint64_t Index = Entry.getAsArrayIndex();
11241       if (Index + 1 != CAT->getSize())
11242         return false;
11243       BaseType = CAT->getElementType();
11244     } else if (BaseType->isAnyComplexType()) {
11245       const auto *CT = BaseType->castAs<ComplexType>();
11246       uint64_t Index = Entry.getAsArrayIndex();
11247       if (Index != 1)
11248         return false;
11249       BaseType = CT->getElementType();
11250     } else if (auto *FD = getAsField(Entry)) {
11251       bool Invalid;
11252       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11253         return Invalid;
11254       BaseType = FD->getType();
11255     } else {
11256       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11257       return false;
11258     }
11259   }
11260   return true;
11261 }
11262 
11263 /// Tests to see if the LValue has a user-specified designator (that isn't
11264 /// necessarily valid). Note that this always returns 'true' if the LValue has
11265 /// an unsized array as its first designator entry, because there's currently no
11266 /// way to tell if the user typed *foo or foo[0].
11267 static bool refersToCompleteObject(const LValue &LVal) {
11268   if (LVal.Designator.Invalid)
11269     return false;
11270 
11271   if (!LVal.Designator.Entries.empty())
11272     return LVal.Designator.isMostDerivedAnUnsizedArray();
11273 
11274   if (!LVal.InvalidBase)
11275     return true;
11276 
11277   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11278   // the LValueBase.
11279   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11280   return !E || !isa<MemberExpr>(E);
11281 }
11282 
11283 /// Attempts to detect a user writing into a piece of memory that's impossible
11284 /// to figure out the size of by just using types.
11285 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11286   const SubobjectDesignator &Designator = LVal.Designator;
11287   // Notes:
11288   // - Users can only write off of the end when we have an invalid base. Invalid
11289   //   bases imply we don't know where the memory came from.
11290   // - We used to be a bit more aggressive here; we'd only be conservative if
11291   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11292   //   broke some common standard library extensions (PR30346), but was
11293   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11294   //   with some sort of list. OTOH, it seems that GCC is always
11295   //   conservative with the last element in structs (if it's an array), so our
11296   //   current behavior is more compatible than an explicit list approach would
11297   //   be.
11298   return LVal.InvalidBase &&
11299          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11300          Designator.MostDerivedIsArrayElement &&
11301          isDesignatorAtObjectEnd(Ctx, LVal);
11302 }
11303 
11304 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11305 /// Fails if the conversion would cause loss of precision.
11306 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11307                                             CharUnits &Result) {
11308   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11309   if (Int.ugt(CharUnitsMax))
11310     return false;
11311   Result = CharUnits::fromQuantity(Int.getZExtValue());
11312   return true;
11313 }
11314 
11315 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11316 /// determine how many bytes exist from the beginning of the object to either
11317 /// the end of the current subobject, or the end of the object itself, depending
11318 /// on what the LValue looks like + the value of Type.
11319 ///
11320 /// If this returns false, the value of Result is undefined.
11321 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11322                                unsigned Type, const LValue &LVal,
11323                                CharUnits &EndOffset) {
11324   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11325 
11326   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11327     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11328       return false;
11329     return HandleSizeof(Info, ExprLoc, Ty, Result);
11330   };
11331 
11332   // We want to evaluate the size of the entire object. This is a valid fallback
11333   // for when Type=1 and the designator is invalid, because we're asked for an
11334   // upper-bound.
11335   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11336     // Type=3 wants a lower bound, so we can't fall back to this.
11337     if (Type == 3 && !DetermineForCompleteObject)
11338       return false;
11339 
11340     llvm::APInt APEndOffset;
11341     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11342         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11343       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11344 
11345     if (LVal.InvalidBase)
11346       return false;
11347 
11348     QualType BaseTy = getObjectType(LVal.getLValueBase());
11349     return CheckedHandleSizeof(BaseTy, EndOffset);
11350   }
11351 
11352   // We want to evaluate the size of a subobject.
11353   const SubobjectDesignator &Designator = LVal.Designator;
11354 
11355   // The following is a moderately common idiom in C:
11356   //
11357   // struct Foo { int a; char c[1]; };
11358   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11359   // strcpy(&F->c[0], Bar);
11360   //
11361   // In order to not break too much legacy code, we need to support it.
11362   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11363     // If we can resolve this to an alloc_size call, we can hand that back,
11364     // because we know for certain how many bytes there are to write to.
11365     llvm::APInt APEndOffset;
11366     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11367         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11368       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11369 
11370     // If we cannot determine the size of the initial allocation, then we can't
11371     // given an accurate upper-bound. However, we are still able to give
11372     // conservative lower-bounds for Type=3.
11373     if (Type == 1)
11374       return false;
11375   }
11376 
11377   CharUnits BytesPerElem;
11378   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11379     return false;
11380 
11381   // According to the GCC documentation, we want the size of the subobject
11382   // denoted by the pointer. But that's not quite right -- what we actually
11383   // want is the size of the immediately-enclosing array, if there is one.
11384   int64_t ElemsRemaining;
11385   if (Designator.MostDerivedIsArrayElement &&
11386       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11387     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11388     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11389     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11390   } else {
11391     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11392   }
11393 
11394   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11395   return true;
11396 }
11397 
11398 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11399 /// returns true and stores the result in @p Size.
11400 ///
11401 /// If @p WasError is non-null, this will report whether the failure to evaluate
11402 /// is to be treated as an Error in IntExprEvaluator.
11403 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11404                                          EvalInfo &Info, uint64_t &Size) {
11405   // Determine the denoted object.
11406   LValue LVal;
11407   {
11408     // The operand of __builtin_object_size is never evaluated for side-effects.
11409     // If there are any, but we can determine the pointed-to object anyway, then
11410     // ignore the side-effects.
11411     SpeculativeEvaluationRAII SpeculativeEval(Info);
11412     IgnoreSideEffectsRAII Fold(Info);
11413 
11414     if (E->isGLValue()) {
11415       // It's possible for us to be given GLValues if we're called via
11416       // Expr::tryEvaluateObjectSize.
11417       APValue RVal;
11418       if (!EvaluateAsRValue(Info, E, RVal))
11419         return false;
11420       LVal.setFrom(Info.Ctx, RVal);
11421     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11422                                 /*InvalidBaseOK=*/true))
11423       return false;
11424   }
11425 
11426   // If we point to before the start of the object, there are no accessible
11427   // bytes.
11428   if (LVal.getLValueOffset().isNegative()) {
11429     Size = 0;
11430     return true;
11431   }
11432 
11433   CharUnits EndOffset;
11434   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11435     return false;
11436 
11437   // If we've fallen outside of the end offset, just pretend there's nothing to
11438   // write to/read from.
11439   if (EndOffset <= LVal.getLValueOffset())
11440     Size = 0;
11441   else
11442     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11443   return true;
11444 }
11445 
11446 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11447   if (unsigned BuiltinOp = E->getBuiltinCallee())
11448     return VisitBuiltinCallExpr(E, BuiltinOp);
11449 
11450   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11451 }
11452 
11453 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11454                                      APValue &Val, APSInt &Alignment) {
11455   QualType SrcTy = E->getArg(0)->getType();
11456   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11457     return false;
11458   // Even though we are evaluating integer expressions we could get a pointer
11459   // argument for the __builtin_is_aligned() case.
11460   if (SrcTy->isPointerType()) {
11461     LValue Ptr;
11462     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11463       return false;
11464     Ptr.moveInto(Val);
11465   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11466     Info.FFDiag(E->getArg(0));
11467     return false;
11468   } else {
11469     APSInt SrcInt;
11470     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11471       return false;
11472     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11473            "Bit widths must be the same");
11474     Val = APValue(SrcInt);
11475   }
11476   assert(Val.hasValue());
11477   return true;
11478 }
11479 
11480 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11481                                             unsigned BuiltinOp) {
11482   switch (BuiltinOp) {
11483   default:
11484     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11485 
11486   case Builtin::BI__builtin_dynamic_object_size:
11487   case Builtin::BI__builtin_object_size: {
11488     // The type was checked when we built the expression.
11489     unsigned Type =
11490         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11491     assert(Type <= 3 && "unexpected type");
11492 
11493     uint64_t Size;
11494     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11495       return Success(Size, E);
11496 
11497     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11498       return Success((Type & 2) ? 0 : -1, E);
11499 
11500     // Expression had no side effects, but we couldn't statically determine the
11501     // size of the referenced object.
11502     switch (Info.EvalMode) {
11503     case EvalInfo::EM_ConstantExpression:
11504     case EvalInfo::EM_ConstantFold:
11505     case EvalInfo::EM_IgnoreSideEffects:
11506       // Leave it to IR generation.
11507       return Error(E);
11508     case EvalInfo::EM_ConstantExpressionUnevaluated:
11509       // Reduce it to a constant now.
11510       return Success((Type & 2) ? 0 : -1, E);
11511     }
11512 
11513     llvm_unreachable("unexpected EvalMode");
11514   }
11515 
11516   case Builtin::BI__builtin_os_log_format_buffer_size: {
11517     analyze_os_log::OSLogBufferLayout Layout;
11518     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11519     return Success(Layout.size().getQuantity(), E);
11520   }
11521 
11522   case Builtin::BI__builtin_is_aligned: {
11523     APValue Src;
11524     APSInt Alignment;
11525     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11526       return false;
11527     if (Src.isLValue()) {
11528       // If we evaluated a pointer, check the minimum known alignment.
11529       LValue Ptr;
11530       Ptr.setFrom(Info.Ctx, Src);
11531       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11532       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11533       // We can return true if the known alignment at the computed offset is
11534       // greater than the requested alignment.
11535       assert(PtrAlign.isPowerOfTwo());
11536       assert(Alignment.isPowerOf2());
11537       if (PtrAlign.getQuantity() >= Alignment)
11538         return Success(1, E);
11539       // If the alignment is not known to be sufficient, some cases could still
11540       // be aligned at run time. However, if the requested alignment is less or
11541       // equal to the base alignment and the offset is not aligned, we know that
11542       // the run-time value can never be aligned.
11543       if (BaseAlignment.getQuantity() >= Alignment &&
11544           PtrAlign.getQuantity() < Alignment)
11545         return Success(0, E);
11546       // Otherwise we can't infer whether the value is sufficiently aligned.
11547       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11548       //  in cases where we can't fully evaluate the pointer.
11549       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11550           << Alignment;
11551       return false;
11552     }
11553     assert(Src.isInt());
11554     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11555   }
11556   case Builtin::BI__builtin_align_up: {
11557     APValue Src;
11558     APSInt Alignment;
11559     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11560       return false;
11561     if (!Src.isInt())
11562       return Error(E);
11563     APSInt AlignedVal =
11564         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11565                Src.getInt().isUnsigned());
11566     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11567     return Success(AlignedVal, E);
11568   }
11569   case Builtin::BI__builtin_align_down: {
11570     APValue Src;
11571     APSInt Alignment;
11572     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11573       return false;
11574     if (!Src.isInt())
11575       return Error(E);
11576     APSInt AlignedVal =
11577         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11578     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11579     return Success(AlignedVal, E);
11580   }
11581 
11582   case Builtin::BI__builtin_bitreverse8:
11583   case Builtin::BI__builtin_bitreverse16:
11584   case Builtin::BI__builtin_bitreverse32:
11585   case Builtin::BI__builtin_bitreverse64: {
11586     APSInt Val;
11587     if (!EvaluateInteger(E->getArg(0), Val, Info))
11588       return false;
11589 
11590     return Success(Val.reverseBits(), E);
11591   }
11592 
11593   case Builtin::BI__builtin_bswap16:
11594   case Builtin::BI__builtin_bswap32:
11595   case Builtin::BI__builtin_bswap64: {
11596     APSInt Val;
11597     if (!EvaluateInteger(E->getArg(0), Val, Info))
11598       return false;
11599 
11600     return Success(Val.byteSwap(), E);
11601   }
11602 
11603   case Builtin::BI__builtin_classify_type:
11604     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11605 
11606   case Builtin::BI__builtin_clrsb:
11607   case Builtin::BI__builtin_clrsbl:
11608   case Builtin::BI__builtin_clrsbll: {
11609     APSInt Val;
11610     if (!EvaluateInteger(E->getArg(0), Val, Info))
11611       return false;
11612 
11613     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11614   }
11615 
11616   case Builtin::BI__builtin_clz:
11617   case Builtin::BI__builtin_clzl:
11618   case Builtin::BI__builtin_clzll:
11619   case Builtin::BI__builtin_clzs: {
11620     APSInt Val;
11621     if (!EvaluateInteger(E->getArg(0), Val, Info))
11622       return false;
11623     if (!Val)
11624       return Error(E);
11625 
11626     return Success(Val.countLeadingZeros(), E);
11627   }
11628 
11629   case Builtin::BI__builtin_constant_p: {
11630     const Expr *Arg = E->getArg(0);
11631     if (EvaluateBuiltinConstantP(Info, Arg))
11632       return Success(true, E);
11633     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11634       // Outside a constant context, eagerly evaluate to false in the presence
11635       // of side-effects in order to avoid -Wunsequenced false-positives in
11636       // a branch on __builtin_constant_p(expr).
11637       return Success(false, E);
11638     }
11639     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11640     return false;
11641   }
11642 
11643   case Builtin::BI__builtin_is_constant_evaluated: {
11644     const auto *Callee = Info.CurrentCall->getCallee();
11645     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11646         (Info.CallStackDepth == 1 ||
11647          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11648           Callee->getIdentifier() &&
11649           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11650       // FIXME: Find a better way to avoid duplicated diagnostics.
11651       if (Info.EvalStatus.Diag)
11652         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11653                                                : Info.CurrentCall->CallLoc,
11654                     diag::warn_is_constant_evaluated_always_true_constexpr)
11655             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11656                                          : "std::is_constant_evaluated");
11657     }
11658 
11659     return Success(Info.InConstantContext, E);
11660   }
11661 
11662   case Builtin::BI__builtin_ctz:
11663   case Builtin::BI__builtin_ctzl:
11664   case Builtin::BI__builtin_ctzll:
11665   case Builtin::BI__builtin_ctzs: {
11666     APSInt Val;
11667     if (!EvaluateInteger(E->getArg(0), Val, Info))
11668       return false;
11669     if (!Val)
11670       return Error(E);
11671 
11672     return Success(Val.countTrailingZeros(), E);
11673   }
11674 
11675   case Builtin::BI__builtin_eh_return_data_regno: {
11676     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11677     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11678     return Success(Operand, E);
11679   }
11680 
11681   case Builtin::BI__builtin_expect:
11682   case Builtin::BI__builtin_expect_with_probability:
11683     return Visit(E->getArg(0));
11684 
11685   case Builtin::BI__builtin_ffs:
11686   case Builtin::BI__builtin_ffsl:
11687   case Builtin::BI__builtin_ffsll: {
11688     APSInt Val;
11689     if (!EvaluateInteger(E->getArg(0), Val, Info))
11690       return false;
11691 
11692     unsigned N = Val.countTrailingZeros();
11693     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11694   }
11695 
11696   case Builtin::BI__builtin_fpclassify: {
11697     APFloat Val(0.0);
11698     if (!EvaluateFloat(E->getArg(5), Val, Info))
11699       return false;
11700     unsigned Arg;
11701     switch (Val.getCategory()) {
11702     case APFloat::fcNaN: Arg = 0; break;
11703     case APFloat::fcInfinity: Arg = 1; break;
11704     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11705     case APFloat::fcZero: Arg = 4; break;
11706     }
11707     return Visit(E->getArg(Arg));
11708   }
11709 
11710   case Builtin::BI__builtin_isinf_sign: {
11711     APFloat Val(0.0);
11712     return EvaluateFloat(E->getArg(0), Val, Info) &&
11713            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11714   }
11715 
11716   case Builtin::BI__builtin_isinf: {
11717     APFloat Val(0.0);
11718     return EvaluateFloat(E->getArg(0), Val, Info) &&
11719            Success(Val.isInfinity() ? 1 : 0, E);
11720   }
11721 
11722   case Builtin::BI__builtin_isfinite: {
11723     APFloat Val(0.0);
11724     return EvaluateFloat(E->getArg(0), Val, Info) &&
11725            Success(Val.isFinite() ? 1 : 0, E);
11726   }
11727 
11728   case Builtin::BI__builtin_isnan: {
11729     APFloat Val(0.0);
11730     return EvaluateFloat(E->getArg(0), Val, Info) &&
11731            Success(Val.isNaN() ? 1 : 0, E);
11732   }
11733 
11734   case Builtin::BI__builtin_isnormal: {
11735     APFloat Val(0.0);
11736     return EvaluateFloat(E->getArg(0), Val, Info) &&
11737            Success(Val.isNormal() ? 1 : 0, E);
11738   }
11739 
11740   case Builtin::BI__builtin_parity:
11741   case Builtin::BI__builtin_parityl:
11742   case Builtin::BI__builtin_parityll: {
11743     APSInt Val;
11744     if (!EvaluateInteger(E->getArg(0), Val, Info))
11745       return false;
11746 
11747     return Success(Val.countPopulation() % 2, E);
11748   }
11749 
11750   case Builtin::BI__builtin_popcount:
11751   case Builtin::BI__builtin_popcountl:
11752   case Builtin::BI__builtin_popcountll: {
11753     APSInt Val;
11754     if (!EvaluateInteger(E->getArg(0), Val, Info))
11755       return false;
11756 
11757     return Success(Val.countPopulation(), E);
11758   }
11759 
11760   case Builtin::BI__builtin_rotateleft8:
11761   case Builtin::BI__builtin_rotateleft16:
11762   case Builtin::BI__builtin_rotateleft32:
11763   case Builtin::BI__builtin_rotateleft64:
11764   case Builtin::BI_rotl8: // Microsoft variants of rotate right
11765   case Builtin::BI_rotl16:
11766   case Builtin::BI_rotl:
11767   case Builtin::BI_lrotl:
11768   case Builtin::BI_rotl64: {
11769     APSInt Val, Amt;
11770     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11771         !EvaluateInteger(E->getArg(1), Amt, Info))
11772       return false;
11773 
11774     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
11775   }
11776 
11777   case Builtin::BI__builtin_rotateright8:
11778   case Builtin::BI__builtin_rotateright16:
11779   case Builtin::BI__builtin_rotateright32:
11780   case Builtin::BI__builtin_rotateright64:
11781   case Builtin::BI_rotr8: // Microsoft variants of rotate right
11782   case Builtin::BI_rotr16:
11783   case Builtin::BI_rotr:
11784   case Builtin::BI_lrotr:
11785   case Builtin::BI_rotr64: {
11786     APSInt Val, Amt;
11787     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11788         !EvaluateInteger(E->getArg(1), Amt, Info))
11789       return false;
11790 
11791     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
11792   }
11793 
11794   case Builtin::BIstrlen:
11795   case Builtin::BIwcslen:
11796     // A call to strlen is not a constant expression.
11797     if (Info.getLangOpts().CPlusPlus11)
11798       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11799         << /*isConstexpr*/0 << /*isConstructor*/0
11800         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11801     else
11802       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11803     LLVM_FALLTHROUGH;
11804   case Builtin::BI__builtin_strlen:
11805   case Builtin::BI__builtin_wcslen: {
11806     // As an extension, we support __builtin_strlen() as a constant expression,
11807     // and support folding strlen() to a constant.
11808     LValue String;
11809     if (!EvaluatePointer(E->getArg(0), String, Info))
11810       return false;
11811 
11812     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
11813 
11814     // Fast path: if it's a string literal, search the string value.
11815     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
11816             String.getLValueBase().dyn_cast<const Expr *>())) {
11817       // The string literal may have embedded null characters. Find the first
11818       // one and truncate there.
11819       StringRef Str = S->getBytes();
11820       int64_t Off = String.Offset.getQuantity();
11821       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
11822           S->getCharByteWidth() == 1 &&
11823           // FIXME: Add fast-path for wchar_t too.
11824           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
11825         Str = Str.substr(Off);
11826 
11827         StringRef::size_type Pos = Str.find(0);
11828         if (Pos != StringRef::npos)
11829           Str = Str.substr(0, Pos);
11830 
11831         return Success(Str.size(), E);
11832       }
11833 
11834       // Fall through to slow path to issue appropriate diagnostic.
11835     }
11836 
11837     // Slow path: scan the bytes of the string looking for the terminating 0.
11838     for (uint64_t Strlen = 0; /**/; ++Strlen) {
11839       APValue Char;
11840       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
11841           !Char.isInt())
11842         return false;
11843       if (!Char.getInt())
11844         return Success(Strlen, E);
11845       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
11846         return false;
11847     }
11848   }
11849 
11850   case Builtin::BIstrcmp:
11851   case Builtin::BIwcscmp:
11852   case Builtin::BIstrncmp:
11853   case Builtin::BIwcsncmp:
11854   case Builtin::BImemcmp:
11855   case Builtin::BIbcmp:
11856   case Builtin::BIwmemcmp:
11857     // A call to strlen is not a constant expression.
11858     if (Info.getLangOpts().CPlusPlus11)
11859       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11860         << /*isConstexpr*/0 << /*isConstructor*/0
11861         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11862     else
11863       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11864     LLVM_FALLTHROUGH;
11865   case Builtin::BI__builtin_strcmp:
11866   case Builtin::BI__builtin_wcscmp:
11867   case Builtin::BI__builtin_strncmp:
11868   case Builtin::BI__builtin_wcsncmp:
11869   case Builtin::BI__builtin_memcmp:
11870   case Builtin::BI__builtin_bcmp:
11871   case Builtin::BI__builtin_wmemcmp: {
11872     LValue String1, String2;
11873     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11874         !EvaluatePointer(E->getArg(1), String2, Info))
11875       return false;
11876 
11877     uint64_t MaxLength = uint64_t(-1);
11878     if (BuiltinOp != Builtin::BIstrcmp &&
11879         BuiltinOp != Builtin::BIwcscmp &&
11880         BuiltinOp != Builtin::BI__builtin_strcmp &&
11881         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11882       APSInt N;
11883       if (!EvaluateInteger(E->getArg(2), N, Info))
11884         return false;
11885       MaxLength = N.getExtValue();
11886     }
11887 
11888     // Empty substrings compare equal by definition.
11889     if (MaxLength == 0u)
11890       return Success(0, E);
11891 
11892     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11893         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11894         String1.Designator.Invalid || String2.Designator.Invalid)
11895       return false;
11896 
11897     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11898     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11899 
11900     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11901                      BuiltinOp == Builtin::BIbcmp ||
11902                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11903                      BuiltinOp == Builtin::BI__builtin_bcmp;
11904 
11905     assert(IsRawByte ||
11906            (Info.Ctx.hasSameUnqualifiedType(
11907                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11908             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11909 
11910     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
11911     // 'char8_t', but no other types.
11912     if (IsRawByte &&
11913         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
11914       // FIXME: Consider using our bit_cast implementation to support this.
11915       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
11916           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
11917           << CharTy1 << CharTy2;
11918       return false;
11919     }
11920 
11921     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11922       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11923              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11924              Char1.isInt() && Char2.isInt();
11925     };
11926     const auto &AdvanceElems = [&] {
11927       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11928              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11929     };
11930 
11931     bool StopAtNull =
11932         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11933          BuiltinOp != Builtin::BIwmemcmp &&
11934          BuiltinOp != Builtin::BI__builtin_memcmp &&
11935          BuiltinOp != Builtin::BI__builtin_bcmp &&
11936          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11937     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11938                   BuiltinOp == Builtin::BIwcsncmp ||
11939                   BuiltinOp == Builtin::BIwmemcmp ||
11940                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11941                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11942                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11943 
11944     for (; MaxLength; --MaxLength) {
11945       APValue Char1, Char2;
11946       if (!ReadCurElems(Char1, Char2))
11947         return false;
11948       if (Char1.getInt().ne(Char2.getInt())) {
11949         if (IsWide) // wmemcmp compares with wchar_t signedness.
11950           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11951         // memcmp always compares unsigned chars.
11952         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11953       }
11954       if (StopAtNull && !Char1.getInt())
11955         return Success(0, E);
11956       assert(!(StopAtNull && !Char2.getInt()));
11957       if (!AdvanceElems())
11958         return false;
11959     }
11960     // We hit the strncmp / memcmp limit.
11961     return Success(0, E);
11962   }
11963 
11964   case Builtin::BI__atomic_always_lock_free:
11965   case Builtin::BI__atomic_is_lock_free:
11966   case Builtin::BI__c11_atomic_is_lock_free: {
11967     APSInt SizeVal;
11968     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11969       return false;
11970 
11971     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11972     // of two less than or equal to the maximum inline atomic width, we know it
11973     // is lock-free.  If the size isn't a power of two, or greater than the
11974     // maximum alignment where we promote atomics, we know it is not lock-free
11975     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11976     // the answer can only be determined at runtime; for example, 16-byte
11977     // atomics have lock-free implementations on some, but not all,
11978     // x86-64 processors.
11979 
11980     // Check power-of-two.
11981     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11982     if (Size.isPowerOfTwo()) {
11983       // Check against inlining width.
11984       unsigned InlineWidthBits =
11985           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11986       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11987         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11988             Size == CharUnits::One() ||
11989             E->getArg(1)->isNullPointerConstant(Info.Ctx,
11990                                                 Expr::NPC_NeverValueDependent))
11991           // OK, we will inline appropriately-aligned operations of this size,
11992           // and _Atomic(T) is appropriately-aligned.
11993           return Success(1, E);
11994 
11995         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
11996           castAs<PointerType>()->getPointeeType();
11997         if (!PointeeType->isIncompleteType() &&
11998             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
11999           // OK, we will inline operations on this object.
12000           return Success(1, E);
12001         }
12002       }
12003     }
12004 
12005     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12006         Success(0, E) : Error(E);
12007   }
12008   case Builtin::BIomp_is_initial_device:
12009     // We can decide statically which value the runtime would return if called.
12010     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
12011   case Builtin::BI__builtin_add_overflow:
12012   case Builtin::BI__builtin_sub_overflow:
12013   case Builtin::BI__builtin_mul_overflow:
12014   case Builtin::BI__builtin_sadd_overflow:
12015   case Builtin::BI__builtin_uadd_overflow:
12016   case Builtin::BI__builtin_uaddl_overflow:
12017   case Builtin::BI__builtin_uaddll_overflow:
12018   case Builtin::BI__builtin_usub_overflow:
12019   case Builtin::BI__builtin_usubl_overflow:
12020   case Builtin::BI__builtin_usubll_overflow:
12021   case Builtin::BI__builtin_umul_overflow:
12022   case Builtin::BI__builtin_umull_overflow:
12023   case Builtin::BI__builtin_umulll_overflow:
12024   case Builtin::BI__builtin_saddl_overflow:
12025   case Builtin::BI__builtin_saddll_overflow:
12026   case Builtin::BI__builtin_ssub_overflow:
12027   case Builtin::BI__builtin_ssubl_overflow:
12028   case Builtin::BI__builtin_ssubll_overflow:
12029   case Builtin::BI__builtin_smul_overflow:
12030   case Builtin::BI__builtin_smull_overflow:
12031   case Builtin::BI__builtin_smulll_overflow: {
12032     LValue ResultLValue;
12033     APSInt LHS, RHS;
12034 
12035     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12036     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12037         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12038         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12039       return false;
12040 
12041     APSInt Result;
12042     bool DidOverflow = false;
12043 
12044     // If the types don't have to match, enlarge all 3 to the largest of them.
12045     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12046         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12047         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12048       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12049                       ResultType->isSignedIntegerOrEnumerationType();
12050       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12051                       ResultType->isSignedIntegerOrEnumerationType();
12052       uint64_t LHSSize = LHS.getBitWidth();
12053       uint64_t RHSSize = RHS.getBitWidth();
12054       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12055       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12056 
12057       // Add an additional bit if the signedness isn't uniformly agreed to. We
12058       // could do this ONLY if there is a signed and an unsigned that both have
12059       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12060       // caught in the shrink-to-result later anyway.
12061       if (IsSigned && !AllSigned)
12062         ++MaxBits;
12063 
12064       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12065       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12066       Result = APSInt(MaxBits, !IsSigned);
12067     }
12068 
12069     // Find largest int.
12070     switch (BuiltinOp) {
12071     default:
12072       llvm_unreachable("Invalid value for BuiltinOp");
12073     case Builtin::BI__builtin_add_overflow:
12074     case Builtin::BI__builtin_sadd_overflow:
12075     case Builtin::BI__builtin_saddl_overflow:
12076     case Builtin::BI__builtin_saddll_overflow:
12077     case Builtin::BI__builtin_uadd_overflow:
12078     case Builtin::BI__builtin_uaddl_overflow:
12079     case Builtin::BI__builtin_uaddll_overflow:
12080       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12081                               : LHS.uadd_ov(RHS, DidOverflow);
12082       break;
12083     case Builtin::BI__builtin_sub_overflow:
12084     case Builtin::BI__builtin_ssub_overflow:
12085     case Builtin::BI__builtin_ssubl_overflow:
12086     case Builtin::BI__builtin_ssubll_overflow:
12087     case Builtin::BI__builtin_usub_overflow:
12088     case Builtin::BI__builtin_usubl_overflow:
12089     case Builtin::BI__builtin_usubll_overflow:
12090       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12091                               : LHS.usub_ov(RHS, DidOverflow);
12092       break;
12093     case Builtin::BI__builtin_mul_overflow:
12094     case Builtin::BI__builtin_smul_overflow:
12095     case Builtin::BI__builtin_smull_overflow:
12096     case Builtin::BI__builtin_smulll_overflow:
12097     case Builtin::BI__builtin_umul_overflow:
12098     case Builtin::BI__builtin_umull_overflow:
12099     case Builtin::BI__builtin_umulll_overflow:
12100       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12101                               : LHS.umul_ov(RHS, DidOverflow);
12102       break;
12103     }
12104 
12105     // In the case where multiple sizes are allowed, truncate and see if
12106     // the values are the same.
12107     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12108         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12109         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12110       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12111       // since it will give us the behavior of a TruncOrSelf in the case where
12112       // its parameter <= its size.  We previously set Result to be at least the
12113       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12114       // will work exactly like TruncOrSelf.
12115       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12116       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12117 
12118       if (!APSInt::isSameValue(Temp, Result))
12119         DidOverflow = true;
12120       Result = Temp;
12121     }
12122 
12123     APValue APV{Result};
12124     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12125       return false;
12126     return Success(DidOverflow, E);
12127   }
12128   }
12129 }
12130 
12131 /// Determine whether this is a pointer past the end of the complete
12132 /// object referred to by the lvalue.
12133 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12134                                             const LValue &LV) {
12135   // A null pointer can be viewed as being "past the end" but we don't
12136   // choose to look at it that way here.
12137   if (!LV.getLValueBase())
12138     return false;
12139 
12140   // If the designator is valid and refers to a subobject, we're not pointing
12141   // past the end.
12142   if (!LV.getLValueDesignator().Invalid &&
12143       !LV.getLValueDesignator().isOnePastTheEnd())
12144     return false;
12145 
12146   // A pointer to an incomplete type might be past-the-end if the type's size is
12147   // zero.  We cannot tell because the type is incomplete.
12148   QualType Ty = getType(LV.getLValueBase());
12149   if (Ty->isIncompleteType())
12150     return true;
12151 
12152   // We're a past-the-end pointer if we point to the byte after the object,
12153   // no matter what our type or path is.
12154   auto Size = Ctx.getTypeSizeInChars(Ty);
12155   return LV.getLValueOffset() == Size;
12156 }
12157 
12158 namespace {
12159 
12160 /// Data recursive integer evaluator of certain binary operators.
12161 ///
12162 /// We use a data recursive algorithm for binary operators so that we are able
12163 /// to handle extreme cases of chained binary operators without causing stack
12164 /// overflow.
12165 class DataRecursiveIntBinOpEvaluator {
12166   struct EvalResult {
12167     APValue Val;
12168     bool Failed;
12169 
12170     EvalResult() : Failed(false) { }
12171 
12172     void swap(EvalResult &RHS) {
12173       Val.swap(RHS.Val);
12174       Failed = RHS.Failed;
12175       RHS.Failed = false;
12176     }
12177   };
12178 
12179   struct Job {
12180     const Expr *E;
12181     EvalResult LHSResult; // meaningful only for binary operator expression.
12182     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12183 
12184     Job() = default;
12185     Job(Job &&) = default;
12186 
12187     void startSpeculativeEval(EvalInfo &Info) {
12188       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12189     }
12190 
12191   private:
12192     SpeculativeEvaluationRAII SpecEvalRAII;
12193   };
12194 
12195   SmallVector<Job, 16> Queue;
12196 
12197   IntExprEvaluator &IntEval;
12198   EvalInfo &Info;
12199   APValue &FinalResult;
12200 
12201 public:
12202   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12203     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12204 
12205   /// True if \param E is a binary operator that we are going to handle
12206   /// data recursively.
12207   /// We handle binary operators that are comma, logical, or that have operands
12208   /// with integral or enumeration type.
12209   static bool shouldEnqueue(const BinaryOperator *E) {
12210     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12211            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
12212             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12213             E->getRHS()->getType()->isIntegralOrEnumerationType());
12214   }
12215 
12216   bool Traverse(const BinaryOperator *E) {
12217     enqueue(E);
12218     EvalResult PrevResult;
12219     while (!Queue.empty())
12220       process(PrevResult);
12221 
12222     if (PrevResult.Failed) return false;
12223 
12224     FinalResult.swap(PrevResult.Val);
12225     return true;
12226   }
12227 
12228 private:
12229   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12230     return IntEval.Success(Value, E, Result);
12231   }
12232   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12233     return IntEval.Success(Value, E, Result);
12234   }
12235   bool Error(const Expr *E) {
12236     return IntEval.Error(E);
12237   }
12238   bool Error(const Expr *E, diag::kind D) {
12239     return IntEval.Error(E, D);
12240   }
12241 
12242   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12243     return Info.CCEDiag(E, D);
12244   }
12245 
12246   // Returns true if visiting the RHS is necessary, false otherwise.
12247   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12248                          bool &SuppressRHSDiags);
12249 
12250   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12251                   const BinaryOperator *E, APValue &Result);
12252 
12253   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12254     Result.Failed = !Evaluate(Result.Val, Info, E);
12255     if (Result.Failed)
12256       Result.Val = APValue();
12257   }
12258 
12259   void process(EvalResult &Result);
12260 
12261   void enqueue(const Expr *E) {
12262     E = E->IgnoreParens();
12263     Queue.resize(Queue.size()+1);
12264     Queue.back().E = E;
12265     Queue.back().Kind = Job::AnyExprKind;
12266   }
12267 };
12268 
12269 }
12270 
12271 bool DataRecursiveIntBinOpEvaluator::
12272        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12273                          bool &SuppressRHSDiags) {
12274   if (E->getOpcode() == BO_Comma) {
12275     // Ignore LHS but note if we could not evaluate it.
12276     if (LHSResult.Failed)
12277       return Info.noteSideEffect();
12278     return true;
12279   }
12280 
12281   if (E->isLogicalOp()) {
12282     bool LHSAsBool;
12283     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12284       // We were able to evaluate the LHS, see if we can get away with not
12285       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12286       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12287         Success(LHSAsBool, E, LHSResult.Val);
12288         return false; // Ignore RHS
12289       }
12290     } else {
12291       LHSResult.Failed = true;
12292 
12293       // Since we weren't able to evaluate the left hand side, it
12294       // might have had side effects.
12295       if (!Info.noteSideEffect())
12296         return false;
12297 
12298       // We can't evaluate the LHS; however, sometimes the result
12299       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12300       // Don't ignore RHS and suppress diagnostics from this arm.
12301       SuppressRHSDiags = true;
12302     }
12303 
12304     return true;
12305   }
12306 
12307   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12308          E->getRHS()->getType()->isIntegralOrEnumerationType());
12309 
12310   if (LHSResult.Failed && !Info.noteFailure())
12311     return false; // Ignore RHS;
12312 
12313   return true;
12314 }
12315 
12316 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12317                                     bool IsSub) {
12318   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12319   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12320   // offsets.
12321   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12322   CharUnits &Offset = LVal.getLValueOffset();
12323   uint64_t Offset64 = Offset.getQuantity();
12324   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12325   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12326                                          : Offset64 + Index64);
12327 }
12328 
12329 bool DataRecursiveIntBinOpEvaluator::
12330        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12331                   const BinaryOperator *E, APValue &Result) {
12332   if (E->getOpcode() == BO_Comma) {
12333     if (RHSResult.Failed)
12334       return false;
12335     Result = RHSResult.Val;
12336     return true;
12337   }
12338 
12339   if (E->isLogicalOp()) {
12340     bool lhsResult, rhsResult;
12341     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12342     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12343 
12344     if (LHSIsOK) {
12345       if (RHSIsOK) {
12346         if (E->getOpcode() == BO_LOr)
12347           return Success(lhsResult || rhsResult, E, Result);
12348         else
12349           return Success(lhsResult && rhsResult, E, Result);
12350       }
12351     } else {
12352       if (RHSIsOK) {
12353         // We can't evaluate the LHS; however, sometimes the result
12354         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12355         if (rhsResult == (E->getOpcode() == BO_LOr))
12356           return Success(rhsResult, E, Result);
12357       }
12358     }
12359 
12360     return false;
12361   }
12362 
12363   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12364          E->getRHS()->getType()->isIntegralOrEnumerationType());
12365 
12366   if (LHSResult.Failed || RHSResult.Failed)
12367     return false;
12368 
12369   const APValue &LHSVal = LHSResult.Val;
12370   const APValue &RHSVal = RHSResult.Val;
12371 
12372   // Handle cases like (unsigned long)&a + 4.
12373   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12374     Result = LHSVal;
12375     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12376     return true;
12377   }
12378 
12379   // Handle cases like 4 + (unsigned long)&a
12380   if (E->getOpcode() == BO_Add &&
12381       RHSVal.isLValue() && LHSVal.isInt()) {
12382     Result = RHSVal;
12383     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12384     return true;
12385   }
12386 
12387   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12388     // Handle (intptr_t)&&A - (intptr_t)&&B.
12389     if (!LHSVal.getLValueOffset().isZero() ||
12390         !RHSVal.getLValueOffset().isZero())
12391       return false;
12392     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12393     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12394     if (!LHSExpr || !RHSExpr)
12395       return false;
12396     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12397     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12398     if (!LHSAddrExpr || !RHSAddrExpr)
12399       return false;
12400     // Make sure both labels come from the same function.
12401     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12402         RHSAddrExpr->getLabel()->getDeclContext())
12403       return false;
12404     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12405     return true;
12406   }
12407 
12408   // All the remaining cases expect both operands to be an integer
12409   if (!LHSVal.isInt() || !RHSVal.isInt())
12410     return Error(E);
12411 
12412   // Set up the width and signedness manually, in case it can't be deduced
12413   // from the operation we're performing.
12414   // FIXME: Don't do this in the cases where we can deduce it.
12415   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12416                E->getType()->isUnsignedIntegerOrEnumerationType());
12417   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12418                          RHSVal.getInt(), Value))
12419     return false;
12420   return Success(Value, E, Result);
12421 }
12422 
12423 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12424   Job &job = Queue.back();
12425 
12426   switch (job.Kind) {
12427     case Job::AnyExprKind: {
12428       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12429         if (shouldEnqueue(Bop)) {
12430           job.Kind = Job::BinOpKind;
12431           enqueue(Bop->getLHS());
12432           return;
12433         }
12434       }
12435 
12436       EvaluateExpr(job.E, Result);
12437       Queue.pop_back();
12438       return;
12439     }
12440 
12441     case Job::BinOpKind: {
12442       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12443       bool SuppressRHSDiags = false;
12444       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12445         Queue.pop_back();
12446         return;
12447       }
12448       if (SuppressRHSDiags)
12449         job.startSpeculativeEval(Info);
12450       job.LHSResult.swap(Result);
12451       job.Kind = Job::BinOpVisitedLHSKind;
12452       enqueue(Bop->getRHS());
12453       return;
12454     }
12455 
12456     case Job::BinOpVisitedLHSKind: {
12457       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12458       EvalResult RHS;
12459       RHS.swap(Result);
12460       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12461       Queue.pop_back();
12462       return;
12463     }
12464   }
12465 
12466   llvm_unreachable("Invalid Job::Kind!");
12467 }
12468 
12469 namespace {
12470 /// Used when we determine that we should fail, but can keep evaluating prior to
12471 /// noting that we had a failure.
12472 class DelayedNoteFailureRAII {
12473   EvalInfo &Info;
12474   bool NoteFailure;
12475 
12476 public:
12477   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
12478       : Info(Info), NoteFailure(NoteFailure) {}
12479   ~DelayedNoteFailureRAII() {
12480     if (NoteFailure) {
12481       bool ContinueAfterFailure = Info.noteFailure();
12482       (void)ContinueAfterFailure;
12483       assert(ContinueAfterFailure &&
12484              "Shouldn't have kept evaluating on failure.");
12485     }
12486   }
12487 };
12488 
12489 enum class CmpResult {
12490   Unequal,
12491   Less,
12492   Equal,
12493   Greater,
12494   Unordered,
12495 };
12496 }
12497 
12498 template <class SuccessCB, class AfterCB>
12499 static bool
12500 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12501                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12502   assert(!E->isValueDependent());
12503   assert(E->isComparisonOp() && "expected comparison operator");
12504   assert((E->getOpcode() == BO_Cmp ||
12505           E->getType()->isIntegralOrEnumerationType()) &&
12506          "unsupported binary expression evaluation");
12507   auto Error = [&](const Expr *E) {
12508     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12509     return false;
12510   };
12511 
12512   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12513   bool IsEquality = E->isEqualityOp();
12514 
12515   QualType LHSTy = E->getLHS()->getType();
12516   QualType RHSTy = E->getRHS()->getType();
12517 
12518   if (LHSTy->isIntegralOrEnumerationType() &&
12519       RHSTy->isIntegralOrEnumerationType()) {
12520     APSInt LHS, RHS;
12521     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12522     if (!LHSOK && !Info.noteFailure())
12523       return false;
12524     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12525       return false;
12526     if (LHS < RHS)
12527       return Success(CmpResult::Less, E);
12528     if (LHS > RHS)
12529       return Success(CmpResult::Greater, E);
12530     return Success(CmpResult::Equal, E);
12531   }
12532 
12533   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12534     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12535     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12536 
12537     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12538     if (!LHSOK && !Info.noteFailure())
12539       return false;
12540     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12541       return false;
12542     if (LHSFX < RHSFX)
12543       return Success(CmpResult::Less, E);
12544     if (LHSFX > RHSFX)
12545       return Success(CmpResult::Greater, E);
12546     return Success(CmpResult::Equal, E);
12547   }
12548 
12549   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12550     ComplexValue LHS, RHS;
12551     bool LHSOK;
12552     if (E->isAssignmentOp()) {
12553       LValue LV;
12554       EvaluateLValue(E->getLHS(), LV, Info);
12555       LHSOK = false;
12556     } else if (LHSTy->isRealFloatingType()) {
12557       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12558       if (LHSOK) {
12559         LHS.makeComplexFloat();
12560         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12561       }
12562     } else {
12563       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12564     }
12565     if (!LHSOK && !Info.noteFailure())
12566       return false;
12567 
12568     if (E->getRHS()->getType()->isRealFloatingType()) {
12569       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12570         return false;
12571       RHS.makeComplexFloat();
12572       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12573     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12574       return false;
12575 
12576     if (LHS.isComplexFloat()) {
12577       APFloat::cmpResult CR_r =
12578         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12579       APFloat::cmpResult CR_i =
12580         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12581       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12582       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12583     } else {
12584       assert(IsEquality && "invalid complex comparison");
12585       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12586                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12587       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12588     }
12589   }
12590 
12591   if (LHSTy->isRealFloatingType() &&
12592       RHSTy->isRealFloatingType()) {
12593     APFloat RHS(0.0), LHS(0.0);
12594 
12595     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12596     if (!LHSOK && !Info.noteFailure())
12597       return false;
12598 
12599     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12600       return false;
12601 
12602     assert(E->isComparisonOp() && "Invalid binary operator!");
12603     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12604     if (!Info.InConstantContext &&
12605         APFloatCmpResult == APFloat::cmpUnordered &&
12606         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12607       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12608       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12609       return false;
12610     }
12611     auto GetCmpRes = [&]() {
12612       switch (APFloatCmpResult) {
12613       case APFloat::cmpEqual:
12614         return CmpResult::Equal;
12615       case APFloat::cmpLessThan:
12616         return CmpResult::Less;
12617       case APFloat::cmpGreaterThan:
12618         return CmpResult::Greater;
12619       case APFloat::cmpUnordered:
12620         return CmpResult::Unordered;
12621       }
12622       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12623     };
12624     return Success(GetCmpRes(), E);
12625   }
12626 
12627   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12628     LValue LHSValue, RHSValue;
12629 
12630     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12631     if (!LHSOK && !Info.noteFailure())
12632       return false;
12633 
12634     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12635       return false;
12636 
12637     // Reject differing bases from the normal codepath; we special-case
12638     // comparisons to null.
12639     if (!HasSameBase(LHSValue, RHSValue)) {
12640       // Inequalities and subtractions between unrelated pointers have
12641       // unspecified or undefined behavior.
12642       if (!IsEquality) {
12643         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12644         return false;
12645       }
12646       // A constant address may compare equal to the address of a symbol.
12647       // The one exception is that address of an object cannot compare equal
12648       // to a null pointer constant.
12649       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12650           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12651         return Error(E);
12652       // It's implementation-defined whether distinct literals will have
12653       // distinct addresses. In clang, the result of such a comparison is
12654       // unspecified, so it is not a constant expression. However, we do know
12655       // that the address of a literal will be non-null.
12656       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12657           LHSValue.Base && RHSValue.Base)
12658         return Error(E);
12659       // We can't tell whether weak symbols will end up pointing to the same
12660       // object.
12661       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12662         return Error(E);
12663       // We can't compare the address of the start of one object with the
12664       // past-the-end address of another object, per C++ DR1652.
12665       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12666            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12667           (RHSValue.Base && RHSValue.Offset.isZero() &&
12668            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12669         return Error(E);
12670       // We can't tell whether an object is at the same address as another
12671       // zero sized object.
12672       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12673           (LHSValue.Base && isZeroSized(RHSValue)))
12674         return Error(E);
12675       return Success(CmpResult::Unequal, E);
12676     }
12677 
12678     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12679     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12680 
12681     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12682     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12683 
12684     // C++11 [expr.rel]p3:
12685     //   Pointers to void (after pointer conversions) can be compared, with a
12686     //   result defined as follows: If both pointers represent the same
12687     //   address or are both the null pointer value, the result is true if the
12688     //   operator is <= or >= and false otherwise; otherwise the result is
12689     //   unspecified.
12690     // We interpret this as applying to pointers to *cv* void.
12691     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12692       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12693 
12694     // C++11 [expr.rel]p2:
12695     // - If two pointers point to non-static data members of the same object,
12696     //   or to subobjects or array elements fo such members, recursively, the
12697     //   pointer to the later declared member compares greater provided the
12698     //   two members have the same access control and provided their class is
12699     //   not a union.
12700     //   [...]
12701     // - Otherwise pointer comparisons are unspecified.
12702     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12703       bool WasArrayIndex;
12704       unsigned Mismatch = FindDesignatorMismatch(
12705           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12706       // At the point where the designators diverge, the comparison has a
12707       // specified value if:
12708       //  - we are comparing array indices
12709       //  - we are comparing fields of a union, or fields with the same access
12710       // Otherwise, the result is unspecified and thus the comparison is not a
12711       // constant expression.
12712       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12713           Mismatch < RHSDesignator.Entries.size()) {
12714         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12715         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12716         if (!LF && !RF)
12717           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12718         else if (!LF)
12719           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12720               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12721               << RF->getParent() << RF;
12722         else if (!RF)
12723           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12724               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12725               << LF->getParent() << LF;
12726         else if (!LF->getParent()->isUnion() &&
12727                  LF->getAccess() != RF->getAccess())
12728           Info.CCEDiag(E,
12729                        diag::note_constexpr_pointer_comparison_differing_access)
12730               << LF << LF->getAccess() << RF << RF->getAccess()
12731               << LF->getParent();
12732       }
12733     }
12734 
12735     // The comparison here must be unsigned, and performed with the same
12736     // width as the pointer.
12737     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12738     uint64_t CompareLHS = LHSOffset.getQuantity();
12739     uint64_t CompareRHS = RHSOffset.getQuantity();
12740     assert(PtrSize <= 64 && "Unexpected pointer width");
12741     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12742     CompareLHS &= Mask;
12743     CompareRHS &= Mask;
12744 
12745     // If there is a base and this is a relational operator, we can only
12746     // compare pointers within the object in question; otherwise, the result
12747     // depends on where the object is located in memory.
12748     if (!LHSValue.Base.isNull() && IsRelational) {
12749       QualType BaseTy = getType(LHSValue.Base);
12750       if (BaseTy->isIncompleteType())
12751         return Error(E);
12752       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12753       uint64_t OffsetLimit = Size.getQuantity();
12754       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12755         return Error(E);
12756     }
12757 
12758     if (CompareLHS < CompareRHS)
12759       return Success(CmpResult::Less, E);
12760     if (CompareLHS > CompareRHS)
12761       return Success(CmpResult::Greater, E);
12762     return Success(CmpResult::Equal, E);
12763   }
12764 
12765   if (LHSTy->isMemberPointerType()) {
12766     assert(IsEquality && "unexpected member pointer operation");
12767     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12768 
12769     MemberPtr LHSValue, RHSValue;
12770 
12771     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12772     if (!LHSOK && !Info.noteFailure())
12773       return false;
12774 
12775     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12776       return false;
12777 
12778     // C++11 [expr.eq]p2:
12779     //   If both operands are null, they compare equal. Otherwise if only one is
12780     //   null, they compare unequal.
12781     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12782       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12783       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12784     }
12785 
12786     //   Otherwise if either is a pointer to a virtual member function, the
12787     //   result is unspecified.
12788     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12789       if (MD->isVirtual())
12790         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12791     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12792       if (MD->isVirtual())
12793         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12794 
12795     //   Otherwise they compare equal if and only if they would refer to the
12796     //   same member of the same most derived object or the same subobject if
12797     //   they were dereferenced with a hypothetical object of the associated
12798     //   class type.
12799     bool Equal = LHSValue == RHSValue;
12800     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12801   }
12802 
12803   if (LHSTy->isNullPtrType()) {
12804     assert(E->isComparisonOp() && "unexpected nullptr operation");
12805     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12806     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12807     // are compared, the result is true of the operator is <=, >= or ==, and
12808     // false otherwise.
12809     return Success(CmpResult::Equal, E);
12810   }
12811 
12812   return DoAfter();
12813 }
12814 
12815 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12816   if (!CheckLiteralType(Info, E))
12817     return false;
12818 
12819   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12820     ComparisonCategoryResult CCR;
12821     switch (CR) {
12822     case CmpResult::Unequal:
12823       llvm_unreachable("should never produce Unequal for three-way comparison");
12824     case CmpResult::Less:
12825       CCR = ComparisonCategoryResult::Less;
12826       break;
12827     case CmpResult::Equal:
12828       CCR = ComparisonCategoryResult::Equal;
12829       break;
12830     case CmpResult::Greater:
12831       CCR = ComparisonCategoryResult::Greater;
12832       break;
12833     case CmpResult::Unordered:
12834       CCR = ComparisonCategoryResult::Unordered;
12835       break;
12836     }
12837     // Evaluation succeeded. Lookup the information for the comparison category
12838     // type and fetch the VarDecl for the result.
12839     const ComparisonCategoryInfo &CmpInfo =
12840         Info.Ctx.CompCategories.getInfoForType(E->getType());
12841     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12842     // Check and evaluate the result as a constant expression.
12843     LValue LV;
12844     LV.set(VD);
12845     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12846       return false;
12847     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
12848                                    ConstantExprKind::Normal);
12849   };
12850   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12851     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12852   });
12853 }
12854 
12855 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12856   // We don't call noteFailure immediately because the assignment happens after
12857   // we evaluate LHS and RHS.
12858   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
12859     return Error(E);
12860 
12861   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
12862   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12863     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12864 
12865   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12866           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12867          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12868 
12869   if (E->isComparisonOp()) {
12870     // Evaluate builtin binary comparisons by evaluating them as three-way
12871     // comparisons and then translating the result.
12872     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12873       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12874              "should only produce Unequal for equality comparisons");
12875       bool IsEqual   = CR == CmpResult::Equal,
12876            IsLess    = CR == CmpResult::Less,
12877            IsGreater = CR == CmpResult::Greater;
12878       auto Op = E->getOpcode();
12879       switch (Op) {
12880       default:
12881         llvm_unreachable("unsupported binary operator");
12882       case BO_EQ:
12883       case BO_NE:
12884         return Success(IsEqual == (Op == BO_EQ), E);
12885       case BO_LT:
12886         return Success(IsLess, E);
12887       case BO_GT:
12888         return Success(IsGreater, E);
12889       case BO_LE:
12890         return Success(IsEqual || IsLess, E);
12891       case BO_GE:
12892         return Success(IsEqual || IsGreater, E);
12893       }
12894     };
12895     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12896       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12897     });
12898   }
12899 
12900   QualType LHSTy = E->getLHS()->getType();
12901   QualType RHSTy = E->getRHS()->getType();
12902 
12903   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12904       E->getOpcode() == BO_Sub) {
12905     LValue LHSValue, RHSValue;
12906 
12907     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12908     if (!LHSOK && !Info.noteFailure())
12909       return false;
12910 
12911     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12912       return false;
12913 
12914     // Reject differing bases from the normal codepath; we special-case
12915     // comparisons to null.
12916     if (!HasSameBase(LHSValue, RHSValue)) {
12917       // Handle &&A - &&B.
12918       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12919         return Error(E);
12920       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12921       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12922       if (!LHSExpr || !RHSExpr)
12923         return Error(E);
12924       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12925       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12926       if (!LHSAddrExpr || !RHSAddrExpr)
12927         return Error(E);
12928       // Make sure both labels come from the same function.
12929       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12930           RHSAddrExpr->getLabel()->getDeclContext())
12931         return Error(E);
12932       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12933     }
12934     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12935     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12936 
12937     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12938     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12939 
12940     // C++11 [expr.add]p6:
12941     //   Unless both pointers point to elements of the same array object, or
12942     //   one past the last element of the array object, the behavior is
12943     //   undefined.
12944     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12945         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12946                                 RHSDesignator))
12947       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12948 
12949     QualType Type = E->getLHS()->getType();
12950     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12951 
12952     CharUnits ElementSize;
12953     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12954       return false;
12955 
12956     // As an extension, a type may have zero size (empty struct or union in
12957     // C, array of zero length). Pointer subtraction in such cases has
12958     // undefined behavior, so is not constant.
12959     if (ElementSize.isZero()) {
12960       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12961           << ElementType;
12962       return false;
12963     }
12964 
12965     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12966     // and produce incorrect results when it overflows. Such behavior
12967     // appears to be non-conforming, but is common, so perhaps we should
12968     // assume the standard intended for such cases to be undefined behavior
12969     // and check for them.
12970 
12971     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12972     // overflow in the final conversion to ptrdiff_t.
12973     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12974     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12975     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12976                     false);
12977     APSInt TrueResult = (LHS - RHS) / ElemSize;
12978     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12979 
12980     if (Result.extend(65) != TrueResult &&
12981         !HandleOverflow(Info, E, TrueResult, E->getType()))
12982       return false;
12983     return Success(Result, E);
12984   }
12985 
12986   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12987 }
12988 
12989 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12990 /// a result as the expression's type.
12991 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12992                                     const UnaryExprOrTypeTraitExpr *E) {
12993   switch(E->getKind()) {
12994   case UETT_PreferredAlignOf:
12995   case UETT_AlignOf: {
12996     if (E->isArgumentType())
12997       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12998                      E);
12999     else
13000       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13001                      E);
13002   }
13003 
13004   case UETT_VecStep: {
13005     QualType Ty = E->getTypeOfArgument();
13006 
13007     if (Ty->isVectorType()) {
13008       unsigned n = Ty->castAs<VectorType>()->getNumElements();
13009 
13010       // The vec_step built-in functions that take a 3-component
13011       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13012       if (n == 3)
13013         n = 4;
13014 
13015       return Success(n, E);
13016     } else
13017       return Success(1, E);
13018   }
13019 
13020   case UETT_SizeOf: {
13021     QualType SrcTy = E->getTypeOfArgument();
13022     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13023     //   the result is the size of the referenced type."
13024     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13025       SrcTy = Ref->getPointeeType();
13026 
13027     CharUnits Sizeof;
13028     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13029       return false;
13030     return Success(Sizeof, E);
13031   }
13032   case UETT_OpenMPRequiredSimdAlign:
13033     assert(E->isArgumentType());
13034     return Success(
13035         Info.Ctx.toCharUnitsFromBits(
13036                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13037             .getQuantity(),
13038         E);
13039   }
13040 
13041   llvm_unreachable("unknown expr/type trait");
13042 }
13043 
13044 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13045   CharUnits Result;
13046   unsigned n = OOE->getNumComponents();
13047   if (n == 0)
13048     return Error(OOE);
13049   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13050   for (unsigned i = 0; i != n; ++i) {
13051     OffsetOfNode ON = OOE->getComponent(i);
13052     switch (ON.getKind()) {
13053     case OffsetOfNode::Array: {
13054       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13055       APSInt IdxResult;
13056       if (!EvaluateInteger(Idx, IdxResult, Info))
13057         return false;
13058       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13059       if (!AT)
13060         return Error(OOE);
13061       CurrentType = AT->getElementType();
13062       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13063       Result += IdxResult.getSExtValue() * ElementSize;
13064       break;
13065     }
13066 
13067     case OffsetOfNode::Field: {
13068       FieldDecl *MemberDecl = ON.getField();
13069       const RecordType *RT = CurrentType->getAs<RecordType>();
13070       if (!RT)
13071         return Error(OOE);
13072       RecordDecl *RD = RT->getDecl();
13073       if (RD->isInvalidDecl()) return false;
13074       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13075       unsigned i = MemberDecl->getFieldIndex();
13076       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13077       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13078       CurrentType = MemberDecl->getType().getNonReferenceType();
13079       break;
13080     }
13081 
13082     case OffsetOfNode::Identifier:
13083       llvm_unreachable("dependent __builtin_offsetof");
13084 
13085     case OffsetOfNode::Base: {
13086       CXXBaseSpecifier *BaseSpec = ON.getBase();
13087       if (BaseSpec->isVirtual())
13088         return Error(OOE);
13089 
13090       // Find the layout of the class whose base we are looking into.
13091       const RecordType *RT = CurrentType->getAs<RecordType>();
13092       if (!RT)
13093         return Error(OOE);
13094       RecordDecl *RD = RT->getDecl();
13095       if (RD->isInvalidDecl()) return false;
13096       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13097 
13098       // Find the base class itself.
13099       CurrentType = BaseSpec->getType();
13100       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13101       if (!BaseRT)
13102         return Error(OOE);
13103 
13104       // Add the offset to the base.
13105       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13106       break;
13107     }
13108     }
13109   }
13110   return Success(Result, OOE);
13111 }
13112 
13113 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13114   switch (E->getOpcode()) {
13115   default:
13116     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13117     // See C99 6.6p3.
13118     return Error(E);
13119   case UO_Extension:
13120     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13121     // If so, we could clear the diagnostic ID.
13122     return Visit(E->getSubExpr());
13123   case UO_Plus:
13124     // The result is just the value.
13125     return Visit(E->getSubExpr());
13126   case UO_Minus: {
13127     if (!Visit(E->getSubExpr()))
13128       return false;
13129     if (!Result.isInt()) return Error(E);
13130     const APSInt &Value = Result.getInt();
13131     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13132         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13133                         E->getType()))
13134       return false;
13135     return Success(-Value, E);
13136   }
13137   case UO_Not: {
13138     if (!Visit(E->getSubExpr()))
13139       return false;
13140     if (!Result.isInt()) return Error(E);
13141     return Success(~Result.getInt(), E);
13142   }
13143   case UO_LNot: {
13144     bool bres;
13145     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13146       return false;
13147     return Success(!bres, E);
13148   }
13149   }
13150 }
13151 
13152 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13153 /// result type is integer.
13154 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13155   const Expr *SubExpr = E->getSubExpr();
13156   QualType DestType = E->getType();
13157   QualType SrcType = SubExpr->getType();
13158 
13159   switch (E->getCastKind()) {
13160   case CK_BaseToDerived:
13161   case CK_DerivedToBase:
13162   case CK_UncheckedDerivedToBase:
13163   case CK_Dynamic:
13164   case CK_ToUnion:
13165   case CK_ArrayToPointerDecay:
13166   case CK_FunctionToPointerDecay:
13167   case CK_NullToPointer:
13168   case CK_NullToMemberPointer:
13169   case CK_BaseToDerivedMemberPointer:
13170   case CK_DerivedToBaseMemberPointer:
13171   case CK_ReinterpretMemberPointer:
13172   case CK_ConstructorConversion:
13173   case CK_IntegralToPointer:
13174   case CK_ToVoid:
13175   case CK_VectorSplat:
13176   case CK_IntegralToFloating:
13177   case CK_FloatingCast:
13178   case CK_CPointerToObjCPointerCast:
13179   case CK_BlockPointerToObjCPointerCast:
13180   case CK_AnyPointerToBlockPointerCast:
13181   case CK_ObjCObjectLValueCast:
13182   case CK_FloatingRealToComplex:
13183   case CK_FloatingComplexToReal:
13184   case CK_FloatingComplexCast:
13185   case CK_FloatingComplexToIntegralComplex:
13186   case CK_IntegralRealToComplex:
13187   case CK_IntegralComplexCast:
13188   case CK_IntegralComplexToFloatingComplex:
13189   case CK_BuiltinFnToFnPtr:
13190   case CK_ZeroToOCLOpaqueType:
13191   case CK_NonAtomicToAtomic:
13192   case CK_AddressSpaceConversion:
13193   case CK_IntToOCLSampler:
13194   case CK_FloatingToFixedPoint:
13195   case CK_FixedPointToFloating:
13196   case CK_FixedPointCast:
13197   case CK_IntegralToFixedPoint:
13198     llvm_unreachable("invalid cast kind for integral value");
13199 
13200   case CK_BitCast:
13201   case CK_Dependent:
13202   case CK_LValueBitCast:
13203   case CK_ARCProduceObject:
13204   case CK_ARCConsumeObject:
13205   case CK_ARCReclaimReturnedObject:
13206   case CK_ARCExtendBlockObject:
13207   case CK_CopyAndAutoreleaseBlockObject:
13208     return Error(E);
13209 
13210   case CK_UserDefinedConversion:
13211   case CK_LValueToRValue:
13212   case CK_AtomicToNonAtomic:
13213   case CK_NoOp:
13214   case CK_LValueToRValueBitCast:
13215     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13216 
13217   case CK_MemberPointerToBoolean:
13218   case CK_PointerToBoolean:
13219   case CK_IntegralToBoolean:
13220   case CK_FloatingToBoolean:
13221   case CK_BooleanToSignedIntegral:
13222   case CK_FloatingComplexToBoolean:
13223   case CK_IntegralComplexToBoolean: {
13224     bool BoolResult;
13225     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13226       return false;
13227     uint64_t IntResult = BoolResult;
13228     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13229       IntResult = (uint64_t)-1;
13230     return Success(IntResult, E);
13231   }
13232 
13233   case CK_FixedPointToIntegral: {
13234     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13235     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13236       return false;
13237     bool Overflowed;
13238     llvm::APSInt Result = Src.convertToInt(
13239         Info.Ctx.getIntWidth(DestType),
13240         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13241     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13242       return false;
13243     return Success(Result, E);
13244   }
13245 
13246   case CK_FixedPointToBoolean: {
13247     // Unsigned padding does not affect this.
13248     APValue Val;
13249     if (!Evaluate(Val, Info, SubExpr))
13250       return false;
13251     return Success(Val.getFixedPoint().getBoolValue(), E);
13252   }
13253 
13254   case CK_IntegralCast: {
13255     if (!Visit(SubExpr))
13256       return false;
13257 
13258     if (!Result.isInt()) {
13259       // Allow casts of address-of-label differences if they are no-ops
13260       // or narrowing.  (The narrowing case isn't actually guaranteed to
13261       // be constant-evaluatable except in some narrow cases which are hard
13262       // to detect here.  We let it through on the assumption the user knows
13263       // what they are doing.)
13264       if (Result.isAddrLabelDiff())
13265         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13266       // Only allow casts of lvalues if they are lossless.
13267       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13268     }
13269 
13270     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13271                                       Result.getInt()), E);
13272   }
13273 
13274   case CK_PointerToIntegral: {
13275     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13276 
13277     LValue LV;
13278     if (!EvaluatePointer(SubExpr, LV, Info))
13279       return false;
13280 
13281     if (LV.getLValueBase()) {
13282       // Only allow based lvalue casts if they are lossless.
13283       // FIXME: Allow a larger integer size than the pointer size, and allow
13284       // narrowing back down to pointer width in subsequent integral casts.
13285       // FIXME: Check integer type's active bits, not its type size.
13286       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13287         return Error(E);
13288 
13289       LV.Designator.setInvalid();
13290       LV.moveInto(Result);
13291       return true;
13292     }
13293 
13294     APSInt AsInt;
13295     APValue V;
13296     LV.moveInto(V);
13297     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13298       llvm_unreachable("Can't cast this!");
13299 
13300     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13301   }
13302 
13303   case CK_IntegralComplexToReal: {
13304     ComplexValue C;
13305     if (!EvaluateComplex(SubExpr, C, Info))
13306       return false;
13307     return Success(C.getComplexIntReal(), E);
13308   }
13309 
13310   case CK_FloatingToIntegral: {
13311     APFloat F(0.0);
13312     if (!EvaluateFloat(SubExpr, F, Info))
13313       return false;
13314 
13315     APSInt Value;
13316     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13317       return false;
13318     return Success(Value, E);
13319   }
13320   }
13321 
13322   llvm_unreachable("unknown cast resulting in integral value");
13323 }
13324 
13325 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13326   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13327     ComplexValue LV;
13328     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13329       return false;
13330     if (!LV.isComplexInt())
13331       return Error(E);
13332     return Success(LV.getComplexIntReal(), E);
13333   }
13334 
13335   return Visit(E->getSubExpr());
13336 }
13337 
13338 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13339   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13340     ComplexValue LV;
13341     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13342       return false;
13343     if (!LV.isComplexInt())
13344       return Error(E);
13345     return Success(LV.getComplexIntImag(), E);
13346   }
13347 
13348   VisitIgnoredValue(E->getSubExpr());
13349   return Success(0, E);
13350 }
13351 
13352 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13353   return Success(E->getPackLength(), E);
13354 }
13355 
13356 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13357   return Success(E->getValue(), E);
13358 }
13359 
13360 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13361        const ConceptSpecializationExpr *E) {
13362   return Success(E->isSatisfied(), E);
13363 }
13364 
13365 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13366   return Success(E->isSatisfied(), E);
13367 }
13368 
13369 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13370   switch (E->getOpcode()) {
13371     default:
13372       // Invalid unary operators
13373       return Error(E);
13374     case UO_Plus:
13375       // The result is just the value.
13376       return Visit(E->getSubExpr());
13377     case UO_Minus: {
13378       if (!Visit(E->getSubExpr())) return false;
13379       if (!Result.isFixedPoint())
13380         return Error(E);
13381       bool Overflowed;
13382       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13383       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13384         return false;
13385       return Success(Negated, E);
13386     }
13387     case UO_LNot: {
13388       bool bres;
13389       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13390         return false;
13391       return Success(!bres, E);
13392     }
13393   }
13394 }
13395 
13396 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13397   const Expr *SubExpr = E->getSubExpr();
13398   QualType DestType = E->getType();
13399   assert(DestType->isFixedPointType() &&
13400          "Expected destination type to be a fixed point type");
13401   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13402 
13403   switch (E->getCastKind()) {
13404   case CK_FixedPointCast: {
13405     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13406     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13407       return false;
13408     bool Overflowed;
13409     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13410     if (Overflowed) {
13411       if (Info.checkingForUndefinedBehavior())
13412         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13413                                          diag::warn_fixedpoint_constant_overflow)
13414           << Result.toString() << E->getType();
13415       else if (!HandleOverflow(Info, E, Result, E->getType()))
13416         return false;
13417     }
13418     return Success(Result, E);
13419   }
13420   case CK_IntegralToFixedPoint: {
13421     APSInt Src;
13422     if (!EvaluateInteger(SubExpr, Src, Info))
13423       return false;
13424 
13425     bool Overflowed;
13426     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13427         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13428 
13429     if (Overflowed) {
13430       if (Info.checkingForUndefinedBehavior())
13431         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13432                                          diag::warn_fixedpoint_constant_overflow)
13433           << IntResult.toString() << E->getType();
13434       else if (!HandleOverflow(Info, E, IntResult, E->getType()))
13435         return false;
13436     }
13437 
13438     return Success(IntResult, E);
13439   }
13440   case CK_FloatingToFixedPoint: {
13441     APFloat Src(0.0);
13442     if (!EvaluateFloat(SubExpr, Src, Info))
13443       return false;
13444 
13445     bool Overflowed;
13446     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13447         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13448 
13449     if (Overflowed) {
13450       if (Info.checkingForUndefinedBehavior())
13451         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13452                                          diag::warn_fixedpoint_constant_overflow)
13453           << Result.toString() << E->getType();
13454       else if (!HandleOverflow(Info, E, Result, E->getType()))
13455         return false;
13456     }
13457 
13458     return Success(Result, E);
13459   }
13460   case CK_NoOp:
13461   case CK_LValueToRValue:
13462     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13463   default:
13464     return Error(E);
13465   }
13466 }
13467 
13468 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13469   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13470     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13471 
13472   const Expr *LHS = E->getLHS();
13473   const Expr *RHS = E->getRHS();
13474   FixedPointSemantics ResultFXSema =
13475       Info.Ctx.getFixedPointSemantics(E->getType());
13476 
13477   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13478   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13479     return false;
13480   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13481   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13482     return false;
13483 
13484   bool OpOverflow = false, ConversionOverflow = false;
13485   APFixedPoint Result(LHSFX.getSemantics());
13486   switch (E->getOpcode()) {
13487   case BO_Add: {
13488     Result = LHSFX.add(RHSFX, &OpOverflow)
13489                   .convert(ResultFXSema, &ConversionOverflow);
13490     break;
13491   }
13492   case BO_Sub: {
13493     Result = LHSFX.sub(RHSFX, &OpOverflow)
13494                   .convert(ResultFXSema, &ConversionOverflow);
13495     break;
13496   }
13497   case BO_Mul: {
13498     Result = LHSFX.mul(RHSFX, &OpOverflow)
13499                   .convert(ResultFXSema, &ConversionOverflow);
13500     break;
13501   }
13502   case BO_Div: {
13503     if (RHSFX.getValue() == 0) {
13504       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13505       return false;
13506     }
13507     Result = LHSFX.div(RHSFX, &OpOverflow)
13508                   .convert(ResultFXSema, &ConversionOverflow);
13509     break;
13510   }
13511   case BO_Shl:
13512   case BO_Shr: {
13513     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13514     llvm::APSInt RHSVal = RHSFX.getValue();
13515 
13516     unsigned ShiftBW =
13517         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13518     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13519     // Embedded-C 4.1.6.2.2:
13520     //   The right operand must be nonnegative and less than the total number
13521     //   of (nonpadding) bits of the fixed-point operand ...
13522     if (RHSVal.isNegative())
13523       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13524     else if (Amt != RHSVal)
13525       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13526           << RHSVal << E->getType() << ShiftBW;
13527 
13528     if (E->getOpcode() == BO_Shl)
13529       Result = LHSFX.shl(Amt, &OpOverflow);
13530     else
13531       Result = LHSFX.shr(Amt, &OpOverflow);
13532     break;
13533   }
13534   default:
13535     return false;
13536   }
13537   if (OpOverflow || ConversionOverflow) {
13538     if (Info.checkingForUndefinedBehavior())
13539       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13540                                        diag::warn_fixedpoint_constant_overflow)
13541         << Result.toString() << E->getType();
13542     else if (!HandleOverflow(Info, E, Result, E->getType()))
13543       return false;
13544   }
13545   return Success(Result, E);
13546 }
13547 
13548 //===----------------------------------------------------------------------===//
13549 // Float Evaluation
13550 //===----------------------------------------------------------------------===//
13551 
13552 namespace {
13553 class FloatExprEvaluator
13554   : public ExprEvaluatorBase<FloatExprEvaluator> {
13555   APFloat &Result;
13556 public:
13557   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13558     : ExprEvaluatorBaseTy(info), Result(result) {}
13559 
13560   bool Success(const APValue &V, const Expr *e) {
13561     Result = V.getFloat();
13562     return true;
13563   }
13564 
13565   bool ZeroInitialization(const Expr *E) {
13566     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13567     return true;
13568   }
13569 
13570   bool VisitCallExpr(const CallExpr *E);
13571 
13572   bool VisitUnaryOperator(const UnaryOperator *E);
13573   bool VisitBinaryOperator(const BinaryOperator *E);
13574   bool VisitFloatingLiteral(const FloatingLiteral *E);
13575   bool VisitCastExpr(const CastExpr *E);
13576 
13577   bool VisitUnaryReal(const UnaryOperator *E);
13578   bool VisitUnaryImag(const UnaryOperator *E);
13579 
13580   // FIXME: Missing: array subscript of vector, member of vector
13581 };
13582 } // end anonymous namespace
13583 
13584 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13585   assert(!E->isValueDependent());
13586   assert(E->isRValue() && E->getType()->isRealFloatingType());
13587   return FloatExprEvaluator(Info, Result).Visit(E);
13588 }
13589 
13590 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13591                                   QualType ResultTy,
13592                                   const Expr *Arg,
13593                                   bool SNaN,
13594                                   llvm::APFloat &Result) {
13595   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13596   if (!S) return false;
13597 
13598   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13599 
13600   llvm::APInt fill;
13601 
13602   // Treat empty strings as if they were zero.
13603   if (S->getString().empty())
13604     fill = llvm::APInt(32, 0);
13605   else if (S->getString().getAsInteger(0, fill))
13606     return false;
13607 
13608   if (Context.getTargetInfo().isNan2008()) {
13609     if (SNaN)
13610       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13611     else
13612       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13613   } else {
13614     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13615     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13616     // a different encoding to what became a standard in 2008, and for pre-
13617     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13618     // sNaN. This is now known as "legacy NaN" encoding.
13619     if (SNaN)
13620       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13621     else
13622       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13623   }
13624 
13625   return true;
13626 }
13627 
13628 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13629   switch (E->getBuiltinCallee()) {
13630   default:
13631     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13632 
13633   case Builtin::BI__builtin_huge_val:
13634   case Builtin::BI__builtin_huge_valf:
13635   case Builtin::BI__builtin_huge_vall:
13636   case Builtin::BI__builtin_huge_valf128:
13637   case Builtin::BI__builtin_inf:
13638   case Builtin::BI__builtin_inff:
13639   case Builtin::BI__builtin_infl:
13640   case Builtin::BI__builtin_inff128: {
13641     const llvm::fltSemantics &Sem =
13642       Info.Ctx.getFloatTypeSemantics(E->getType());
13643     Result = llvm::APFloat::getInf(Sem);
13644     return true;
13645   }
13646 
13647   case Builtin::BI__builtin_nans:
13648   case Builtin::BI__builtin_nansf:
13649   case Builtin::BI__builtin_nansl:
13650   case Builtin::BI__builtin_nansf128:
13651     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13652                                true, Result))
13653       return Error(E);
13654     return true;
13655 
13656   case Builtin::BI__builtin_nan:
13657   case Builtin::BI__builtin_nanf:
13658   case Builtin::BI__builtin_nanl:
13659   case Builtin::BI__builtin_nanf128:
13660     // If this is __builtin_nan() turn this into a nan, otherwise we
13661     // can't constant fold it.
13662     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13663                                false, Result))
13664       return Error(E);
13665     return true;
13666 
13667   case Builtin::BI__builtin_fabs:
13668   case Builtin::BI__builtin_fabsf:
13669   case Builtin::BI__builtin_fabsl:
13670   case Builtin::BI__builtin_fabsf128:
13671     // The C standard says "fabs raises no floating-point exceptions,
13672     // even if x is a signaling NaN. The returned value is independent of
13673     // the current rounding direction mode."  Therefore constant folding can
13674     // proceed without regard to the floating point settings.
13675     // Reference, WG14 N2478 F.10.4.3
13676     if (!EvaluateFloat(E->getArg(0), Result, Info))
13677       return false;
13678 
13679     if (Result.isNegative())
13680       Result.changeSign();
13681     return true;
13682 
13683   // FIXME: Builtin::BI__builtin_powi
13684   // FIXME: Builtin::BI__builtin_powif
13685   // FIXME: Builtin::BI__builtin_powil
13686 
13687   case Builtin::BI__builtin_copysign:
13688   case Builtin::BI__builtin_copysignf:
13689   case Builtin::BI__builtin_copysignl:
13690   case Builtin::BI__builtin_copysignf128: {
13691     APFloat RHS(0.);
13692     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13693         !EvaluateFloat(E->getArg(1), RHS, Info))
13694       return false;
13695     Result.copySign(RHS);
13696     return true;
13697   }
13698   }
13699 }
13700 
13701 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13702   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13703     ComplexValue CV;
13704     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13705       return false;
13706     Result = CV.FloatReal;
13707     return true;
13708   }
13709 
13710   return Visit(E->getSubExpr());
13711 }
13712 
13713 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13714   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13715     ComplexValue CV;
13716     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13717       return false;
13718     Result = CV.FloatImag;
13719     return true;
13720   }
13721 
13722   VisitIgnoredValue(E->getSubExpr());
13723   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13724   Result = llvm::APFloat::getZero(Sem);
13725   return true;
13726 }
13727 
13728 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13729   switch (E->getOpcode()) {
13730   default: return Error(E);
13731   case UO_Plus:
13732     return EvaluateFloat(E->getSubExpr(), Result, Info);
13733   case UO_Minus:
13734     // In C standard, WG14 N2478 F.3 p4
13735     // "the unary - raises no floating point exceptions,
13736     // even if the operand is signalling."
13737     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13738       return false;
13739     Result.changeSign();
13740     return true;
13741   }
13742 }
13743 
13744 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13745   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13746     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13747 
13748   APFloat RHS(0.0);
13749   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13750   if (!LHSOK && !Info.noteFailure())
13751     return false;
13752   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13753          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13754 }
13755 
13756 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13757   Result = E->getValue();
13758   return true;
13759 }
13760 
13761 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13762   const Expr* SubExpr = E->getSubExpr();
13763 
13764   switch (E->getCastKind()) {
13765   default:
13766     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13767 
13768   case CK_IntegralToFloating: {
13769     APSInt IntResult;
13770     const FPOptions FPO = E->getFPFeaturesInEffect(
13771                                   Info.Ctx.getLangOpts());
13772     return EvaluateInteger(SubExpr, IntResult, Info) &&
13773            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
13774                                 IntResult, E->getType(), Result);
13775   }
13776 
13777   case CK_FixedPointToFloating: {
13778     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13779     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
13780       return false;
13781     Result =
13782         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
13783     return true;
13784   }
13785 
13786   case CK_FloatingCast: {
13787     if (!Visit(SubExpr))
13788       return false;
13789     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13790                                   Result);
13791   }
13792 
13793   case CK_FloatingComplexToReal: {
13794     ComplexValue V;
13795     if (!EvaluateComplex(SubExpr, V, Info))
13796       return false;
13797     Result = V.getComplexFloatReal();
13798     return true;
13799   }
13800   }
13801 }
13802 
13803 //===----------------------------------------------------------------------===//
13804 // Complex Evaluation (for float and integer)
13805 //===----------------------------------------------------------------------===//
13806 
13807 namespace {
13808 class ComplexExprEvaluator
13809   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13810   ComplexValue &Result;
13811 
13812 public:
13813   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13814     : ExprEvaluatorBaseTy(info), Result(Result) {}
13815 
13816   bool Success(const APValue &V, const Expr *e) {
13817     Result.setFrom(V);
13818     return true;
13819   }
13820 
13821   bool ZeroInitialization(const Expr *E);
13822 
13823   //===--------------------------------------------------------------------===//
13824   //                            Visitor Methods
13825   //===--------------------------------------------------------------------===//
13826 
13827   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13828   bool VisitCastExpr(const CastExpr *E);
13829   bool VisitBinaryOperator(const BinaryOperator *E);
13830   bool VisitUnaryOperator(const UnaryOperator *E);
13831   bool VisitInitListExpr(const InitListExpr *E);
13832   bool VisitCallExpr(const CallExpr *E);
13833 };
13834 } // end anonymous namespace
13835 
13836 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13837                             EvalInfo &Info) {
13838   assert(!E->isValueDependent());
13839   assert(E->isRValue() && E->getType()->isAnyComplexType());
13840   return ComplexExprEvaluator(Info, Result).Visit(E);
13841 }
13842 
13843 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13844   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13845   if (ElemTy->isRealFloatingType()) {
13846     Result.makeComplexFloat();
13847     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13848     Result.FloatReal = Zero;
13849     Result.FloatImag = Zero;
13850   } else {
13851     Result.makeComplexInt();
13852     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13853     Result.IntReal = Zero;
13854     Result.IntImag = Zero;
13855   }
13856   return true;
13857 }
13858 
13859 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13860   const Expr* SubExpr = E->getSubExpr();
13861 
13862   if (SubExpr->getType()->isRealFloatingType()) {
13863     Result.makeComplexFloat();
13864     APFloat &Imag = Result.FloatImag;
13865     if (!EvaluateFloat(SubExpr, Imag, Info))
13866       return false;
13867 
13868     Result.FloatReal = APFloat(Imag.getSemantics());
13869     return true;
13870   } else {
13871     assert(SubExpr->getType()->isIntegerType() &&
13872            "Unexpected imaginary literal.");
13873 
13874     Result.makeComplexInt();
13875     APSInt &Imag = Result.IntImag;
13876     if (!EvaluateInteger(SubExpr, Imag, Info))
13877       return false;
13878 
13879     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13880     return true;
13881   }
13882 }
13883 
13884 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13885 
13886   switch (E->getCastKind()) {
13887   case CK_BitCast:
13888   case CK_BaseToDerived:
13889   case CK_DerivedToBase:
13890   case CK_UncheckedDerivedToBase:
13891   case CK_Dynamic:
13892   case CK_ToUnion:
13893   case CK_ArrayToPointerDecay:
13894   case CK_FunctionToPointerDecay:
13895   case CK_NullToPointer:
13896   case CK_NullToMemberPointer:
13897   case CK_BaseToDerivedMemberPointer:
13898   case CK_DerivedToBaseMemberPointer:
13899   case CK_MemberPointerToBoolean:
13900   case CK_ReinterpretMemberPointer:
13901   case CK_ConstructorConversion:
13902   case CK_IntegralToPointer:
13903   case CK_PointerToIntegral:
13904   case CK_PointerToBoolean:
13905   case CK_ToVoid:
13906   case CK_VectorSplat:
13907   case CK_IntegralCast:
13908   case CK_BooleanToSignedIntegral:
13909   case CK_IntegralToBoolean:
13910   case CK_IntegralToFloating:
13911   case CK_FloatingToIntegral:
13912   case CK_FloatingToBoolean:
13913   case CK_FloatingCast:
13914   case CK_CPointerToObjCPointerCast:
13915   case CK_BlockPointerToObjCPointerCast:
13916   case CK_AnyPointerToBlockPointerCast:
13917   case CK_ObjCObjectLValueCast:
13918   case CK_FloatingComplexToReal:
13919   case CK_FloatingComplexToBoolean:
13920   case CK_IntegralComplexToReal:
13921   case CK_IntegralComplexToBoolean:
13922   case CK_ARCProduceObject:
13923   case CK_ARCConsumeObject:
13924   case CK_ARCReclaimReturnedObject:
13925   case CK_ARCExtendBlockObject:
13926   case CK_CopyAndAutoreleaseBlockObject:
13927   case CK_BuiltinFnToFnPtr:
13928   case CK_ZeroToOCLOpaqueType:
13929   case CK_NonAtomicToAtomic:
13930   case CK_AddressSpaceConversion:
13931   case CK_IntToOCLSampler:
13932   case CK_FloatingToFixedPoint:
13933   case CK_FixedPointToFloating:
13934   case CK_FixedPointCast:
13935   case CK_FixedPointToBoolean:
13936   case CK_FixedPointToIntegral:
13937   case CK_IntegralToFixedPoint:
13938     llvm_unreachable("invalid cast kind for complex value");
13939 
13940   case CK_LValueToRValue:
13941   case CK_AtomicToNonAtomic:
13942   case CK_NoOp:
13943   case CK_LValueToRValueBitCast:
13944     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13945 
13946   case CK_Dependent:
13947   case CK_LValueBitCast:
13948   case CK_UserDefinedConversion:
13949     return Error(E);
13950 
13951   case CK_FloatingRealToComplex: {
13952     APFloat &Real = Result.FloatReal;
13953     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13954       return false;
13955 
13956     Result.makeComplexFloat();
13957     Result.FloatImag = APFloat(Real.getSemantics());
13958     return true;
13959   }
13960 
13961   case CK_FloatingComplexCast: {
13962     if (!Visit(E->getSubExpr()))
13963       return false;
13964 
13965     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13966     QualType From
13967       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13968 
13969     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13970            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13971   }
13972 
13973   case CK_FloatingComplexToIntegralComplex: {
13974     if (!Visit(E->getSubExpr()))
13975       return false;
13976 
13977     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13978     QualType From
13979       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13980     Result.makeComplexInt();
13981     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13982                                 To, Result.IntReal) &&
13983            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13984                                 To, Result.IntImag);
13985   }
13986 
13987   case CK_IntegralRealToComplex: {
13988     APSInt &Real = Result.IntReal;
13989     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13990       return false;
13991 
13992     Result.makeComplexInt();
13993     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13994     return true;
13995   }
13996 
13997   case CK_IntegralComplexCast: {
13998     if (!Visit(E->getSubExpr()))
13999       return false;
14000 
14001     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14002     QualType From
14003       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14004 
14005     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14006     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14007     return true;
14008   }
14009 
14010   case CK_IntegralComplexToFloatingComplex: {
14011     if (!Visit(E->getSubExpr()))
14012       return false;
14013 
14014     const FPOptions FPO = E->getFPFeaturesInEffect(
14015                                   Info.Ctx.getLangOpts());
14016     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14017     QualType From
14018       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14019     Result.makeComplexFloat();
14020     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14021                                 To, Result.FloatReal) &&
14022            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14023                                 To, Result.FloatImag);
14024   }
14025   }
14026 
14027   llvm_unreachable("unknown cast resulting in complex value");
14028 }
14029 
14030 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14031   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14032     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14033 
14034   // Track whether the LHS or RHS is real at the type system level. When this is
14035   // the case we can simplify our evaluation strategy.
14036   bool LHSReal = false, RHSReal = false;
14037 
14038   bool LHSOK;
14039   if (E->getLHS()->getType()->isRealFloatingType()) {
14040     LHSReal = true;
14041     APFloat &Real = Result.FloatReal;
14042     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14043     if (LHSOK) {
14044       Result.makeComplexFloat();
14045       Result.FloatImag = APFloat(Real.getSemantics());
14046     }
14047   } else {
14048     LHSOK = Visit(E->getLHS());
14049   }
14050   if (!LHSOK && !Info.noteFailure())
14051     return false;
14052 
14053   ComplexValue RHS;
14054   if (E->getRHS()->getType()->isRealFloatingType()) {
14055     RHSReal = true;
14056     APFloat &Real = RHS.FloatReal;
14057     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14058       return false;
14059     RHS.makeComplexFloat();
14060     RHS.FloatImag = APFloat(Real.getSemantics());
14061   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14062     return false;
14063 
14064   assert(!(LHSReal && RHSReal) &&
14065          "Cannot have both operands of a complex operation be real.");
14066   switch (E->getOpcode()) {
14067   default: return Error(E);
14068   case BO_Add:
14069     if (Result.isComplexFloat()) {
14070       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14071                                        APFloat::rmNearestTiesToEven);
14072       if (LHSReal)
14073         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14074       else if (!RHSReal)
14075         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14076                                          APFloat::rmNearestTiesToEven);
14077     } else {
14078       Result.getComplexIntReal() += RHS.getComplexIntReal();
14079       Result.getComplexIntImag() += RHS.getComplexIntImag();
14080     }
14081     break;
14082   case BO_Sub:
14083     if (Result.isComplexFloat()) {
14084       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14085                                             APFloat::rmNearestTiesToEven);
14086       if (LHSReal) {
14087         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14088         Result.getComplexFloatImag().changeSign();
14089       } else if (!RHSReal) {
14090         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14091                                               APFloat::rmNearestTiesToEven);
14092       }
14093     } else {
14094       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14095       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14096     }
14097     break;
14098   case BO_Mul:
14099     if (Result.isComplexFloat()) {
14100       // This is an implementation of complex multiplication according to the
14101       // constraints laid out in C11 Annex G. The implementation uses the
14102       // following naming scheme:
14103       //   (a + ib) * (c + id)
14104       ComplexValue LHS = Result;
14105       APFloat &A = LHS.getComplexFloatReal();
14106       APFloat &B = LHS.getComplexFloatImag();
14107       APFloat &C = RHS.getComplexFloatReal();
14108       APFloat &D = RHS.getComplexFloatImag();
14109       APFloat &ResR = Result.getComplexFloatReal();
14110       APFloat &ResI = Result.getComplexFloatImag();
14111       if (LHSReal) {
14112         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14113         ResR = A * C;
14114         ResI = A * D;
14115       } else if (RHSReal) {
14116         ResR = C * A;
14117         ResI = C * B;
14118       } else {
14119         // In the fully general case, we need to handle NaNs and infinities
14120         // robustly.
14121         APFloat AC = A * C;
14122         APFloat BD = B * D;
14123         APFloat AD = A * D;
14124         APFloat BC = B * C;
14125         ResR = AC - BD;
14126         ResI = AD + BC;
14127         if (ResR.isNaN() && ResI.isNaN()) {
14128           bool Recalc = false;
14129           if (A.isInfinity() || B.isInfinity()) {
14130             A = APFloat::copySign(
14131                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14132             B = APFloat::copySign(
14133                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14134             if (C.isNaN())
14135               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14136             if (D.isNaN())
14137               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14138             Recalc = true;
14139           }
14140           if (C.isInfinity() || D.isInfinity()) {
14141             C = APFloat::copySign(
14142                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14143             D = APFloat::copySign(
14144                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14145             if (A.isNaN())
14146               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14147             if (B.isNaN())
14148               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14149             Recalc = true;
14150           }
14151           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14152                           AD.isInfinity() || BC.isInfinity())) {
14153             if (A.isNaN())
14154               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14155             if (B.isNaN())
14156               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14157             if (C.isNaN())
14158               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14159             if (D.isNaN())
14160               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14161             Recalc = true;
14162           }
14163           if (Recalc) {
14164             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14165             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14166           }
14167         }
14168       }
14169     } else {
14170       ComplexValue LHS = Result;
14171       Result.getComplexIntReal() =
14172         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14173          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14174       Result.getComplexIntImag() =
14175         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14176          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14177     }
14178     break;
14179   case BO_Div:
14180     if (Result.isComplexFloat()) {
14181       // This is an implementation of complex division according to the
14182       // constraints laid out in C11 Annex G. The implementation uses the
14183       // following naming scheme:
14184       //   (a + ib) / (c + id)
14185       ComplexValue LHS = Result;
14186       APFloat &A = LHS.getComplexFloatReal();
14187       APFloat &B = LHS.getComplexFloatImag();
14188       APFloat &C = RHS.getComplexFloatReal();
14189       APFloat &D = RHS.getComplexFloatImag();
14190       APFloat &ResR = Result.getComplexFloatReal();
14191       APFloat &ResI = Result.getComplexFloatImag();
14192       if (RHSReal) {
14193         ResR = A / C;
14194         ResI = B / C;
14195       } else {
14196         if (LHSReal) {
14197           // No real optimizations we can do here, stub out with zero.
14198           B = APFloat::getZero(A.getSemantics());
14199         }
14200         int DenomLogB = 0;
14201         APFloat MaxCD = maxnum(abs(C), abs(D));
14202         if (MaxCD.isFinite()) {
14203           DenomLogB = ilogb(MaxCD);
14204           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14205           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14206         }
14207         APFloat Denom = C * C + D * D;
14208         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14209                       APFloat::rmNearestTiesToEven);
14210         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14211                       APFloat::rmNearestTiesToEven);
14212         if (ResR.isNaN() && ResI.isNaN()) {
14213           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14214             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14215             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14216           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14217                      D.isFinite()) {
14218             A = APFloat::copySign(
14219                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14220             B = APFloat::copySign(
14221                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14222             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14223             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14224           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14225             C = APFloat::copySign(
14226                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14227             D = APFloat::copySign(
14228                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14229             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14230             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14231           }
14232         }
14233       }
14234     } else {
14235       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14236         return Error(E, diag::note_expr_divide_by_zero);
14237 
14238       ComplexValue LHS = Result;
14239       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14240         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14241       Result.getComplexIntReal() =
14242         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14243          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14244       Result.getComplexIntImag() =
14245         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14246          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14247     }
14248     break;
14249   }
14250 
14251   return true;
14252 }
14253 
14254 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14255   // Get the operand value into 'Result'.
14256   if (!Visit(E->getSubExpr()))
14257     return false;
14258 
14259   switch (E->getOpcode()) {
14260   default:
14261     return Error(E);
14262   case UO_Extension:
14263     return true;
14264   case UO_Plus:
14265     // The result is always just the subexpr.
14266     return true;
14267   case UO_Minus:
14268     if (Result.isComplexFloat()) {
14269       Result.getComplexFloatReal().changeSign();
14270       Result.getComplexFloatImag().changeSign();
14271     }
14272     else {
14273       Result.getComplexIntReal() = -Result.getComplexIntReal();
14274       Result.getComplexIntImag() = -Result.getComplexIntImag();
14275     }
14276     return true;
14277   case UO_Not:
14278     if (Result.isComplexFloat())
14279       Result.getComplexFloatImag().changeSign();
14280     else
14281       Result.getComplexIntImag() = -Result.getComplexIntImag();
14282     return true;
14283   }
14284 }
14285 
14286 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14287   if (E->getNumInits() == 2) {
14288     if (E->getType()->isComplexType()) {
14289       Result.makeComplexFloat();
14290       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14291         return false;
14292       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14293         return false;
14294     } else {
14295       Result.makeComplexInt();
14296       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14297         return false;
14298       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14299         return false;
14300     }
14301     return true;
14302   }
14303   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14304 }
14305 
14306 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14307   switch (E->getBuiltinCallee()) {
14308   case Builtin::BI__builtin_complex:
14309     Result.makeComplexFloat();
14310     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14311       return false;
14312     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14313       return false;
14314     return true;
14315 
14316   default:
14317     break;
14318   }
14319 
14320   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14321 }
14322 
14323 //===----------------------------------------------------------------------===//
14324 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14325 // implicit conversion.
14326 //===----------------------------------------------------------------------===//
14327 
14328 namespace {
14329 class AtomicExprEvaluator :
14330     public ExprEvaluatorBase<AtomicExprEvaluator> {
14331   const LValue *This;
14332   APValue &Result;
14333 public:
14334   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14335       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14336 
14337   bool Success(const APValue &V, const Expr *E) {
14338     Result = V;
14339     return true;
14340   }
14341 
14342   bool ZeroInitialization(const Expr *E) {
14343     ImplicitValueInitExpr VIE(
14344         E->getType()->castAs<AtomicType>()->getValueType());
14345     // For atomic-qualified class (and array) types in C++, initialize the
14346     // _Atomic-wrapped subobject directly, in-place.
14347     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14348                 : Evaluate(Result, Info, &VIE);
14349   }
14350 
14351   bool VisitCastExpr(const CastExpr *E) {
14352     switch (E->getCastKind()) {
14353     default:
14354       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14355     case CK_NonAtomicToAtomic:
14356       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14357                   : Evaluate(Result, Info, E->getSubExpr());
14358     }
14359   }
14360 };
14361 } // end anonymous namespace
14362 
14363 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14364                            EvalInfo &Info) {
14365   assert(!E->isValueDependent());
14366   assert(E->isRValue() && E->getType()->isAtomicType());
14367   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14368 }
14369 
14370 //===----------------------------------------------------------------------===//
14371 // Void expression evaluation, primarily for a cast to void on the LHS of a
14372 // comma operator
14373 //===----------------------------------------------------------------------===//
14374 
14375 namespace {
14376 class VoidExprEvaluator
14377   : public ExprEvaluatorBase<VoidExprEvaluator> {
14378 public:
14379   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14380 
14381   bool Success(const APValue &V, const Expr *e) { return true; }
14382 
14383   bool ZeroInitialization(const Expr *E) { return true; }
14384 
14385   bool VisitCastExpr(const CastExpr *E) {
14386     switch (E->getCastKind()) {
14387     default:
14388       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14389     case CK_ToVoid:
14390       VisitIgnoredValue(E->getSubExpr());
14391       return true;
14392     }
14393   }
14394 
14395   bool VisitCallExpr(const CallExpr *E) {
14396     switch (E->getBuiltinCallee()) {
14397     case Builtin::BI__assume:
14398     case Builtin::BI__builtin_assume:
14399       // The argument is not evaluated!
14400       return true;
14401 
14402     case Builtin::BI__builtin_operator_delete:
14403       return HandleOperatorDeleteCall(Info, E);
14404 
14405     default:
14406       break;
14407     }
14408 
14409     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14410   }
14411 
14412   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14413 };
14414 } // end anonymous namespace
14415 
14416 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14417   // We cannot speculatively evaluate a delete expression.
14418   if (Info.SpeculativeEvaluationDepth)
14419     return false;
14420 
14421   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14422   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14423     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14424         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14425     return false;
14426   }
14427 
14428   const Expr *Arg = E->getArgument();
14429 
14430   LValue Pointer;
14431   if (!EvaluatePointer(Arg, Pointer, Info))
14432     return false;
14433   if (Pointer.Designator.Invalid)
14434     return false;
14435 
14436   // Deleting a null pointer has no effect.
14437   if (Pointer.isNullPointer()) {
14438     // This is the only case where we need to produce an extension warning:
14439     // the only other way we can succeed is if we find a dynamic allocation,
14440     // and we will have warned when we allocated it in that case.
14441     if (!Info.getLangOpts().CPlusPlus20)
14442       Info.CCEDiag(E, diag::note_constexpr_new);
14443     return true;
14444   }
14445 
14446   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14447       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14448   if (!Alloc)
14449     return false;
14450   QualType AllocType = Pointer.Base.getDynamicAllocType();
14451 
14452   // For the non-array case, the designator must be empty if the static type
14453   // does not have a virtual destructor.
14454   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14455       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14456     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14457         << Arg->getType()->getPointeeType() << AllocType;
14458     return false;
14459   }
14460 
14461   // For a class type with a virtual destructor, the selected operator delete
14462   // is the one looked up when building the destructor.
14463   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14464     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14465     if (VirtualDelete &&
14466         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14467       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14468           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14469       return false;
14470     }
14471   }
14472 
14473   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14474                          (*Alloc)->Value, AllocType))
14475     return false;
14476 
14477   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14478     // The element was already erased. This means the destructor call also
14479     // deleted the object.
14480     // FIXME: This probably results in undefined behavior before we get this
14481     // far, and should be diagnosed elsewhere first.
14482     Info.FFDiag(E, diag::note_constexpr_double_delete);
14483     return false;
14484   }
14485 
14486   return true;
14487 }
14488 
14489 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14490   assert(!E->isValueDependent());
14491   assert(E->isRValue() && E->getType()->isVoidType());
14492   return VoidExprEvaluator(Info).Visit(E);
14493 }
14494 
14495 //===----------------------------------------------------------------------===//
14496 // Top level Expr::EvaluateAsRValue method.
14497 //===----------------------------------------------------------------------===//
14498 
14499 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14500   assert(!E->isValueDependent());
14501   // In C, function designators are not lvalues, but we evaluate them as if they
14502   // are.
14503   QualType T = E->getType();
14504   if (E->isGLValue() || T->isFunctionType()) {
14505     LValue LV;
14506     if (!EvaluateLValue(E, LV, Info))
14507       return false;
14508     LV.moveInto(Result);
14509   } else if (T->isVectorType()) {
14510     if (!EvaluateVector(E, Result, Info))
14511       return false;
14512   } else if (T->isIntegralOrEnumerationType()) {
14513     if (!IntExprEvaluator(Info, Result).Visit(E))
14514       return false;
14515   } else if (T->hasPointerRepresentation()) {
14516     LValue LV;
14517     if (!EvaluatePointer(E, LV, Info))
14518       return false;
14519     LV.moveInto(Result);
14520   } else if (T->isRealFloatingType()) {
14521     llvm::APFloat F(0.0);
14522     if (!EvaluateFloat(E, F, Info))
14523       return false;
14524     Result = APValue(F);
14525   } else if (T->isAnyComplexType()) {
14526     ComplexValue C;
14527     if (!EvaluateComplex(E, C, Info))
14528       return false;
14529     C.moveInto(Result);
14530   } else if (T->isFixedPointType()) {
14531     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14532   } else if (T->isMemberPointerType()) {
14533     MemberPtr P;
14534     if (!EvaluateMemberPointer(E, P, Info))
14535       return false;
14536     P.moveInto(Result);
14537     return true;
14538   } else if (T->isArrayType()) {
14539     LValue LV;
14540     APValue &Value =
14541         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14542     if (!EvaluateArray(E, LV, Value, Info))
14543       return false;
14544     Result = Value;
14545   } else if (T->isRecordType()) {
14546     LValue LV;
14547     APValue &Value =
14548         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14549     if (!EvaluateRecord(E, LV, Value, Info))
14550       return false;
14551     Result = Value;
14552   } else if (T->isVoidType()) {
14553     if (!Info.getLangOpts().CPlusPlus11)
14554       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14555         << E->getType();
14556     if (!EvaluateVoid(E, Info))
14557       return false;
14558   } else if (T->isAtomicType()) {
14559     QualType Unqual = T.getAtomicUnqualifiedType();
14560     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14561       LValue LV;
14562       APValue &Value = Info.CurrentCall->createTemporary(
14563           E, Unqual, ScopeKind::FullExpression, LV);
14564       if (!EvaluateAtomic(E, &LV, Value, Info))
14565         return false;
14566     } else {
14567       if (!EvaluateAtomic(E, nullptr, Result, Info))
14568         return false;
14569     }
14570   } else if (Info.getLangOpts().CPlusPlus11) {
14571     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14572     return false;
14573   } else {
14574     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14575     return false;
14576   }
14577 
14578   return true;
14579 }
14580 
14581 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14582 /// cases, the in-place evaluation is essential, since later initializers for
14583 /// an object can indirectly refer to subobjects which were initialized earlier.
14584 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14585                             const Expr *E, bool AllowNonLiteralTypes) {
14586   assert(!E->isValueDependent());
14587 
14588   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14589     return false;
14590 
14591   if (E->isRValue()) {
14592     // Evaluate arrays and record types in-place, so that later initializers can
14593     // refer to earlier-initialized members of the object.
14594     QualType T = E->getType();
14595     if (T->isArrayType())
14596       return EvaluateArray(E, This, Result, Info);
14597     else if (T->isRecordType())
14598       return EvaluateRecord(E, This, Result, Info);
14599     else if (T->isAtomicType()) {
14600       QualType Unqual = T.getAtomicUnqualifiedType();
14601       if (Unqual->isArrayType() || Unqual->isRecordType())
14602         return EvaluateAtomic(E, &This, Result, Info);
14603     }
14604   }
14605 
14606   // For any other type, in-place evaluation is unimportant.
14607   return Evaluate(Result, Info, E);
14608 }
14609 
14610 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14611 /// lvalue-to-rvalue cast if it is an lvalue.
14612 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14613   assert(!E->isValueDependent());
14614   if (Info.EnableNewConstInterp) {
14615     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14616       return false;
14617   } else {
14618     if (E->getType().isNull())
14619       return false;
14620 
14621     if (!CheckLiteralType(Info, E))
14622       return false;
14623 
14624     if (!::Evaluate(Result, Info, E))
14625       return false;
14626 
14627     if (E->isGLValue()) {
14628       LValue LV;
14629       LV.setFrom(Info.Ctx, Result);
14630       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14631         return false;
14632     }
14633   }
14634 
14635   // Check this core constant expression is a constant expression.
14636   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14637                                  ConstantExprKind::Normal) &&
14638          CheckMemoryLeaks(Info);
14639 }
14640 
14641 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14642                                  const ASTContext &Ctx, bool &IsConst) {
14643   // Fast-path evaluations of integer literals, since we sometimes see files
14644   // containing vast quantities of these.
14645   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14646     Result.Val = APValue(APSInt(L->getValue(),
14647                                 L->getType()->isUnsignedIntegerType()));
14648     IsConst = true;
14649     return true;
14650   }
14651 
14652   // This case should be rare, but we need to check it before we check on
14653   // the type below.
14654   if (Exp->getType().isNull()) {
14655     IsConst = false;
14656     return true;
14657   }
14658 
14659   // FIXME: Evaluating values of large array and record types can cause
14660   // performance problems. Only do so in C++11 for now.
14661   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
14662                           Exp->getType()->isRecordType()) &&
14663       !Ctx.getLangOpts().CPlusPlus11) {
14664     IsConst = false;
14665     return true;
14666   }
14667   return false;
14668 }
14669 
14670 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14671                                       Expr::SideEffectsKind SEK) {
14672   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14673          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14674 }
14675 
14676 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14677                              const ASTContext &Ctx, EvalInfo &Info) {
14678   assert(!E->isValueDependent());
14679   bool IsConst;
14680   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14681     return IsConst;
14682 
14683   return EvaluateAsRValue(Info, E, Result.Val);
14684 }
14685 
14686 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14687                           const ASTContext &Ctx,
14688                           Expr::SideEffectsKind AllowSideEffects,
14689                           EvalInfo &Info) {
14690   assert(!E->isValueDependent());
14691   if (!E->getType()->isIntegralOrEnumerationType())
14692     return false;
14693 
14694   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14695       !ExprResult.Val.isInt() ||
14696       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14697     return false;
14698 
14699   return true;
14700 }
14701 
14702 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14703                                  const ASTContext &Ctx,
14704                                  Expr::SideEffectsKind AllowSideEffects,
14705                                  EvalInfo &Info) {
14706   assert(!E->isValueDependent());
14707   if (!E->getType()->isFixedPointType())
14708     return false;
14709 
14710   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14711     return false;
14712 
14713   if (!ExprResult.Val.isFixedPoint() ||
14714       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14715     return false;
14716 
14717   return true;
14718 }
14719 
14720 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14721 /// any crazy technique (that has nothing to do with language standards) that
14722 /// we want to.  If this function returns true, it returns the folded constant
14723 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14724 /// will be applied to the result.
14725 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14726                             bool InConstantContext) const {
14727   assert(!isValueDependent() &&
14728          "Expression evaluator can't be called on a dependent expression.");
14729   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14730   Info.InConstantContext = InConstantContext;
14731   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14732 }
14733 
14734 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14735                                       bool InConstantContext) const {
14736   assert(!isValueDependent() &&
14737          "Expression evaluator can't be called on a dependent expression.");
14738   EvalResult Scratch;
14739   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14740          HandleConversionToBool(Scratch.Val, Result);
14741 }
14742 
14743 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14744                          SideEffectsKind AllowSideEffects,
14745                          bool InConstantContext) const {
14746   assert(!isValueDependent() &&
14747          "Expression evaluator can't be called on a dependent expression.");
14748   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14749   Info.InConstantContext = InConstantContext;
14750   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14751 }
14752 
14753 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14754                                 SideEffectsKind AllowSideEffects,
14755                                 bool InConstantContext) const {
14756   assert(!isValueDependent() &&
14757          "Expression evaluator can't be called on a dependent expression.");
14758   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14759   Info.InConstantContext = InConstantContext;
14760   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14761 }
14762 
14763 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14764                            SideEffectsKind AllowSideEffects,
14765                            bool InConstantContext) const {
14766   assert(!isValueDependent() &&
14767          "Expression evaluator can't be called on a dependent expression.");
14768 
14769   if (!getType()->isRealFloatingType())
14770     return false;
14771 
14772   EvalResult ExprResult;
14773   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14774       !ExprResult.Val.isFloat() ||
14775       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14776     return false;
14777 
14778   Result = ExprResult.Val.getFloat();
14779   return true;
14780 }
14781 
14782 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14783                             bool InConstantContext) const {
14784   assert(!isValueDependent() &&
14785          "Expression evaluator can't be called on a dependent expression.");
14786 
14787   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14788   Info.InConstantContext = InConstantContext;
14789   LValue LV;
14790   CheckedTemporaries CheckedTemps;
14791   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14792       Result.HasSideEffects ||
14793       !CheckLValueConstantExpression(Info, getExprLoc(),
14794                                      Ctx.getLValueReferenceType(getType()), LV,
14795                                      ConstantExprKind::Normal, CheckedTemps))
14796     return false;
14797 
14798   LV.moveInto(Result.Val);
14799   return true;
14800 }
14801 
14802 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
14803                                 APValue DestroyedValue, QualType Type,
14804                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
14805                                 bool IsConstantDestruction) {
14806   EvalInfo Info(Ctx, EStatus,
14807                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
14808                                       : EvalInfo::EM_ConstantFold);
14809   Info.setEvaluatingDecl(Base, DestroyedValue,
14810                          EvalInfo::EvaluatingDeclKind::Dtor);
14811   Info.InConstantContext = IsConstantDestruction;
14812 
14813   LValue LVal;
14814   LVal.set(Base);
14815 
14816   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
14817       EStatus.HasSideEffects)
14818     return false;
14819 
14820   if (!Info.discardCleanups())
14821     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14822 
14823   return true;
14824 }
14825 
14826 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
14827                                   ConstantExprKind Kind) const {
14828   assert(!isValueDependent() &&
14829          "Expression evaluator can't be called on a dependent expression.");
14830 
14831   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14832   EvalInfo Info(Ctx, Result, EM);
14833   Info.InConstantContext = true;
14834 
14835   // The type of the object we're initializing is 'const T' for a class NTTP.
14836   QualType T = getType();
14837   if (Kind == ConstantExprKind::ClassTemplateArgument)
14838     T.addConst();
14839 
14840   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
14841   // represent the result of the evaluation. CheckConstantExpression ensures
14842   // this doesn't escape.
14843   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
14844   APValue::LValueBase Base(&BaseMTE);
14845 
14846   Info.setEvaluatingDecl(Base, Result.Val);
14847   LValue LVal;
14848   LVal.set(Base);
14849 
14850   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
14851     return false;
14852 
14853   if (!Info.discardCleanups())
14854     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14855 
14856   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14857                                Result.Val, Kind))
14858     return false;
14859   if (!CheckMemoryLeaks(Info))
14860     return false;
14861 
14862   // If this is a class template argument, it's required to have constant
14863   // destruction too.
14864   if (Kind == ConstantExprKind::ClassTemplateArgument &&
14865       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
14866                             true) ||
14867        Result.HasSideEffects)) {
14868     // FIXME: Prefix a note to indicate that the problem is lack of constant
14869     // destruction.
14870     return false;
14871   }
14872 
14873   return true;
14874 }
14875 
14876 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
14877                                  const VarDecl *VD,
14878                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
14879                                  bool IsConstantInitialization) const {
14880   assert(!isValueDependent() &&
14881          "Expression evaluator can't be called on a dependent expression.");
14882 
14883   // FIXME: Evaluating initializers for large array and record types can cause
14884   // performance problems. Only do so in C++11 for now.
14885   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
14886       !Ctx.getLangOpts().CPlusPlus11)
14887     return false;
14888 
14889   Expr::EvalStatus EStatus;
14890   EStatus.Diag = &Notes;
14891 
14892   EvalInfo Info(Ctx, EStatus,
14893                 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
14894                     ? EvalInfo::EM_ConstantExpression
14895                     : EvalInfo::EM_ConstantFold);
14896   Info.setEvaluatingDecl(VD, Value);
14897   Info.InConstantContext = IsConstantInitialization;
14898 
14899   SourceLocation DeclLoc = VD->getLocation();
14900   QualType DeclTy = VD->getType();
14901 
14902   if (Info.EnableNewConstInterp) {
14903     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
14904     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
14905       return false;
14906   } else {
14907     LValue LVal;
14908     LVal.set(VD);
14909 
14910     if (!EvaluateInPlace(Value, Info, LVal, this,
14911                          /*AllowNonLiteralTypes=*/true) ||
14912         EStatus.HasSideEffects)
14913       return false;
14914 
14915     // At this point, any lifetime-extended temporaries are completely
14916     // initialized.
14917     Info.performLifetimeExtension();
14918 
14919     if (!Info.discardCleanups())
14920       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14921   }
14922   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
14923                                  ConstantExprKind::Normal) &&
14924          CheckMemoryLeaks(Info);
14925 }
14926 
14927 bool VarDecl::evaluateDestruction(
14928     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14929   Expr::EvalStatus EStatus;
14930   EStatus.Diag = &Notes;
14931 
14932   // Only treat the destruction as constant destruction if we formally have
14933   // constant initialization (or are usable in a constant expression).
14934   bool IsConstantDestruction = hasConstantInitialization();
14935 
14936   // Make a copy of the value for the destructor to mutate, if we know it.
14937   // Otherwise, treat the value as default-initialized; if the destructor works
14938   // anyway, then the destruction is constant (and must be essentially empty).
14939   APValue DestroyedValue;
14940   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
14941     DestroyedValue = *getEvaluatedValue();
14942   else if (!getDefaultInitValue(getType(), DestroyedValue))
14943     return false;
14944 
14945   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
14946                            getType(), getLocation(), EStatus,
14947                            IsConstantDestruction) ||
14948       EStatus.HasSideEffects)
14949     return false;
14950 
14951   ensureEvaluatedStmt()->HasConstantDestruction = true;
14952   return true;
14953 }
14954 
14955 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14956 /// constant folded, but discard the result.
14957 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14958   assert(!isValueDependent() &&
14959          "Expression evaluator can't be called on a dependent expression.");
14960 
14961   EvalResult Result;
14962   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14963          !hasUnacceptableSideEffect(Result, SEK);
14964 }
14965 
14966 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14967                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14968   assert(!isValueDependent() &&
14969          "Expression evaluator can't be called on a dependent expression.");
14970 
14971   EvalResult EVResult;
14972   EVResult.Diag = Diag;
14973   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14974   Info.InConstantContext = true;
14975 
14976   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14977   (void)Result;
14978   assert(Result && "Could not evaluate expression");
14979   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14980 
14981   return EVResult.Val.getInt();
14982 }
14983 
14984 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14985     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14986   assert(!isValueDependent() &&
14987          "Expression evaluator can't be called on a dependent expression.");
14988 
14989   EvalResult EVResult;
14990   EVResult.Diag = Diag;
14991   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14992   Info.InConstantContext = true;
14993   Info.CheckingForUndefinedBehavior = true;
14994 
14995   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14996   (void)Result;
14997   assert(Result && "Could not evaluate expression");
14998   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14999 
15000   return EVResult.Val.getInt();
15001 }
15002 
15003 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15004   assert(!isValueDependent() &&
15005          "Expression evaluator can't be called on a dependent expression.");
15006 
15007   bool IsConst;
15008   EvalResult EVResult;
15009   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15010     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15011     Info.CheckingForUndefinedBehavior = true;
15012     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15013   }
15014 }
15015 
15016 bool Expr::EvalResult::isGlobalLValue() const {
15017   assert(Val.isLValue());
15018   return IsGlobalLValue(Val.getLValueBase());
15019 }
15020 
15021 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15022 /// an integer constant expression.
15023 
15024 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15025 /// comma, etc
15026 
15027 // CheckICE - This function does the fundamental ICE checking: the returned
15028 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15029 // and a (possibly null) SourceLocation indicating the location of the problem.
15030 //
15031 // Note that to reduce code duplication, this helper does no evaluation
15032 // itself; the caller checks whether the expression is evaluatable, and
15033 // in the rare cases where CheckICE actually cares about the evaluated
15034 // value, it calls into Evaluate.
15035 
15036 namespace {
15037 
15038 enum ICEKind {
15039   /// This expression is an ICE.
15040   IK_ICE,
15041   /// This expression is not an ICE, but if it isn't evaluated, it's
15042   /// a legal subexpression for an ICE. This return value is used to handle
15043   /// the comma operator in C99 mode, and non-constant subexpressions.
15044   IK_ICEIfUnevaluated,
15045   /// This expression is not an ICE, and is not a legal subexpression for one.
15046   IK_NotICE
15047 };
15048 
15049 struct ICEDiag {
15050   ICEKind Kind;
15051   SourceLocation Loc;
15052 
15053   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15054 };
15055 
15056 }
15057 
15058 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15059 
15060 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15061 
15062 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15063   Expr::EvalResult EVResult;
15064   Expr::EvalStatus Status;
15065   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15066 
15067   Info.InConstantContext = true;
15068   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15069       !EVResult.Val.isInt())
15070     return ICEDiag(IK_NotICE, E->getBeginLoc());
15071 
15072   return NoDiag();
15073 }
15074 
15075 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15076   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15077   if (!E->getType()->isIntegralOrEnumerationType())
15078     return ICEDiag(IK_NotICE, E->getBeginLoc());
15079 
15080   switch (E->getStmtClass()) {
15081 #define ABSTRACT_STMT(Node)
15082 #define STMT(Node, Base) case Expr::Node##Class:
15083 #define EXPR(Node, Base)
15084 #include "clang/AST/StmtNodes.inc"
15085   case Expr::PredefinedExprClass:
15086   case Expr::FloatingLiteralClass:
15087   case Expr::ImaginaryLiteralClass:
15088   case Expr::StringLiteralClass:
15089   case Expr::ArraySubscriptExprClass:
15090   case Expr::MatrixSubscriptExprClass:
15091   case Expr::OMPArraySectionExprClass:
15092   case Expr::OMPArrayShapingExprClass:
15093   case Expr::OMPIteratorExprClass:
15094   case Expr::MemberExprClass:
15095   case Expr::CompoundAssignOperatorClass:
15096   case Expr::CompoundLiteralExprClass:
15097   case Expr::ExtVectorElementExprClass:
15098   case Expr::DesignatedInitExprClass:
15099   case Expr::ArrayInitLoopExprClass:
15100   case Expr::ArrayInitIndexExprClass:
15101   case Expr::NoInitExprClass:
15102   case Expr::DesignatedInitUpdateExprClass:
15103   case Expr::ImplicitValueInitExprClass:
15104   case Expr::ParenListExprClass:
15105   case Expr::VAArgExprClass:
15106   case Expr::AddrLabelExprClass:
15107   case Expr::StmtExprClass:
15108   case Expr::CXXMemberCallExprClass:
15109   case Expr::CUDAKernelCallExprClass:
15110   case Expr::CXXAddrspaceCastExprClass:
15111   case Expr::CXXDynamicCastExprClass:
15112   case Expr::CXXTypeidExprClass:
15113   case Expr::CXXUuidofExprClass:
15114   case Expr::MSPropertyRefExprClass:
15115   case Expr::MSPropertySubscriptExprClass:
15116   case Expr::CXXNullPtrLiteralExprClass:
15117   case Expr::UserDefinedLiteralClass:
15118   case Expr::CXXThisExprClass:
15119   case Expr::CXXThrowExprClass:
15120   case Expr::CXXNewExprClass:
15121   case Expr::CXXDeleteExprClass:
15122   case Expr::CXXPseudoDestructorExprClass:
15123   case Expr::UnresolvedLookupExprClass:
15124   case Expr::TypoExprClass:
15125   case Expr::RecoveryExprClass:
15126   case Expr::DependentScopeDeclRefExprClass:
15127   case Expr::CXXConstructExprClass:
15128   case Expr::CXXInheritedCtorInitExprClass:
15129   case Expr::CXXStdInitializerListExprClass:
15130   case Expr::CXXBindTemporaryExprClass:
15131   case Expr::ExprWithCleanupsClass:
15132   case Expr::CXXTemporaryObjectExprClass:
15133   case Expr::CXXUnresolvedConstructExprClass:
15134   case Expr::CXXDependentScopeMemberExprClass:
15135   case Expr::UnresolvedMemberExprClass:
15136   case Expr::ObjCStringLiteralClass:
15137   case Expr::ObjCBoxedExprClass:
15138   case Expr::ObjCArrayLiteralClass:
15139   case Expr::ObjCDictionaryLiteralClass:
15140   case Expr::ObjCEncodeExprClass:
15141   case Expr::ObjCMessageExprClass:
15142   case Expr::ObjCSelectorExprClass:
15143   case Expr::ObjCProtocolExprClass:
15144   case Expr::ObjCIvarRefExprClass:
15145   case Expr::ObjCPropertyRefExprClass:
15146   case Expr::ObjCSubscriptRefExprClass:
15147   case Expr::ObjCIsaExprClass:
15148   case Expr::ObjCAvailabilityCheckExprClass:
15149   case Expr::ShuffleVectorExprClass:
15150   case Expr::ConvertVectorExprClass:
15151   case Expr::BlockExprClass:
15152   case Expr::NoStmtClass:
15153   case Expr::OpaqueValueExprClass:
15154   case Expr::PackExpansionExprClass:
15155   case Expr::SubstNonTypeTemplateParmPackExprClass:
15156   case Expr::FunctionParmPackExprClass:
15157   case Expr::AsTypeExprClass:
15158   case Expr::ObjCIndirectCopyRestoreExprClass:
15159   case Expr::MaterializeTemporaryExprClass:
15160   case Expr::PseudoObjectExprClass:
15161   case Expr::AtomicExprClass:
15162   case Expr::LambdaExprClass:
15163   case Expr::CXXFoldExprClass:
15164   case Expr::CoawaitExprClass:
15165   case Expr::DependentCoawaitExprClass:
15166   case Expr::CoyieldExprClass:
15167     return ICEDiag(IK_NotICE, E->getBeginLoc());
15168 
15169   case Expr::InitListExprClass: {
15170     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15171     // form "T x = { a };" is equivalent to "T x = a;".
15172     // Unless we're initializing a reference, T is a scalar as it is known to be
15173     // of integral or enumeration type.
15174     if (E->isRValue())
15175       if (cast<InitListExpr>(E)->getNumInits() == 1)
15176         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15177     return ICEDiag(IK_NotICE, E->getBeginLoc());
15178   }
15179 
15180   case Expr::SizeOfPackExprClass:
15181   case Expr::GNUNullExprClass:
15182   case Expr::SourceLocExprClass:
15183     return NoDiag();
15184 
15185   case Expr::SubstNonTypeTemplateParmExprClass:
15186     return
15187       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15188 
15189   case Expr::ConstantExprClass:
15190     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15191 
15192   case Expr::ParenExprClass:
15193     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15194   case Expr::GenericSelectionExprClass:
15195     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15196   case Expr::IntegerLiteralClass:
15197   case Expr::FixedPointLiteralClass:
15198   case Expr::CharacterLiteralClass:
15199   case Expr::ObjCBoolLiteralExprClass:
15200   case Expr::CXXBoolLiteralExprClass:
15201   case Expr::CXXScalarValueInitExprClass:
15202   case Expr::TypeTraitExprClass:
15203   case Expr::ConceptSpecializationExprClass:
15204   case Expr::RequiresExprClass:
15205   case Expr::ArrayTypeTraitExprClass:
15206   case Expr::ExpressionTraitExprClass:
15207   case Expr::CXXNoexceptExprClass:
15208     return NoDiag();
15209   case Expr::CallExprClass:
15210   case Expr::CXXOperatorCallExprClass: {
15211     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15212     // constant expressions, but they can never be ICEs because an ICE cannot
15213     // contain an operand of (pointer to) function type.
15214     const CallExpr *CE = cast<CallExpr>(E);
15215     if (CE->getBuiltinCallee())
15216       return CheckEvalInICE(E, Ctx);
15217     return ICEDiag(IK_NotICE, E->getBeginLoc());
15218   }
15219   case Expr::CXXRewrittenBinaryOperatorClass:
15220     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15221                     Ctx);
15222   case Expr::DeclRefExprClass: {
15223     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15224     if (isa<EnumConstantDecl>(D))
15225       return NoDiag();
15226 
15227     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15228     // integer variables in constant expressions:
15229     //
15230     // C++ 7.1.5.1p2
15231     //   A variable of non-volatile const-qualified integral or enumeration
15232     //   type initialized by an ICE can be used in ICEs.
15233     //
15234     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15235     // that mode, use of reference variables should not be allowed.
15236     const VarDecl *VD = dyn_cast<VarDecl>(D);
15237     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15238         !VD->getType()->isReferenceType())
15239       return NoDiag();
15240 
15241     return ICEDiag(IK_NotICE, E->getBeginLoc());
15242   }
15243   case Expr::UnaryOperatorClass: {
15244     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15245     switch (Exp->getOpcode()) {
15246     case UO_PostInc:
15247     case UO_PostDec:
15248     case UO_PreInc:
15249     case UO_PreDec:
15250     case UO_AddrOf:
15251     case UO_Deref:
15252     case UO_Coawait:
15253       // C99 6.6/3 allows increment and decrement within unevaluated
15254       // subexpressions of constant expressions, but they can never be ICEs
15255       // because an ICE cannot contain an lvalue operand.
15256       return ICEDiag(IK_NotICE, E->getBeginLoc());
15257     case UO_Extension:
15258     case UO_LNot:
15259     case UO_Plus:
15260     case UO_Minus:
15261     case UO_Not:
15262     case UO_Real:
15263     case UO_Imag:
15264       return CheckICE(Exp->getSubExpr(), Ctx);
15265     }
15266     llvm_unreachable("invalid unary operator class");
15267   }
15268   case Expr::OffsetOfExprClass: {
15269     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15270     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15271     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15272     // compliance: we should warn earlier for offsetof expressions with
15273     // array subscripts that aren't ICEs, and if the array subscripts
15274     // are ICEs, the value of the offsetof must be an integer constant.
15275     return CheckEvalInICE(E, Ctx);
15276   }
15277   case Expr::UnaryExprOrTypeTraitExprClass: {
15278     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15279     if ((Exp->getKind() ==  UETT_SizeOf) &&
15280         Exp->getTypeOfArgument()->isVariableArrayType())
15281       return ICEDiag(IK_NotICE, E->getBeginLoc());
15282     return NoDiag();
15283   }
15284   case Expr::BinaryOperatorClass: {
15285     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15286     switch (Exp->getOpcode()) {
15287     case BO_PtrMemD:
15288     case BO_PtrMemI:
15289     case BO_Assign:
15290     case BO_MulAssign:
15291     case BO_DivAssign:
15292     case BO_RemAssign:
15293     case BO_AddAssign:
15294     case BO_SubAssign:
15295     case BO_ShlAssign:
15296     case BO_ShrAssign:
15297     case BO_AndAssign:
15298     case BO_XorAssign:
15299     case BO_OrAssign:
15300       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15301       // constant expressions, but they can never be ICEs because an ICE cannot
15302       // contain an lvalue operand.
15303       return ICEDiag(IK_NotICE, E->getBeginLoc());
15304 
15305     case BO_Mul:
15306     case BO_Div:
15307     case BO_Rem:
15308     case BO_Add:
15309     case BO_Sub:
15310     case BO_Shl:
15311     case BO_Shr:
15312     case BO_LT:
15313     case BO_GT:
15314     case BO_LE:
15315     case BO_GE:
15316     case BO_EQ:
15317     case BO_NE:
15318     case BO_And:
15319     case BO_Xor:
15320     case BO_Or:
15321     case BO_Comma:
15322     case BO_Cmp: {
15323       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15324       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15325       if (Exp->getOpcode() == BO_Div ||
15326           Exp->getOpcode() == BO_Rem) {
15327         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15328         // we don't evaluate one.
15329         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15330           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15331           if (REval == 0)
15332             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15333           if (REval.isSigned() && REval.isAllOnesValue()) {
15334             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15335             if (LEval.isMinSignedValue())
15336               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15337           }
15338         }
15339       }
15340       if (Exp->getOpcode() == BO_Comma) {
15341         if (Ctx.getLangOpts().C99) {
15342           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15343           // if it isn't evaluated.
15344           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15345             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15346         } else {
15347           // In both C89 and C++, commas in ICEs are illegal.
15348           return ICEDiag(IK_NotICE, E->getBeginLoc());
15349         }
15350       }
15351       return Worst(LHSResult, RHSResult);
15352     }
15353     case BO_LAnd:
15354     case BO_LOr: {
15355       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15356       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15357       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15358         // Rare case where the RHS has a comma "side-effect"; we need
15359         // to actually check the condition to see whether the side
15360         // with the comma is evaluated.
15361         if ((Exp->getOpcode() == BO_LAnd) !=
15362             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15363           return RHSResult;
15364         return NoDiag();
15365       }
15366 
15367       return Worst(LHSResult, RHSResult);
15368     }
15369     }
15370     llvm_unreachable("invalid binary operator kind");
15371   }
15372   case Expr::ImplicitCastExprClass:
15373   case Expr::CStyleCastExprClass:
15374   case Expr::CXXFunctionalCastExprClass:
15375   case Expr::CXXStaticCastExprClass:
15376   case Expr::CXXReinterpretCastExprClass:
15377   case Expr::CXXConstCastExprClass:
15378   case Expr::ObjCBridgedCastExprClass: {
15379     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15380     if (isa<ExplicitCastExpr>(E)) {
15381       if (const FloatingLiteral *FL
15382             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15383         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15384         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15385         APSInt IgnoredVal(DestWidth, !DestSigned);
15386         bool Ignored;
15387         // If the value does not fit in the destination type, the behavior is
15388         // undefined, so we are not required to treat it as a constant
15389         // expression.
15390         if (FL->getValue().convertToInteger(IgnoredVal,
15391                                             llvm::APFloat::rmTowardZero,
15392                                             &Ignored) & APFloat::opInvalidOp)
15393           return ICEDiag(IK_NotICE, E->getBeginLoc());
15394         return NoDiag();
15395       }
15396     }
15397     switch (cast<CastExpr>(E)->getCastKind()) {
15398     case CK_LValueToRValue:
15399     case CK_AtomicToNonAtomic:
15400     case CK_NonAtomicToAtomic:
15401     case CK_NoOp:
15402     case CK_IntegralToBoolean:
15403     case CK_IntegralCast:
15404       return CheckICE(SubExpr, Ctx);
15405     default:
15406       return ICEDiag(IK_NotICE, E->getBeginLoc());
15407     }
15408   }
15409   case Expr::BinaryConditionalOperatorClass: {
15410     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15411     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15412     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15413     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15414     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15415     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15416     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15417         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15418     return FalseResult;
15419   }
15420   case Expr::ConditionalOperatorClass: {
15421     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15422     // If the condition (ignoring parens) is a __builtin_constant_p call,
15423     // then only the true side is actually considered in an integer constant
15424     // expression, and it is fully evaluated.  This is an important GNU
15425     // extension.  See GCC PR38377 for discussion.
15426     if (const CallExpr *CallCE
15427         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15428       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15429         return CheckEvalInICE(E, Ctx);
15430     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15431     if (CondResult.Kind == IK_NotICE)
15432       return CondResult;
15433 
15434     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15435     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15436 
15437     if (TrueResult.Kind == IK_NotICE)
15438       return TrueResult;
15439     if (FalseResult.Kind == IK_NotICE)
15440       return FalseResult;
15441     if (CondResult.Kind == IK_ICEIfUnevaluated)
15442       return CondResult;
15443     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15444       return NoDiag();
15445     // Rare case where the diagnostics depend on which side is evaluated
15446     // Note that if we get here, CondResult is 0, and at least one of
15447     // TrueResult and FalseResult is non-zero.
15448     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15449       return FalseResult;
15450     return TrueResult;
15451   }
15452   case Expr::CXXDefaultArgExprClass:
15453     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15454   case Expr::CXXDefaultInitExprClass:
15455     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15456   case Expr::ChooseExprClass: {
15457     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15458   }
15459   case Expr::BuiltinBitCastExprClass: {
15460     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15461       return ICEDiag(IK_NotICE, E->getBeginLoc());
15462     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15463   }
15464   }
15465 
15466   llvm_unreachable("Invalid StmtClass!");
15467 }
15468 
15469 /// Evaluate an expression as a C++11 integral constant expression.
15470 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15471                                                     const Expr *E,
15472                                                     llvm::APSInt *Value,
15473                                                     SourceLocation *Loc) {
15474   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15475     if (Loc) *Loc = E->getExprLoc();
15476     return false;
15477   }
15478 
15479   APValue Result;
15480   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15481     return false;
15482 
15483   if (!Result.isInt()) {
15484     if (Loc) *Loc = E->getExprLoc();
15485     return false;
15486   }
15487 
15488   if (Value) *Value = Result.getInt();
15489   return true;
15490 }
15491 
15492 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15493                                  SourceLocation *Loc) const {
15494   assert(!isValueDependent() &&
15495          "Expression evaluator can't be called on a dependent expression.");
15496 
15497   if (Ctx.getLangOpts().CPlusPlus11)
15498     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15499 
15500   ICEDiag D = CheckICE(this, Ctx);
15501   if (D.Kind != IK_ICE) {
15502     if (Loc) *Loc = D.Loc;
15503     return false;
15504   }
15505   return true;
15506 }
15507 
15508 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15509                                                     SourceLocation *Loc,
15510                                                     bool isEvaluated) const {
15511   assert(!isValueDependent() &&
15512          "Expression evaluator can't be called on a dependent expression.");
15513 
15514   APSInt Value;
15515 
15516   if (Ctx.getLangOpts().CPlusPlus11) {
15517     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15518       return Value;
15519     return None;
15520   }
15521 
15522   if (!isIntegerConstantExpr(Ctx, Loc))
15523     return None;
15524 
15525   // The only possible side-effects here are due to UB discovered in the
15526   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15527   // required to treat the expression as an ICE, so we produce the folded
15528   // value.
15529   EvalResult ExprResult;
15530   Expr::EvalStatus Status;
15531   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15532   Info.InConstantContext = true;
15533 
15534   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15535     llvm_unreachable("ICE cannot be evaluated!");
15536 
15537   return ExprResult.Val.getInt();
15538 }
15539 
15540 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15541   assert(!isValueDependent() &&
15542          "Expression evaluator can't be called on a dependent expression.");
15543 
15544   return CheckICE(this, Ctx).Kind == IK_ICE;
15545 }
15546 
15547 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15548                                SourceLocation *Loc) const {
15549   assert(!isValueDependent() &&
15550          "Expression evaluator can't be called on a dependent expression.");
15551 
15552   // We support this checking in C++98 mode in order to diagnose compatibility
15553   // issues.
15554   assert(Ctx.getLangOpts().CPlusPlus);
15555 
15556   // Build evaluation settings.
15557   Expr::EvalStatus Status;
15558   SmallVector<PartialDiagnosticAt, 8> Diags;
15559   Status.Diag = &Diags;
15560   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15561 
15562   APValue Scratch;
15563   bool IsConstExpr =
15564       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15565       // FIXME: We don't produce a diagnostic for this, but the callers that
15566       // call us on arbitrary full-expressions should generally not care.
15567       Info.discardCleanups() && !Status.HasSideEffects;
15568 
15569   if (!Diags.empty()) {
15570     IsConstExpr = false;
15571     if (Loc) *Loc = Diags[0].first;
15572   } else if (!IsConstExpr) {
15573     // FIXME: This shouldn't happen.
15574     if (Loc) *Loc = getExprLoc();
15575   }
15576 
15577   return IsConstExpr;
15578 }
15579 
15580 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15581                                     const FunctionDecl *Callee,
15582                                     ArrayRef<const Expr*> Args,
15583                                     const Expr *This) const {
15584   assert(!isValueDependent() &&
15585          "Expression evaluator can't be called on a dependent expression.");
15586 
15587   Expr::EvalStatus Status;
15588   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15589   Info.InConstantContext = true;
15590 
15591   LValue ThisVal;
15592   const LValue *ThisPtr = nullptr;
15593   if (This) {
15594 #ifndef NDEBUG
15595     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15596     assert(MD && "Don't provide `this` for non-methods.");
15597     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15598 #endif
15599     if (!This->isValueDependent() &&
15600         EvaluateObjectArgument(Info, This, ThisVal) &&
15601         !Info.EvalStatus.HasSideEffects)
15602       ThisPtr = &ThisVal;
15603 
15604     // Ignore any side-effects from a failed evaluation. This is safe because
15605     // they can't interfere with any other argument evaluation.
15606     Info.EvalStatus.HasSideEffects = false;
15607   }
15608 
15609   CallRef Call = Info.CurrentCall->createCall(Callee);
15610   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15611        I != E; ++I) {
15612     unsigned Idx = I - Args.begin();
15613     if (Idx >= Callee->getNumParams())
15614       break;
15615     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15616     if ((*I)->isValueDependent() ||
15617         !EvaluateCallArg(PVD, *I, Call, Info) ||
15618         Info.EvalStatus.HasSideEffects) {
15619       // If evaluation fails, throw away the argument entirely.
15620       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15621         *Slot = APValue();
15622     }
15623 
15624     // Ignore any side-effects from a failed evaluation. This is safe because
15625     // they can't interfere with any other argument evaluation.
15626     Info.EvalStatus.HasSideEffects = false;
15627   }
15628 
15629   // Parameter cleanups happen in the caller and are not part of this
15630   // evaluation.
15631   Info.discardCleanups();
15632   Info.EvalStatus.HasSideEffects = false;
15633 
15634   // Build fake call to Callee.
15635   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15636   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15637   FullExpressionRAII Scope(Info);
15638   return Evaluate(Value, Info, this) && Scope.destroy() &&
15639          !Info.EvalStatus.HasSideEffects;
15640 }
15641 
15642 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15643                                    SmallVectorImpl<
15644                                      PartialDiagnosticAt> &Diags) {
15645   // FIXME: It would be useful to check constexpr function templates, but at the
15646   // moment the constant expression evaluator cannot cope with the non-rigorous
15647   // ASTs which we build for dependent expressions.
15648   if (FD->isDependentContext())
15649     return true;
15650 
15651   Expr::EvalStatus Status;
15652   Status.Diag = &Diags;
15653 
15654   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15655   Info.InConstantContext = true;
15656   Info.CheckingPotentialConstantExpression = true;
15657 
15658   // The constexpr VM attempts to compile all methods to bytecode here.
15659   if (Info.EnableNewConstInterp) {
15660     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15661     return Diags.empty();
15662   }
15663 
15664   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15665   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15666 
15667   // Fabricate an arbitrary expression on the stack and pretend that it
15668   // is a temporary being used as the 'this' pointer.
15669   LValue This;
15670   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15671   This.set({&VIE, Info.CurrentCall->Index});
15672 
15673   ArrayRef<const Expr*> Args;
15674 
15675   APValue Scratch;
15676   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15677     // Evaluate the call as a constant initializer, to allow the construction
15678     // of objects of non-literal types.
15679     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15680     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15681   } else {
15682     SourceLocation Loc = FD->getLocation();
15683     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15684                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15685   }
15686 
15687   return Diags.empty();
15688 }
15689 
15690 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15691                                               const FunctionDecl *FD,
15692                                               SmallVectorImpl<
15693                                                 PartialDiagnosticAt> &Diags) {
15694   assert(!E->isValueDependent() &&
15695          "Expression evaluator can't be called on a dependent expression.");
15696 
15697   Expr::EvalStatus Status;
15698   Status.Diag = &Diags;
15699 
15700   EvalInfo Info(FD->getASTContext(), Status,
15701                 EvalInfo::EM_ConstantExpressionUnevaluated);
15702   Info.InConstantContext = true;
15703   Info.CheckingPotentialConstantExpression = true;
15704 
15705   // Fabricate a call stack frame to give the arguments a plausible cover story.
15706   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15707 
15708   APValue ResultScratch;
15709   Evaluate(ResultScratch, Info, E);
15710   return Diags.empty();
15711 }
15712 
15713 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15714                                  unsigned Type) const {
15715   if (!getType()->isPointerType())
15716     return false;
15717 
15718   Expr::EvalStatus Status;
15719   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15720   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15721 }
15722