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->isPRValue())
105       return E->getType();
106     return Ctx.getLValueReferenceType(E->getType());
107   }
108 
109   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
110   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
111     if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
112       return DirectCallee->getAttr<AllocSizeAttr>();
113     if (const Decl *IndirectCallee = CE->getCalleeDecl())
114       return IndirectCallee->getAttr<AllocSizeAttr>();
115     return nullptr;
116   }
117 
118   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119   /// This will look through a single cast.
120   ///
121   /// Returns null if we couldn't unwrap a function with alloc_size.
122   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123     if (!E->getType()->isPointerType())
124       return nullptr;
125 
126     E = E->IgnoreParens();
127     // If we're doing a variable assignment from e.g. malloc(N), there will
128     // probably be a cast of some kind. In exotic cases, we might also see a
129     // top-level ExprWithCleanups. Ignore them either way.
130     if (const auto *FE = dyn_cast<FullExpr>(E))
131       E = FE->getSubExpr()->IgnoreParens();
132 
133     if (const auto *Cast = dyn_cast<CastExpr>(E))
134       E = Cast->getSubExpr()->IgnoreParens();
135 
136     if (const auto *CE = dyn_cast<CallExpr>(E))
137       return getAllocSizeAttr(CE) ? CE : nullptr;
138     return nullptr;
139   }
140 
141   /// Determines whether or not the given Base contains a call to a function
142   /// with the alloc_size attribute.
143   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
144     const auto *E = Base.dyn_cast<const Expr *>();
145     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
146   }
147 
148   /// Determines whether the given kind of constant expression is only ever
149   /// used for name mangling. If so, it's permitted to reference things that we
150   /// can't generate code for (in particular, dllimported functions).
151   static bool isForManglingOnly(ConstantExprKind Kind) {
152     switch (Kind) {
153     case ConstantExprKind::Normal:
154     case ConstantExprKind::ClassTemplateArgument:
155     case ConstantExprKind::ImmediateInvocation:
156       // Note that non-type template arguments of class type are emitted as
157       // template parameter objects.
158       return false;
159 
160     case ConstantExprKind::NonClassTemplateArgument:
161       return true;
162     }
163     llvm_unreachable("unknown ConstantExprKind");
164   }
165 
166   static bool isTemplateArgument(ConstantExprKind Kind) {
167     switch (Kind) {
168     case ConstantExprKind::Normal:
169     case ConstantExprKind::ImmediateInvocation:
170       return false;
171 
172     case ConstantExprKind::ClassTemplateArgument:
173     case ConstantExprKind::NonClassTemplateArgument:
174       return true;
175     }
176     llvm_unreachable("unknown ConstantExprKind");
177   }
178 
179   /// The bound to claim that an array of unknown bound has.
180   /// The value in MostDerivedArraySize is undefined in this case. So, set it
181   /// to an arbitrary value that's likely to loudly break things if it's used.
182   static const uint64_t AssumedSizeForUnsizedArray =
183       std::numeric_limits<uint64_t>::max() / 2;
184 
185   /// Determines if an LValue with the given LValueBase will have an unsized
186   /// array in its designator.
187   /// Find the path length and type of the most-derived subobject in the given
188   /// path, and find the size of the containing array, if any.
189   static unsigned
190   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
191                            ArrayRef<APValue::LValuePathEntry> Path,
192                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
193                            bool &FirstEntryIsUnsizedArray) {
194     // This only accepts LValueBases from APValues, and APValues don't support
195     // arrays that lack size info.
196     assert(!isBaseAnAllocSizeCall(Base) &&
197            "Unsized arrays shouldn't appear here");
198     unsigned MostDerivedLength = 0;
199     Type = getType(Base);
200 
201     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
202       if (Type->isArrayType()) {
203         const ArrayType *AT = Ctx.getAsArrayType(Type);
204         Type = AT->getElementType();
205         MostDerivedLength = I + 1;
206         IsArray = true;
207 
208         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
209           ArraySize = CAT->getSize().getZExtValue();
210         } else {
211           assert(I == 0 && "unexpected unsized array designator");
212           FirstEntryIsUnsizedArray = true;
213           ArraySize = AssumedSizeForUnsizedArray;
214         }
215       } else if (Type->isAnyComplexType()) {
216         const ComplexType *CT = Type->castAs<ComplexType>();
217         Type = CT->getElementType();
218         ArraySize = 2;
219         MostDerivedLength = I + 1;
220         IsArray = true;
221       } else if (const FieldDecl *FD = getAsField(Path[I])) {
222         Type = FD->getType();
223         ArraySize = 0;
224         MostDerivedLength = I + 1;
225         IsArray = false;
226       } else {
227         // Path[I] describes a base class.
228         ArraySize = 0;
229         IsArray = false;
230       }
231     }
232     return MostDerivedLength;
233   }
234 
235   /// A path from a glvalue to a subobject of that glvalue.
236   struct SubobjectDesignator {
237     /// True if the subobject was named in a manner not supported by C++11. Such
238     /// lvalues can still be folded, but they are not core constant expressions
239     /// and we cannot perform lvalue-to-rvalue conversions on them.
240     unsigned Invalid : 1;
241 
242     /// Is this a pointer one past the end of an object?
243     unsigned IsOnePastTheEnd : 1;
244 
245     /// Indicator of whether the first entry is an unsized array.
246     unsigned FirstEntryIsAnUnsizedArray : 1;
247 
248     /// Indicator of whether the most-derived object is an array element.
249     unsigned MostDerivedIsArrayElement : 1;
250 
251     /// The length of the path to the most-derived object of which this is a
252     /// subobject.
253     unsigned MostDerivedPathLength : 28;
254 
255     /// The size of the array of which the most-derived object is an element.
256     /// This will always be 0 if the most-derived object is not an array
257     /// element. 0 is not an indicator of whether or not the most-derived object
258     /// is an array, however, because 0-length arrays are allowed.
259     ///
260     /// If the current array is an unsized array, the value of this is
261     /// undefined.
262     uint64_t MostDerivedArraySize;
263 
264     /// The type of the most derived object referred to by this address.
265     QualType MostDerivedType;
266 
267     typedef APValue::LValuePathEntry PathEntry;
268 
269     /// The entries on the path from the glvalue to the designated subobject.
270     SmallVector<PathEntry, 8> Entries;
271 
272     SubobjectDesignator() : Invalid(true) {}
273 
274     explicit SubobjectDesignator(QualType T)
275         : Invalid(false), IsOnePastTheEnd(false),
276           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
277           MostDerivedPathLength(0), MostDerivedArraySize(0),
278           MostDerivedType(T) {}
279 
280     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
281         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
282           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
283           MostDerivedPathLength(0), MostDerivedArraySize(0) {
284       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
285       if (!Invalid) {
286         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
287         ArrayRef<PathEntry> VEntries = V.getLValuePath();
288         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
289         if (V.getLValueBase()) {
290           bool IsArray = false;
291           bool FirstIsUnsizedArray = false;
292           MostDerivedPathLength = findMostDerivedSubobject(
293               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
294               MostDerivedType, IsArray, FirstIsUnsizedArray);
295           MostDerivedIsArrayElement = IsArray;
296           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
297         }
298       }
299     }
300 
301     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
302                   unsigned NewLength) {
303       if (Invalid)
304         return;
305 
306       assert(Base && "cannot truncate path for null pointer");
307       assert(NewLength <= Entries.size() && "not a truncation");
308 
309       if (NewLength == Entries.size())
310         return;
311       Entries.resize(NewLength);
312 
313       bool IsArray = false;
314       bool FirstIsUnsizedArray = false;
315       MostDerivedPathLength = findMostDerivedSubobject(
316           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
317           FirstIsUnsizedArray);
318       MostDerivedIsArrayElement = IsArray;
319       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
320     }
321 
322     void setInvalid() {
323       Invalid = true;
324       Entries.clear();
325     }
326 
327     /// Determine whether the most derived subobject is an array without a
328     /// known bound.
329     bool isMostDerivedAnUnsizedArray() const {
330       assert(!Invalid && "Calling this makes no sense on invalid designators");
331       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
332     }
333 
334     /// Determine what the most derived array's size is. Results in an assertion
335     /// failure if the most derived array lacks a size.
336     uint64_t getMostDerivedArraySize() const {
337       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
338       return MostDerivedArraySize;
339     }
340 
341     /// Determine whether this is a one-past-the-end pointer.
342     bool isOnePastTheEnd() const {
343       assert(!Invalid);
344       if (IsOnePastTheEnd)
345         return true;
346       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
347           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
348               MostDerivedArraySize)
349         return true;
350       return false;
351     }
352 
353     /// Get the range of valid index adjustments in the form
354     ///   {maximum value that can be subtracted from this pointer,
355     ///    maximum value that can be added to this pointer}
356     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
357       if (Invalid || isMostDerivedAnUnsizedArray())
358         return {0, 0};
359 
360       // [expr.add]p4: For the purposes of these operators, a pointer to a
361       // nonarray object behaves the same as a pointer to the first element of
362       // an array of length one with the type of the object as its element type.
363       bool IsArray = MostDerivedPathLength == Entries.size() &&
364                      MostDerivedIsArrayElement;
365       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
366                                     : (uint64_t)IsOnePastTheEnd;
367       uint64_t ArraySize =
368           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
369       return {ArrayIndex, ArraySize - ArrayIndex};
370     }
371 
372     /// Check that this refers to a valid subobject.
373     bool isValidSubobject() const {
374       if (Invalid)
375         return false;
376       return !isOnePastTheEnd();
377     }
378     /// Check that this refers to a valid subobject, and if not, produce a
379     /// relevant diagnostic and set the designator as invalid.
380     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
381 
382     /// Get the type of the designated object.
383     QualType getType(ASTContext &Ctx) const {
384       assert(!Invalid && "invalid designator has no subobject type");
385       return MostDerivedPathLength == Entries.size()
386                  ? MostDerivedType
387                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
388     }
389 
390     /// Update this designator to refer to the first element within this array.
391     void addArrayUnchecked(const ConstantArrayType *CAT) {
392       Entries.push_back(PathEntry::ArrayIndex(0));
393 
394       // This is a most-derived object.
395       MostDerivedType = CAT->getElementType();
396       MostDerivedIsArrayElement = true;
397       MostDerivedArraySize = CAT->getSize().getZExtValue();
398       MostDerivedPathLength = Entries.size();
399     }
400     /// Update this designator to refer to the first element within the array of
401     /// elements of type T. This is an array of unknown size.
402     void addUnsizedArrayUnchecked(QualType ElemTy) {
403       Entries.push_back(PathEntry::ArrayIndex(0));
404 
405       MostDerivedType = ElemTy;
406       MostDerivedIsArrayElement = true;
407       // The value in MostDerivedArraySize is undefined in this case. So, set it
408       // to an arbitrary value that's likely to loudly break things if it's
409       // used.
410       MostDerivedArraySize = AssumedSizeForUnsizedArray;
411       MostDerivedPathLength = Entries.size();
412     }
413     /// Update this designator to refer to the given base or member of this
414     /// object.
415     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
416       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
417 
418       // If this isn't a base class, it's a new most-derived object.
419       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
420         MostDerivedType = FD->getType();
421         MostDerivedIsArrayElement = false;
422         MostDerivedArraySize = 0;
423         MostDerivedPathLength = Entries.size();
424       }
425     }
426     /// Update this designator to refer to the given complex component.
427     void addComplexUnchecked(QualType EltTy, bool Imag) {
428       Entries.push_back(PathEntry::ArrayIndex(Imag));
429 
430       // This is technically a most-derived object, though in practice this
431       // is unlikely to matter.
432       MostDerivedType = EltTy;
433       MostDerivedIsArrayElement = true;
434       MostDerivedArraySize = 2;
435       MostDerivedPathLength = Entries.size();
436     }
437     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
438     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
439                                    const APSInt &N);
440     /// Add N to the address of this subobject.
441     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
442       if (Invalid || !N) return;
443       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
444       if (isMostDerivedAnUnsizedArray()) {
445         diagnoseUnsizedArrayPointerArithmetic(Info, E);
446         // Can't verify -- trust that the user is doing the right thing (or if
447         // not, trust that the caller will catch the bad behavior).
448         // FIXME: Should we reject if this overflows, at least?
449         Entries.back() = PathEntry::ArrayIndex(
450             Entries.back().getAsArrayIndex() + TruncatedN);
451         return;
452       }
453 
454       // [expr.add]p4: For the purposes of these operators, a pointer to a
455       // nonarray object behaves the same as a pointer to the first element of
456       // an array of length one with the type of the object as its element type.
457       bool IsArray = MostDerivedPathLength == Entries.size() &&
458                      MostDerivedIsArrayElement;
459       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
460                                     : (uint64_t)IsOnePastTheEnd;
461       uint64_t ArraySize =
462           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
463 
464       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
465         // Calculate the actual index in a wide enough type, so we can include
466         // it in the note.
467         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
468         (llvm::APInt&)N += ArrayIndex;
469         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
470         diagnosePointerArithmetic(Info, E, N);
471         setInvalid();
472         return;
473       }
474 
475       ArrayIndex += TruncatedN;
476       assert(ArrayIndex <= ArraySize &&
477              "bounds check succeeded for out-of-bounds index");
478 
479       if (IsArray)
480         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
481       else
482         IsOnePastTheEnd = (ArrayIndex != 0);
483     }
484   };
485 
486   /// A scope at the end of which an object can need to be destroyed.
487   enum class ScopeKind {
488     Block,
489     FullExpression,
490     Call
491   };
492 
493   /// A reference to a particular call and its arguments.
494   struct CallRef {
495     CallRef() : OrigCallee(), CallIndex(0), Version() {}
496     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
497         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
498 
499     explicit operator bool() const { return OrigCallee; }
500 
501     /// Get the parameter that the caller initialized, corresponding to the
502     /// given parameter in the callee.
503     const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
504       return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
505                         : PVD;
506     }
507 
508     /// The callee at the point where the arguments were evaluated. This might
509     /// be different from the actual callee (a different redeclaration, or a
510     /// virtual override), but this function's parameters are the ones that
511     /// appear in the parameter map.
512     const FunctionDecl *OrigCallee;
513     /// The call index of the frame that holds the argument values.
514     unsigned CallIndex;
515     /// The version of the parameters corresponding to this call.
516     unsigned Version;
517   };
518 
519   /// A stack frame in the constexpr call stack.
520   class CallStackFrame : public interp::Frame {
521   public:
522     EvalInfo &Info;
523 
524     /// Parent - The caller of this stack frame.
525     CallStackFrame *Caller;
526 
527     /// Callee - The function which was called.
528     const FunctionDecl *Callee;
529 
530     /// This - The binding for the this pointer in this call, if any.
531     const LValue *This;
532 
533     /// Information on how to find the arguments to this call. Our arguments
534     /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
535     /// key and this value as the version.
536     CallRef Arguments;
537 
538     /// Source location information about the default argument or default
539     /// initializer expression we're evaluating, if any.
540     CurrentSourceLocExprScope CurSourceLocExprScope;
541 
542     // Note that we intentionally use std::map here so that references to
543     // values are stable.
544     typedef std::pair<const void *, unsigned> MapKeyTy;
545     typedef std::map<MapKeyTy, APValue> MapTy;
546     /// Temporaries - Temporary lvalues materialized within this stack frame.
547     MapTy Temporaries;
548 
549     /// CallLoc - The location of the call expression for this call.
550     SourceLocation CallLoc;
551 
552     /// Index - The call index of this call.
553     unsigned Index;
554 
555     /// The stack of integers for tracking version numbers for temporaries.
556     SmallVector<unsigned, 2> TempVersionStack = {1};
557     unsigned CurTempVersion = TempVersionStack.back();
558 
559     unsigned getTempVersion() const { return TempVersionStack.back(); }
560 
561     void pushTempVersion() {
562       TempVersionStack.push_back(++CurTempVersion);
563     }
564 
565     void popTempVersion() {
566       TempVersionStack.pop_back();
567     }
568 
569     CallRef createCall(const FunctionDecl *Callee) {
570       return {Callee, Index, ++CurTempVersion};
571     }
572 
573     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
574     // on the overall stack usage of deeply-recursing constexpr evaluations.
575     // (We should cache this map rather than recomputing it repeatedly.)
576     // But let's try this and see how it goes; we can look into caching the map
577     // as a later change.
578 
579     /// LambdaCaptureFields - Mapping from captured variables/this to
580     /// corresponding data members in the closure class.
581     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
582     FieldDecl *LambdaThisCaptureField;
583 
584     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
585                    const FunctionDecl *Callee, const LValue *This,
586                    CallRef Arguments);
587     ~CallStackFrame();
588 
589     // Return the temporary for Key whose version number is Version.
590     APValue *getTemporary(const void *Key, unsigned Version) {
591       MapKeyTy KV(Key, Version);
592       auto LB = Temporaries.lower_bound(KV);
593       if (LB != Temporaries.end() && LB->first == KV)
594         return &LB->second;
595       // Pair (Key,Version) wasn't found in the map. Check that no elements
596       // in the map have 'Key' as their key.
597       assert((LB == Temporaries.end() || LB->first.first != Key) &&
598              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
599              "Element with key 'Key' found in map");
600       return nullptr;
601     }
602 
603     // Return the current temporary for Key in the map.
604     APValue *getCurrentTemporary(const void *Key) {
605       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
606       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
607         return &std::prev(UB)->second;
608       return nullptr;
609     }
610 
611     // Return the version number of the current temporary for Key.
612     unsigned getCurrentTemporaryVersion(const void *Key) const {
613       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
614       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
615         return std::prev(UB)->first.second;
616       return 0;
617     }
618 
619     /// Allocate storage for an object of type T in this stack frame.
620     /// Populates LV with a handle to the created object. Key identifies
621     /// the temporary within the stack frame, and must not be reused without
622     /// bumping the temporary version number.
623     template<typename KeyT>
624     APValue &createTemporary(const KeyT *Key, QualType T,
625                              ScopeKind Scope, LValue &LV);
626 
627     /// Allocate storage for a parameter of a function call made in this frame.
628     APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
629 
630     void describe(llvm::raw_ostream &OS) override;
631 
632     Frame *getCaller() const override { return Caller; }
633     SourceLocation getCallLocation() const override { return CallLoc; }
634     const FunctionDecl *getCallee() const override { return Callee; }
635 
636     bool isStdFunction() const {
637       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
638         if (DC->isStdNamespace())
639           return true;
640       return false;
641     }
642 
643   private:
644     APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
645                          ScopeKind Scope);
646   };
647 
648   /// Temporarily override 'this'.
649   class ThisOverrideRAII {
650   public:
651     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
652         : Frame(Frame), OldThis(Frame.This) {
653       if (Enable)
654         Frame.This = NewThis;
655     }
656     ~ThisOverrideRAII() {
657       Frame.This = OldThis;
658     }
659   private:
660     CallStackFrame &Frame;
661     const LValue *OldThis;
662   };
663 }
664 
665 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
666                               const LValue &This, QualType ThisType);
667 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
668                               APValue::LValueBase LVBase, APValue &Value,
669                               QualType T);
670 
671 namespace {
672   /// A cleanup, and a flag indicating whether it is lifetime-extended.
673   class Cleanup {
674     llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
675     APValue::LValueBase Base;
676     QualType T;
677 
678   public:
679     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
680             ScopeKind Scope)
681         : Value(Val, Scope), Base(Base), T(T) {}
682 
683     /// Determine whether this cleanup should be performed at the end of the
684     /// given kind of scope.
685     bool isDestroyedAtEndOf(ScopeKind K) const {
686       return (int)Value.getInt() >= (int)K;
687     }
688     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
689       if (RunDestructors) {
690         SourceLocation Loc;
691         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
692           Loc = VD->getLocation();
693         else if (const Expr *E = Base.dyn_cast<const Expr*>())
694           Loc = E->getExprLoc();
695         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
696       }
697       *Value.getPointer() = APValue();
698       return true;
699     }
700 
701     bool hasSideEffect() {
702       return T.isDestructedType();
703     }
704   };
705 
706   /// A reference to an object whose construction we are currently evaluating.
707   struct ObjectUnderConstruction {
708     APValue::LValueBase Base;
709     ArrayRef<APValue::LValuePathEntry> Path;
710     friend bool operator==(const ObjectUnderConstruction &LHS,
711                            const ObjectUnderConstruction &RHS) {
712       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
713     }
714     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
715       return llvm::hash_combine(Obj.Base, Obj.Path);
716     }
717   };
718   enum class ConstructionPhase {
719     None,
720     Bases,
721     AfterBases,
722     AfterFields,
723     Destroying,
724     DestroyingBases
725   };
726 }
727 
728 namespace llvm {
729 template<> struct DenseMapInfo<ObjectUnderConstruction> {
730   using Base = DenseMapInfo<APValue::LValueBase>;
731   static ObjectUnderConstruction getEmptyKey() {
732     return {Base::getEmptyKey(), {}}; }
733   static ObjectUnderConstruction getTombstoneKey() {
734     return {Base::getTombstoneKey(), {}};
735   }
736   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
737     return hash_value(Object);
738   }
739   static bool isEqual(const ObjectUnderConstruction &LHS,
740                       const ObjectUnderConstruction &RHS) {
741     return LHS == RHS;
742   }
743 };
744 }
745 
746 namespace {
747   /// A dynamically-allocated heap object.
748   struct DynAlloc {
749     /// The value of this heap-allocated object.
750     APValue Value;
751     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
752     /// or a CallExpr (the latter is for direct calls to operator new inside
753     /// std::allocator<T>::allocate).
754     const Expr *AllocExpr = nullptr;
755 
756     enum Kind {
757       New,
758       ArrayNew,
759       StdAllocator
760     };
761 
762     /// Get the kind of the allocation. This must match between allocation
763     /// and deallocation.
764     Kind getKind() const {
765       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
766         return NE->isArray() ? ArrayNew : New;
767       assert(isa<CallExpr>(AllocExpr));
768       return StdAllocator;
769     }
770   };
771 
772   struct DynAllocOrder {
773     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
774       return L.getIndex() < R.getIndex();
775     }
776   };
777 
778   /// EvalInfo - This is a private struct used by the evaluator to capture
779   /// information about a subexpression as it is folded.  It retains information
780   /// about the AST context, but also maintains information about the folded
781   /// expression.
782   ///
783   /// If an expression could be evaluated, it is still possible it is not a C
784   /// "integer constant expression" or constant expression.  If not, this struct
785   /// captures information about how and why not.
786   ///
787   /// One bit of information passed *into* the request for constant folding
788   /// indicates whether the subexpression is "evaluated" or not according to C
789   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
790   /// evaluate the expression regardless of what the RHS is, but C only allows
791   /// certain things in certain situations.
792   class EvalInfo : public interp::State {
793   public:
794     ASTContext &Ctx;
795 
796     /// EvalStatus - Contains information about the evaluation.
797     Expr::EvalStatus &EvalStatus;
798 
799     /// CurrentCall - The top of the constexpr call stack.
800     CallStackFrame *CurrentCall;
801 
802     /// CallStackDepth - The number of calls in the call stack right now.
803     unsigned CallStackDepth;
804 
805     /// NextCallIndex - The next call index to assign.
806     unsigned NextCallIndex;
807 
808     /// StepsLeft - The remaining number of evaluation steps we're permitted
809     /// to perform. This is essentially a limit for the number of statements
810     /// we will evaluate.
811     unsigned StepsLeft;
812 
813     /// Enable the experimental new constant interpreter. If an expression is
814     /// not supported by the interpreter, an error is triggered.
815     bool EnableNewConstInterp;
816 
817     /// BottomFrame - The frame in which evaluation started. This must be
818     /// initialized after CurrentCall and CallStackDepth.
819     CallStackFrame BottomFrame;
820 
821     /// A stack of values whose lifetimes end at the end of some surrounding
822     /// evaluation frame.
823     llvm::SmallVector<Cleanup, 16> CleanupStack;
824 
825     /// EvaluatingDecl - This is the declaration whose initializer is being
826     /// evaluated, if any.
827     APValue::LValueBase EvaluatingDecl;
828 
829     enum class EvaluatingDeclKind {
830       None,
831       /// We're evaluating the construction of EvaluatingDecl.
832       Ctor,
833       /// We're evaluating the destruction of EvaluatingDecl.
834       Dtor,
835     };
836     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
837 
838     /// EvaluatingDeclValue - This is the value being constructed for the
839     /// declaration whose initializer is being evaluated, if any.
840     APValue *EvaluatingDeclValue;
841 
842     /// Set of objects that are currently being constructed.
843     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
844         ObjectsUnderConstruction;
845 
846     /// Current heap allocations, along with the location where each was
847     /// allocated. We use std::map here because we need stable addresses
848     /// for the stored APValues.
849     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
850 
851     /// The number of heap allocations performed so far in this evaluation.
852     unsigned NumHeapAllocs = 0;
853 
854     struct EvaluatingConstructorRAII {
855       EvalInfo &EI;
856       ObjectUnderConstruction Object;
857       bool DidInsert;
858       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
859                                 bool HasBases)
860           : EI(EI), Object(Object) {
861         DidInsert =
862             EI.ObjectsUnderConstruction
863                 .insert({Object, HasBases ? ConstructionPhase::Bases
864                                           : ConstructionPhase::AfterBases})
865                 .second;
866       }
867       void finishedConstructingBases() {
868         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
869       }
870       void finishedConstructingFields() {
871         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
872       }
873       ~EvaluatingConstructorRAII() {
874         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
875       }
876     };
877 
878     struct EvaluatingDestructorRAII {
879       EvalInfo &EI;
880       ObjectUnderConstruction Object;
881       bool DidInsert;
882       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
883           : EI(EI), Object(Object) {
884         DidInsert = EI.ObjectsUnderConstruction
885                         .insert({Object, ConstructionPhase::Destroying})
886                         .second;
887       }
888       void startedDestroyingBases() {
889         EI.ObjectsUnderConstruction[Object] =
890             ConstructionPhase::DestroyingBases;
891       }
892       ~EvaluatingDestructorRAII() {
893         if (DidInsert)
894           EI.ObjectsUnderConstruction.erase(Object);
895       }
896     };
897 
898     ConstructionPhase
899     isEvaluatingCtorDtor(APValue::LValueBase Base,
900                          ArrayRef<APValue::LValuePathEntry> Path) {
901       return ObjectsUnderConstruction.lookup({Base, Path});
902     }
903 
904     /// If we're currently speculatively evaluating, the outermost call stack
905     /// depth at which we can mutate state, otherwise 0.
906     unsigned SpeculativeEvaluationDepth = 0;
907 
908     /// The current array initialization index, if we're performing array
909     /// initialization.
910     uint64_t ArrayInitIndex = -1;
911 
912     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
913     /// notes attached to it will also be stored, otherwise they will not be.
914     bool HasActiveDiagnostic;
915 
916     /// Have we emitted a diagnostic explaining why we couldn't constant
917     /// fold (not just why it's not strictly a constant expression)?
918     bool HasFoldFailureDiagnostic;
919 
920     /// Whether or not we're in a context where the front end requires a
921     /// constant value.
922     bool InConstantContext;
923 
924     /// Whether we're checking that an expression is a potential constant
925     /// expression. If so, do not fail on constructs that could become constant
926     /// later on (such as a use of an undefined global).
927     bool CheckingPotentialConstantExpression = false;
928 
929     /// Whether we're checking for an expression that has undefined behavior.
930     /// If so, we will produce warnings if we encounter an operation that is
931     /// always undefined.
932     ///
933     /// Note that we still need to evaluate the expression normally when this
934     /// is set; this is used when evaluating ICEs in C.
935     bool CheckingForUndefinedBehavior = false;
936 
937     enum EvaluationMode {
938       /// Evaluate as a constant expression. Stop if we find that the expression
939       /// is not a constant expression.
940       EM_ConstantExpression,
941 
942       /// Evaluate as a constant expression. Stop if we find that the expression
943       /// is not a constant expression. Some expressions can be retried in the
944       /// optimizer if we don't constant fold them here, but in an unevaluated
945       /// context we try to fold them immediately since the optimizer never
946       /// gets a chance to look at it.
947       EM_ConstantExpressionUnevaluated,
948 
949       /// Fold the expression to a constant. Stop if we hit a side-effect that
950       /// we can't model.
951       EM_ConstantFold,
952 
953       /// Evaluate in any way we know how. Don't worry about side-effects that
954       /// can't be modeled.
955       EM_IgnoreSideEffects,
956     } EvalMode;
957 
958     /// Are we checking whether the expression is a potential constant
959     /// expression?
960     bool checkingPotentialConstantExpression() const override  {
961       return CheckingPotentialConstantExpression;
962     }
963 
964     /// Are we checking an expression for overflow?
965     // FIXME: We should check for any kind of undefined or suspicious behavior
966     // in such constructs, not just overflow.
967     bool checkingForUndefinedBehavior() const override {
968       return CheckingForUndefinedBehavior;
969     }
970 
971     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
972         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
973           CallStackDepth(0), NextCallIndex(1),
974           StepsLeft(C.getLangOpts().ConstexprStepLimit),
975           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
976           BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
977           EvaluatingDecl((const ValueDecl *)nullptr),
978           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
979           HasFoldFailureDiagnostic(false), InConstantContext(false),
980           EvalMode(Mode) {}
981 
982     ~EvalInfo() {
983       discardCleanups();
984     }
985 
986     ASTContext &getCtx() const override { return Ctx; }
987 
988     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
989                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
990       EvaluatingDecl = Base;
991       IsEvaluatingDecl = EDK;
992       EvaluatingDeclValue = &Value;
993     }
994 
995     bool CheckCallLimit(SourceLocation Loc) {
996       // Don't perform any constexpr calls (other than the call we're checking)
997       // when checking a potential constant expression.
998       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
999         return false;
1000       if (NextCallIndex == 0) {
1001         // NextCallIndex has wrapped around.
1002         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1003         return false;
1004       }
1005       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1006         return true;
1007       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1008         << getLangOpts().ConstexprCallDepth;
1009       return false;
1010     }
1011 
1012     std::pair<CallStackFrame *, unsigned>
1013     getCallFrameAndDepth(unsigned CallIndex) {
1014       assert(CallIndex && "no call index in getCallFrameAndDepth");
1015       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1016       // be null in this loop.
1017       unsigned Depth = CallStackDepth;
1018       CallStackFrame *Frame = CurrentCall;
1019       while (Frame->Index > CallIndex) {
1020         Frame = Frame->Caller;
1021         --Depth;
1022       }
1023       if (Frame->Index == CallIndex)
1024         return {Frame, Depth};
1025       return {nullptr, 0};
1026     }
1027 
1028     bool nextStep(const Stmt *S) {
1029       if (!StepsLeft) {
1030         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1031         return false;
1032       }
1033       --StepsLeft;
1034       return true;
1035     }
1036 
1037     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1038 
1039     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1040       Optional<DynAlloc*> Result;
1041       auto It = HeapAllocs.find(DA);
1042       if (It != HeapAllocs.end())
1043         Result = &It->second;
1044       return Result;
1045     }
1046 
1047     /// Get the allocated storage for the given parameter of the given call.
1048     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1049       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1050       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1051                    : nullptr;
1052     }
1053 
1054     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1055     struct StdAllocatorCaller {
1056       unsigned FrameIndex;
1057       QualType ElemType;
1058       explicit operator bool() const { return FrameIndex != 0; };
1059     };
1060 
1061     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1062       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1063            Call = Call->Caller) {
1064         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1065         if (!MD)
1066           continue;
1067         const IdentifierInfo *FnII = MD->getIdentifier();
1068         if (!FnII || !FnII->isStr(FnName))
1069           continue;
1070 
1071         const auto *CTSD =
1072             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1073         if (!CTSD)
1074           continue;
1075 
1076         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1077         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1078         if (CTSD->isInStdNamespace() && ClassII &&
1079             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1080             TAL[0].getKind() == TemplateArgument::Type)
1081           return {Call->Index, TAL[0].getAsType()};
1082       }
1083 
1084       return {};
1085     }
1086 
1087     void performLifetimeExtension() {
1088       // Disable the cleanups for lifetime-extended temporaries.
1089       llvm::erase_if(CleanupStack, [](Cleanup &C) {
1090         return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1091       });
1092     }
1093 
1094     /// Throw away any remaining cleanups at the end of evaluation. If any
1095     /// cleanups would have had a side-effect, note that as an unmodeled
1096     /// side-effect and return false. Otherwise, return true.
1097     bool discardCleanups() {
1098       for (Cleanup &C : CleanupStack) {
1099         if (C.hasSideEffect() && !noteSideEffect()) {
1100           CleanupStack.clear();
1101           return false;
1102         }
1103       }
1104       CleanupStack.clear();
1105       return true;
1106     }
1107 
1108   private:
1109     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1110     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1111 
1112     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1113     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1114 
1115     void setFoldFailureDiagnostic(bool Flag) override {
1116       HasFoldFailureDiagnostic = Flag;
1117     }
1118 
1119     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1120 
1121     // If we have a prior diagnostic, it will be noting that the expression
1122     // isn't a constant expression. This diagnostic is more important,
1123     // unless we require this evaluation to produce a constant expression.
1124     //
1125     // FIXME: We might want to show both diagnostics to the user in
1126     // EM_ConstantFold mode.
1127     bool hasPriorDiagnostic() override {
1128       if (!EvalStatus.Diag->empty()) {
1129         switch (EvalMode) {
1130         case EM_ConstantFold:
1131         case EM_IgnoreSideEffects:
1132           if (!HasFoldFailureDiagnostic)
1133             break;
1134           // We've already failed to fold something. Keep that diagnostic.
1135           LLVM_FALLTHROUGH;
1136         case EM_ConstantExpression:
1137         case EM_ConstantExpressionUnevaluated:
1138           setActiveDiagnostic(false);
1139           return true;
1140         }
1141       }
1142       return false;
1143     }
1144 
1145     unsigned getCallStackDepth() override { return CallStackDepth; }
1146 
1147   public:
1148     /// Should we continue evaluation after encountering a side-effect that we
1149     /// couldn't model?
1150     bool keepEvaluatingAfterSideEffect() {
1151       switch (EvalMode) {
1152       case EM_IgnoreSideEffects:
1153         return true;
1154 
1155       case EM_ConstantExpression:
1156       case EM_ConstantExpressionUnevaluated:
1157       case EM_ConstantFold:
1158         // By default, assume any side effect might be valid in some other
1159         // evaluation of this expression from a different context.
1160         return checkingPotentialConstantExpression() ||
1161                checkingForUndefinedBehavior();
1162       }
1163       llvm_unreachable("Missed EvalMode case");
1164     }
1165 
1166     /// Note that we have had a side-effect, and determine whether we should
1167     /// keep evaluating.
1168     bool noteSideEffect() {
1169       EvalStatus.HasSideEffects = true;
1170       return keepEvaluatingAfterSideEffect();
1171     }
1172 
1173     /// Should we continue evaluation after encountering undefined behavior?
1174     bool keepEvaluatingAfterUndefinedBehavior() {
1175       switch (EvalMode) {
1176       case EM_IgnoreSideEffects:
1177       case EM_ConstantFold:
1178         return true;
1179 
1180       case EM_ConstantExpression:
1181       case EM_ConstantExpressionUnevaluated:
1182         return checkingForUndefinedBehavior();
1183       }
1184       llvm_unreachable("Missed EvalMode case");
1185     }
1186 
1187     /// Note that we hit something that was technically undefined behavior, but
1188     /// that we can evaluate past it (such as signed overflow or floating-point
1189     /// division by zero.)
1190     bool noteUndefinedBehavior() override {
1191       EvalStatus.HasUndefinedBehavior = true;
1192       return keepEvaluatingAfterUndefinedBehavior();
1193     }
1194 
1195     /// Should we continue evaluation as much as possible after encountering a
1196     /// construct which can't be reduced to a value?
1197     bool keepEvaluatingAfterFailure() const override {
1198       if (!StepsLeft)
1199         return false;
1200 
1201       switch (EvalMode) {
1202       case EM_ConstantExpression:
1203       case EM_ConstantExpressionUnevaluated:
1204       case EM_ConstantFold:
1205       case EM_IgnoreSideEffects:
1206         return checkingPotentialConstantExpression() ||
1207                checkingForUndefinedBehavior();
1208       }
1209       llvm_unreachable("Missed EvalMode case");
1210     }
1211 
1212     /// Notes that we failed to evaluate an expression that other expressions
1213     /// directly depend on, and determine if we should keep evaluating. This
1214     /// should only be called if we actually intend to keep evaluating.
1215     ///
1216     /// Call noteSideEffect() instead if we may be able to ignore the value that
1217     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1218     ///
1219     /// (Foo(), 1)      // use noteSideEffect
1220     /// (Foo() || true) // use noteSideEffect
1221     /// Foo() + 1       // use noteFailure
1222     LLVM_NODISCARD bool noteFailure() {
1223       // Failure when evaluating some expression often means there is some
1224       // subexpression whose evaluation was skipped. Therefore, (because we
1225       // don't track whether we skipped an expression when unwinding after an
1226       // evaluation failure) every evaluation failure that bubbles up from a
1227       // subexpression implies that a side-effect has potentially happened. We
1228       // skip setting the HasSideEffects flag to true until we decide to
1229       // continue evaluating after that point, which happens here.
1230       bool KeepGoing = keepEvaluatingAfterFailure();
1231       EvalStatus.HasSideEffects |= KeepGoing;
1232       return KeepGoing;
1233     }
1234 
1235     class ArrayInitLoopIndex {
1236       EvalInfo &Info;
1237       uint64_t OuterIndex;
1238 
1239     public:
1240       ArrayInitLoopIndex(EvalInfo &Info)
1241           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1242         Info.ArrayInitIndex = 0;
1243       }
1244       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1245 
1246       operator uint64_t&() { return Info.ArrayInitIndex; }
1247     };
1248   };
1249 
1250   /// Object used to treat all foldable expressions as constant expressions.
1251   struct FoldConstant {
1252     EvalInfo &Info;
1253     bool Enabled;
1254     bool HadNoPriorDiags;
1255     EvalInfo::EvaluationMode OldMode;
1256 
1257     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1258       : Info(Info),
1259         Enabled(Enabled),
1260         HadNoPriorDiags(Info.EvalStatus.Diag &&
1261                         Info.EvalStatus.Diag->empty() &&
1262                         !Info.EvalStatus.HasSideEffects),
1263         OldMode(Info.EvalMode) {
1264       if (Enabled)
1265         Info.EvalMode = EvalInfo::EM_ConstantFold;
1266     }
1267     void keepDiagnostics() { Enabled = false; }
1268     ~FoldConstant() {
1269       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1270           !Info.EvalStatus.HasSideEffects)
1271         Info.EvalStatus.Diag->clear();
1272       Info.EvalMode = OldMode;
1273     }
1274   };
1275 
1276   /// RAII object used to set the current evaluation mode to ignore
1277   /// side-effects.
1278   struct IgnoreSideEffectsRAII {
1279     EvalInfo &Info;
1280     EvalInfo::EvaluationMode OldMode;
1281     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1282         : Info(Info), OldMode(Info.EvalMode) {
1283       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1284     }
1285 
1286     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1287   };
1288 
1289   /// RAII object used to optionally suppress diagnostics and side-effects from
1290   /// a speculative evaluation.
1291   class SpeculativeEvaluationRAII {
1292     EvalInfo *Info = nullptr;
1293     Expr::EvalStatus OldStatus;
1294     unsigned OldSpeculativeEvaluationDepth;
1295 
1296     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1297       Info = Other.Info;
1298       OldStatus = Other.OldStatus;
1299       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1300       Other.Info = nullptr;
1301     }
1302 
1303     void maybeRestoreState() {
1304       if (!Info)
1305         return;
1306 
1307       Info->EvalStatus = OldStatus;
1308       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1309     }
1310 
1311   public:
1312     SpeculativeEvaluationRAII() = default;
1313 
1314     SpeculativeEvaluationRAII(
1315         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1316         : Info(&Info), OldStatus(Info.EvalStatus),
1317           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1318       Info.EvalStatus.Diag = NewDiag;
1319       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1320     }
1321 
1322     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1323     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1324       moveFromAndCancel(std::move(Other));
1325     }
1326 
1327     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1328       maybeRestoreState();
1329       moveFromAndCancel(std::move(Other));
1330       return *this;
1331     }
1332 
1333     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1334   };
1335 
1336   /// RAII object wrapping a full-expression or block scope, and handling
1337   /// the ending of the lifetime of temporaries created within it.
1338   template<ScopeKind Kind>
1339   class ScopeRAII {
1340     EvalInfo &Info;
1341     unsigned OldStackSize;
1342   public:
1343     ScopeRAII(EvalInfo &Info)
1344         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1345       // Push a new temporary version. This is needed to distinguish between
1346       // temporaries created in different iterations of a loop.
1347       Info.CurrentCall->pushTempVersion();
1348     }
1349     bool destroy(bool RunDestructors = true) {
1350       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1351       OldStackSize = -1U;
1352       return OK;
1353     }
1354     ~ScopeRAII() {
1355       if (OldStackSize != -1U)
1356         destroy(false);
1357       // Body moved to a static method to encourage the compiler to inline away
1358       // instances of this class.
1359       Info.CurrentCall->popTempVersion();
1360     }
1361   private:
1362     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1363                         unsigned OldStackSize) {
1364       assert(OldStackSize <= Info.CleanupStack.size() &&
1365              "running cleanups out of order?");
1366 
1367       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1368       // for a full-expression scope.
1369       bool Success = true;
1370       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1371         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1372           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1373             Success = false;
1374             break;
1375           }
1376         }
1377       }
1378 
1379       // Compact any retained cleanups.
1380       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1381       if (Kind != ScopeKind::Block)
1382         NewEnd =
1383             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1384               return C.isDestroyedAtEndOf(Kind);
1385             });
1386       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1387       return Success;
1388     }
1389   };
1390   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1391   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1392   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1393 }
1394 
1395 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1396                                          CheckSubobjectKind CSK) {
1397   if (Invalid)
1398     return false;
1399   if (isOnePastTheEnd()) {
1400     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1401       << CSK;
1402     setInvalid();
1403     return false;
1404   }
1405   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1406   // must actually be at least one array element; even a VLA cannot have a
1407   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1408   return true;
1409 }
1410 
1411 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1412                                                                 const Expr *E) {
1413   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1414   // Do not set the designator as invalid: we can represent this situation,
1415   // and correct handling of __builtin_object_size requires us to do so.
1416 }
1417 
1418 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1419                                                     const Expr *E,
1420                                                     const APSInt &N) {
1421   // If we're complaining, we must be able to statically determine the size of
1422   // the most derived array.
1423   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1424     Info.CCEDiag(E, diag::note_constexpr_array_index)
1425       << N << /*array*/ 0
1426       << static_cast<unsigned>(getMostDerivedArraySize());
1427   else
1428     Info.CCEDiag(E, diag::note_constexpr_array_index)
1429       << N << /*non-array*/ 1;
1430   setInvalid();
1431 }
1432 
1433 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1434                                const FunctionDecl *Callee, const LValue *This,
1435                                CallRef Call)
1436     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1437       Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1438   Info.CurrentCall = this;
1439   ++Info.CallStackDepth;
1440 }
1441 
1442 CallStackFrame::~CallStackFrame() {
1443   assert(Info.CurrentCall == this && "calls retired out of order");
1444   --Info.CallStackDepth;
1445   Info.CurrentCall = Caller;
1446 }
1447 
1448 static bool isRead(AccessKinds AK) {
1449   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1450 }
1451 
1452 static bool isModification(AccessKinds AK) {
1453   switch (AK) {
1454   case AK_Read:
1455   case AK_ReadObjectRepresentation:
1456   case AK_MemberCall:
1457   case AK_DynamicCast:
1458   case AK_TypeId:
1459     return false;
1460   case AK_Assign:
1461   case AK_Increment:
1462   case AK_Decrement:
1463   case AK_Construct:
1464   case AK_Destroy:
1465     return true;
1466   }
1467   llvm_unreachable("unknown access kind");
1468 }
1469 
1470 static bool isAnyAccess(AccessKinds AK) {
1471   return isRead(AK) || isModification(AK);
1472 }
1473 
1474 /// Is this an access per the C++ definition?
1475 static bool isFormalAccess(AccessKinds AK) {
1476   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1477 }
1478 
1479 /// Is this kind of axcess valid on an indeterminate object value?
1480 static bool isValidIndeterminateAccess(AccessKinds AK) {
1481   switch (AK) {
1482   case AK_Read:
1483   case AK_Increment:
1484   case AK_Decrement:
1485     // These need the object's value.
1486     return false;
1487 
1488   case AK_ReadObjectRepresentation:
1489   case AK_Assign:
1490   case AK_Construct:
1491   case AK_Destroy:
1492     // Construction and destruction don't need the value.
1493     return true;
1494 
1495   case AK_MemberCall:
1496   case AK_DynamicCast:
1497   case AK_TypeId:
1498     // These aren't really meaningful on scalars.
1499     return true;
1500   }
1501   llvm_unreachable("unknown access kind");
1502 }
1503 
1504 namespace {
1505   struct ComplexValue {
1506   private:
1507     bool IsInt;
1508 
1509   public:
1510     APSInt IntReal, IntImag;
1511     APFloat FloatReal, FloatImag;
1512 
1513     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1514 
1515     void makeComplexFloat() { IsInt = false; }
1516     bool isComplexFloat() const { return !IsInt; }
1517     APFloat &getComplexFloatReal() { return FloatReal; }
1518     APFloat &getComplexFloatImag() { return FloatImag; }
1519 
1520     void makeComplexInt() { IsInt = true; }
1521     bool isComplexInt() const { return IsInt; }
1522     APSInt &getComplexIntReal() { return IntReal; }
1523     APSInt &getComplexIntImag() { return IntImag; }
1524 
1525     void moveInto(APValue &v) const {
1526       if (isComplexFloat())
1527         v = APValue(FloatReal, FloatImag);
1528       else
1529         v = APValue(IntReal, IntImag);
1530     }
1531     void setFrom(const APValue &v) {
1532       assert(v.isComplexFloat() || v.isComplexInt());
1533       if (v.isComplexFloat()) {
1534         makeComplexFloat();
1535         FloatReal = v.getComplexFloatReal();
1536         FloatImag = v.getComplexFloatImag();
1537       } else {
1538         makeComplexInt();
1539         IntReal = v.getComplexIntReal();
1540         IntImag = v.getComplexIntImag();
1541       }
1542     }
1543   };
1544 
1545   struct LValue {
1546     APValue::LValueBase Base;
1547     CharUnits Offset;
1548     SubobjectDesignator Designator;
1549     bool IsNullPtr : 1;
1550     bool InvalidBase : 1;
1551 
1552     const APValue::LValueBase getLValueBase() const { return Base; }
1553     CharUnits &getLValueOffset() { return Offset; }
1554     const CharUnits &getLValueOffset() const { return Offset; }
1555     SubobjectDesignator &getLValueDesignator() { return Designator; }
1556     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1557     bool isNullPointer() const { return IsNullPtr;}
1558 
1559     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1560     unsigned getLValueVersion() const { return Base.getVersion(); }
1561 
1562     void moveInto(APValue &V) const {
1563       if (Designator.Invalid)
1564         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1565       else {
1566         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1567         V = APValue(Base, Offset, Designator.Entries,
1568                     Designator.IsOnePastTheEnd, IsNullPtr);
1569       }
1570     }
1571     void setFrom(ASTContext &Ctx, const APValue &V) {
1572       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1573       Base = V.getLValueBase();
1574       Offset = V.getLValueOffset();
1575       InvalidBase = false;
1576       Designator = SubobjectDesignator(Ctx, V);
1577       IsNullPtr = V.isNullPointer();
1578     }
1579 
1580     void set(APValue::LValueBase B, bool BInvalid = false) {
1581 #ifndef NDEBUG
1582       // We only allow a few types of invalid bases. Enforce that here.
1583       if (BInvalid) {
1584         const auto *E = B.get<const Expr *>();
1585         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1586                "Unexpected type of invalid base");
1587       }
1588 #endif
1589 
1590       Base = B;
1591       Offset = CharUnits::fromQuantity(0);
1592       InvalidBase = BInvalid;
1593       Designator = SubobjectDesignator(getType(B));
1594       IsNullPtr = false;
1595     }
1596 
1597     void setNull(ASTContext &Ctx, QualType PointerTy) {
1598       Base = (const ValueDecl *)nullptr;
1599       Offset =
1600           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1601       InvalidBase = false;
1602       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1603       IsNullPtr = true;
1604     }
1605 
1606     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1607       set(B, true);
1608     }
1609 
1610     std::string toString(ASTContext &Ctx, QualType T) const {
1611       APValue Printable;
1612       moveInto(Printable);
1613       return Printable.getAsString(Ctx, T);
1614     }
1615 
1616   private:
1617     // Check that this LValue is not based on a null pointer. If it is, produce
1618     // a diagnostic and mark the designator as invalid.
1619     template <typename GenDiagType>
1620     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1621       if (Designator.Invalid)
1622         return false;
1623       if (IsNullPtr) {
1624         GenDiag();
1625         Designator.setInvalid();
1626         return false;
1627       }
1628       return true;
1629     }
1630 
1631   public:
1632     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1633                           CheckSubobjectKind CSK) {
1634       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1635         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1636       });
1637     }
1638 
1639     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1640                                        AccessKinds AK) {
1641       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1642         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1643       });
1644     }
1645 
1646     // Check this LValue refers to an object. If not, set the designator to be
1647     // invalid and emit a diagnostic.
1648     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1649       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1650              Designator.checkSubobject(Info, E, CSK);
1651     }
1652 
1653     void addDecl(EvalInfo &Info, const Expr *E,
1654                  const Decl *D, bool Virtual = false) {
1655       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1656         Designator.addDeclUnchecked(D, Virtual);
1657     }
1658     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1659       if (!Designator.Entries.empty()) {
1660         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1661         Designator.setInvalid();
1662         return;
1663       }
1664       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1665         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1666         Designator.FirstEntryIsAnUnsizedArray = true;
1667         Designator.addUnsizedArrayUnchecked(ElemTy);
1668       }
1669     }
1670     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1671       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1672         Designator.addArrayUnchecked(CAT);
1673     }
1674     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1675       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1676         Designator.addComplexUnchecked(EltTy, Imag);
1677     }
1678     void clearIsNullPointer() {
1679       IsNullPtr = false;
1680     }
1681     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1682                               const APSInt &Index, CharUnits ElementSize) {
1683       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1684       // but we're not required to diagnose it and it's valid in C++.)
1685       if (!Index)
1686         return;
1687 
1688       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1689       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1690       // offsets.
1691       uint64_t Offset64 = Offset.getQuantity();
1692       uint64_t ElemSize64 = ElementSize.getQuantity();
1693       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1694       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1695 
1696       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1697         Designator.adjustIndex(Info, E, Index);
1698       clearIsNullPointer();
1699     }
1700     void adjustOffset(CharUnits N) {
1701       Offset += N;
1702       if (N.getQuantity())
1703         clearIsNullPointer();
1704     }
1705   };
1706 
1707   struct MemberPtr {
1708     MemberPtr() {}
1709     explicit MemberPtr(const ValueDecl *Decl)
1710         : DeclAndIsDerivedMember(Decl, false) {}
1711 
1712     /// The member or (direct or indirect) field referred to by this member
1713     /// pointer, or 0 if this is a null member pointer.
1714     const ValueDecl *getDecl() const {
1715       return DeclAndIsDerivedMember.getPointer();
1716     }
1717     /// Is this actually a member of some type derived from the relevant class?
1718     bool isDerivedMember() const {
1719       return DeclAndIsDerivedMember.getInt();
1720     }
1721     /// Get the class which the declaration actually lives in.
1722     const CXXRecordDecl *getContainingRecord() const {
1723       return cast<CXXRecordDecl>(
1724           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1725     }
1726 
1727     void moveInto(APValue &V) const {
1728       V = APValue(getDecl(), isDerivedMember(), Path);
1729     }
1730     void setFrom(const APValue &V) {
1731       assert(V.isMemberPointer());
1732       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1733       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1734       Path.clear();
1735       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1736       Path.insert(Path.end(), P.begin(), P.end());
1737     }
1738 
1739     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1740     /// whether the member is a member of some class derived from the class type
1741     /// of the member pointer.
1742     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1743     /// Path - The path of base/derived classes from the member declaration's
1744     /// class (exclusive) to the class type of the member pointer (inclusive).
1745     SmallVector<const CXXRecordDecl*, 4> Path;
1746 
1747     /// Perform a cast towards the class of the Decl (either up or down the
1748     /// hierarchy).
1749     bool castBack(const CXXRecordDecl *Class) {
1750       assert(!Path.empty());
1751       const CXXRecordDecl *Expected;
1752       if (Path.size() >= 2)
1753         Expected = Path[Path.size() - 2];
1754       else
1755         Expected = getContainingRecord();
1756       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1757         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1758         // if B does not contain the original member and is not a base or
1759         // derived class of the class containing the original member, the result
1760         // of the cast is undefined.
1761         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1762         // (D::*). We consider that to be a language defect.
1763         return false;
1764       }
1765       Path.pop_back();
1766       return true;
1767     }
1768     /// Perform a base-to-derived member pointer cast.
1769     bool castToDerived(const CXXRecordDecl *Derived) {
1770       if (!getDecl())
1771         return true;
1772       if (!isDerivedMember()) {
1773         Path.push_back(Derived);
1774         return true;
1775       }
1776       if (!castBack(Derived))
1777         return false;
1778       if (Path.empty())
1779         DeclAndIsDerivedMember.setInt(false);
1780       return true;
1781     }
1782     /// Perform a derived-to-base member pointer cast.
1783     bool castToBase(const CXXRecordDecl *Base) {
1784       if (!getDecl())
1785         return true;
1786       if (Path.empty())
1787         DeclAndIsDerivedMember.setInt(true);
1788       if (isDerivedMember()) {
1789         Path.push_back(Base);
1790         return true;
1791       }
1792       return castBack(Base);
1793     }
1794   };
1795 
1796   /// Compare two member pointers, which are assumed to be of the same type.
1797   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1798     if (!LHS.getDecl() || !RHS.getDecl())
1799       return !LHS.getDecl() && !RHS.getDecl();
1800     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1801       return false;
1802     return LHS.Path == RHS.Path;
1803   }
1804 }
1805 
1806 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1807 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1808                             const LValue &This, const Expr *E,
1809                             bool AllowNonLiteralTypes = false);
1810 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1811                            bool InvalidBaseOK = false);
1812 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1813                             bool InvalidBaseOK = false);
1814 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1815                                   EvalInfo &Info);
1816 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1817 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1818 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1819                                     EvalInfo &Info);
1820 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1821 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1822 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1823                            EvalInfo &Info);
1824 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1825 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1826                                   EvalInfo &Info);
1827 
1828 /// Evaluate an integer or fixed point expression into an APResult.
1829 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1830                                         EvalInfo &Info);
1831 
1832 /// Evaluate only a fixed point expression into an APResult.
1833 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1834                                EvalInfo &Info);
1835 
1836 //===----------------------------------------------------------------------===//
1837 // Misc utilities
1838 //===----------------------------------------------------------------------===//
1839 
1840 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1841 /// preserving its value (by extending by up to one bit as needed).
1842 static void negateAsSigned(APSInt &Int) {
1843   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1844     Int = Int.extend(Int.getBitWidth() + 1);
1845     Int.setIsSigned(true);
1846   }
1847   Int = -Int;
1848 }
1849 
1850 template<typename KeyT>
1851 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1852                                          ScopeKind Scope, LValue &LV) {
1853   unsigned Version = getTempVersion();
1854   APValue::LValueBase Base(Key, Index, Version);
1855   LV.set(Base);
1856   return createLocal(Base, Key, T, Scope);
1857 }
1858 
1859 /// Allocate storage for a parameter of a function call made in this frame.
1860 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1861                                      LValue &LV) {
1862   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1863   APValue::LValueBase Base(PVD, Index, Args.Version);
1864   LV.set(Base);
1865   // We always destroy parameters at the end of the call, even if we'd allow
1866   // them to live to the end of the full-expression at runtime, in order to
1867   // give portable results and match other compilers.
1868   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1869 }
1870 
1871 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1872                                      QualType T, ScopeKind Scope) {
1873   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1874   unsigned Version = Base.getVersion();
1875   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1876   assert(Result.isAbsent() && "local created multiple times");
1877 
1878   // If we're creating a local immediately in the operand of a speculative
1879   // evaluation, don't register a cleanup to be run outside the speculative
1880   // evaluation context, since we won't actually be able to initialize this
1881   // object.
1882   if (Index <= Info.SpeculativeEvaluationDepth) {
1883     if (T.isDestructedType())
1884       Info.noteSideEffect();
1885   } else {
1886     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1887   }
1888   return Result;
1889 }
1890 
1891 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1892   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1893     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1894     return nullptr;
1895   }
1896 
1897   DynamicAllocLValue DA(NumHeapAllocs++);
1898   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1899   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1900                                    std::forward_as_tuple(DA), std::tuple<>());
1901   assert(Result.second && "reused a heap alloc index?");
1902   Result.first->second.AllocExpr = E;
1903   return &Result.first->second.Value;
1904 }
1905 
1906 /// Produce a string describing the given constexpr call.
1907 void CallStackFrame::describe(raw_ostream &Out) {
1908   unsigned ArgIndex = 0;
1909   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1910                       !isa<CXXConstructorDecl>(Callee) &&
1911                       cast<CXXMethodDecl>(Callee)->isInstance();
1912 
1913   if (!IsMemberCall)
1914     Out << *Callee << '(';
1915 
1916   if (This && IsMemberCall) {
1917     APValue Val;
1918     This->moveInto(Val);
1919     Val.printPretty(Out, Info.Ctx,
1920                     This->Designator.MostDerivedType);
1921     // FIXME: Add parens around Val if needed.
1922     Out << "->" << *Callee << '(';
1923     IsMemberCall = false;
1924   }
1925 
1926   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1927        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1928     if (ArgIndex > (unsigned)IsMemberCall)
1929       Out << ", ";
1930 
1931     const ParmVarDecl *Param = *I;
1932     APValue *V = Info.getParamSlot(Arguments, Param);
1933     if (V)
1934       V->printPretty(Out, Info.Ctx, Param->getType());
1935     else
1936       Out << "<...>";
1937 
1938     if (ArgIndex == 0 && IsMemberCall)
1939       Out << "->" << *Callee << '(';
1940   }
1941 
1942   Out << ')';
1943 }
1944 
1945 /// Evaluate an expression to see if it had side-effects, and discard its
1946 /// result.
1947 /// \return \c true if the caller should keep evaluating.
1948 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1949   assert(!E->isValueDependent());
1950   APValue Scratch;
1951   if (!Evaluate(Scratch, Info, E))
1952     // We don't need the value, but we might have skipped a side effect here.
1953     return Info.noteSideEffect();
1954   return true;
1955 }
1956 
1957 /// Should this call expression be treated as a constant?
1958 static bool IsConstantCall(const CallExpr *E) {
1959   unsigned Builtin = E->getBuiltinCallee();
1960   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1961           Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1962           Builtin == Builtin::BI__builtin_function_start);
1963 }
1964 
1965 static bool IsGlobalLValue(APValue::LValueBase B) {
1966   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1967   // constant expression of pointer type that evaluates to...
1968 
1969   // ... a null pointer value, or a prvalue core constant expression of type
1970   // std::nullptr_t.
1971   if (!B) return true;
1972 
1973   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1974     // ... the address of an object with static storage duration,
1975     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1976       return VD->hasGlobalStorage();
1977     if (isa<TemplateParamObjectDecl>(D))
1978       return true;
1979     // ... the address of a function,
1980     // ... the address of a GUID [MS extension],
1981     return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D);
1982   }
1983 
1984   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1985     return true;
1986 
1987   const Expr *E = B.get<const Expr*>();
1988   switch (E->getStmtClass()) {
1989   default:
1990     return false;
1991   case Expr::CompoundLiteralExprClass: {
1992     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1993     return CLE->isFileScope() && CLE->isLValue();
1994   }
1995   case Expr::MaterializeTemporaryExprClass:
1996     // A materialized temporary might have been lifetime-extended to static
1997     // storage duration.
1998     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1999   // A string literal has static storage duration.
2000   case Expr::StringLiteralClass:
2001   case Expr::PredefinedExprClass:
2002   case Expr::ObjCStringLiteralClass:
2003   case Expr::ObjCEncodeExprClass:
2004     return true;
2005   case Expr::ObjCBoxedExprClass:
2006     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2007   case Expr::CallExprClass:
2008     return IsConstantCall(cast<CallExpr>(E));
2009   // For GCC compatibility, &&label has static storage duration.
2010   case Expr::AddrLabelExprClass:
2011     return true;
2012   // A Block literal expression may be used as the initialization value for
2013   // Block variables at global or local static scope.
2014   case Expr::BlockExprClass:
2015     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2016   case Expr::ImplicitValueInitExprClass:
2017     // FIXME:
2018     // We can never form an lvalue with an implicit value initialization as its
2019     // base through expression evaluation, so these only appear in one case: the
2020     // implicit variable declaration we invent when checking whether a constexpr
2021     // constructor can produce a constant expression. We must assume that such
2022     // an expression might be a global lvalue.
2023     return true;
2024   }
2025 }
2026 
2027 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2028   return LVal.Base.dyn_cast<const ValueDecl*>();
2029 }
2030 
2031 static bool IsLiteralLValue(const LValue &Value) {
2032   if (Value.getLValueCallIndex())
2033     return false;
2034   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2035   return E && !isa<MaterializeTemporaryExpr>(E);
2036 }
2037 
2038 static bool IsWeakLValue(const LValue &Value) {
2039   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2040   return Decl && Decl->isWeak();
2041 }
2042 
2043 static bool isZeroSized(const LValue &Value) {
2044   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2045   if (Decl && isa<VarDecl>(Decl)) {
2046     QualType Ty = Decl->getType();
2047     if (Ty->isArrayType())
2048       return Ty->isIncompleteType() ||
2049              Decl->getASTContext().getTypeSize(Ty) == 0;
2050   }
2051   return false;
2052 }
2053 
2054 static bool HasSameBase(const LValue &A, const LValue &B) {
2055   if (!A.getLValueBase())
2056     return !B.getLValueBase();
2057   if (!B.getLValueBase())
2058     return false;
2059 
2060   if (A.getLValueBase().getOpaqueValue() !=
2061       B.getLValueBase().getOpaqueValue())
2062     return false;
2063 
2064   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2065          A.getLValueVersion() == B.getLValueVersion();
2066 }
2067 
2068 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2069   assert(Base && "no location for a null lvalue");
2070   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2071 
2072   // For a parameter, find the corresponding call stack frame (if it still
2073   // exists), and point at the parameter of the function definition we actually
2074   // invoked.
2075   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2076     unsigned Idx = PVD->getFunctionScopeIndex();
2077     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2078       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2079           F->Arguments.Version == Base.getVersion() && F->Callee &&
2080           Idx < F->Callee->getNumParams()) {
2081         VD = F->Callee->getParamDecl(Idx);
2082         break;
2083       }
2084     }
2085   }
2086 
2087   if (VD)
2088     Info.Note(VD->getLocation(), diag::note_declared_at);
2089   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2090     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2091   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2092     // FIXME: Produce a note for dangling pointers too.
2093     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2094       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2095                 diag::note_constexpr_dynamic_alloc_here);
2096   }
2097   // We have no information to show for a typeid(T) object.
2098 }
2099 
2100 enum class CheckEvaluationResultKind {
2101   ConstantExpression,
2102   FullyInitialized,
2103 };
2104 
2105 /// Materialized temporaries that we've already checked to determine if they're
2106 /// initializsed by a constant expression.
2107 using CheckedTemporaries =
2108     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2109 
2110 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2111                                   EvalInfo &Info, SourceLocation DiagLoc,
2112                                   QualType Type, const APValue &Value,
2113                                   ConstantExprKind Kind,
2114                                   SourceLocation SubobjectLoc,
2115                                   CheckedTemporaries &CheckedTemps);
2116 
2117 /// Check that this reference or pointer core constant expression is a valid
2118 /// value for an address or reference constant expression. Return true if we
2119 /// can fold this expression, whether or not it's a constant expression.
2120 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2121                                           QualType Type, const LValue &LVal,
2122                                           ConstantExprKind Kind,
2123                                           CheckedTemporaries &CheckedTemps) {
2124   bool IsReferenceType = Type->isReferenceType();
2125 
2126   APValue::LValueBase Base = LVal.getLValueBase();
2127   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2128 
2129   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2130   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2131 
2132   // Additional restrictions apply in a template argument. We only enforce the
2133   // C++20 restrictions here; additional syntactic and semantic restrictions
2134   // are applied elsewhere.
2135   if (isTemplateArgument(Kind)) {
2136     int InvalidBaseKind = -1;
2137     StringRef Ident;
2138     if (Base.is<TypeInfoLValue>())
2139       InvalidBaseKind = 0;
2140     else if (isa_and_nonnull<StringLiteral>(BaseE))
2141       InvalidBaseKind = 1;
2142     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2143              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2144       InvalidBaseKind = 2;
2145     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2146       InvalidBaseKind = 3;
2147       Ident = PE->getIdentKindName();
2148     }
2149 
2150     if (InvalidBaseKind != -1) {
2151       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2152           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2153           << Ident;
2154       return false;
2155     }
2156   }
2157 
2158   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2159     if (FD->isConsteval()) {
2160       Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2161           << !Type->isAnyPointerType();
2162       Info.Note(FD->getLocation(), diag::note_declared_at);
2163       return false;
2164     }
2165   }
2166 
2167   // Check that the object is a global. Note that the fake 'this' object we
2168   // manufacture when checking potential constant expressions is conservatively
2169   // assumed to be global here.
2170   if (!IsGlobalLValue(Base)) {
2171     if (Info.getLangOpts().CPlusPlus11) {
2172       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2173       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2174         << IsReferenceType << !Designator.Entries.empty()
2175         << !!VD << VD;
2176 
2177       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2178       if (VarD && VarD->isConstexpr()) {
2179         // Non-static local constexpr variables have unintuitive semantics:
2180         //   constexpr int a = 1;
2181         //   constexpr const int *p = &a;
2182         // ... is invalid because the address of 'a' is not constant. Suggest
2183         // adding a 'static' in this case.
2184         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2185             << VarD
2186             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2187       } else {
2188         NoteLValueLocation(Info, Base);
2189       }
2190     } else {
2191       Info.FFDiag(Loc);
2192     }
2193     // Don't allow references to temporaries to escape.
2194     return false;
2195   }
2196   assert((Info.checkingPotentialConstantExpression() ||
2197           LVal.getLValueCallIndex() == 0) &&
2198          "have call index for global lvalue");
2199 
2200   if (Base.is<DynamicAllocLValue>()) {
2201     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2202         << IsReferenceType << !Designator.Entries.empty();
2203     NoteLValueLocation(Info, Base);
2204     return false;
2205   }
2206 
2207   if (BaseVD) {
2208     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2209       // Check if this is a thread-local variable.
2210       if (Var->getTLSKind())
2211         // FIXME: Diagnostic!
2212         return false;
2213 
2214       // A dllimport variable never acts like a constant, unless we're
2215       // evaluating a value for use only in name mangling.
2216       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2217         // FIXME: Diagnostic!
2218         return false;
2219 
2220       // In CUDA/HIP device compilation, only device side variables have
2221       // constant addresses.
2222       if (Info.getCtx().getLangOpts().CUDA &&
2223           Info.getCtx().getLangOpts().CUDAIsDevice &&
2224           Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2225         if ((!Var->hasAttr<CUDADeviceAttr>() &&
2226              !Var->hasAttr<CUDAConstantAttr>() &&
2227              !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2228              !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2229             Var->hasAttr<HIPManagedAttr>())
2230           return false;
2231       }
2232     }
2233     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2234       // __declspec(dllimport) must be handled very carefully:
2235       // We must never initialize an expression with the thunk in C++.
2236       // Doing otherwise would allow the same id-expression to yield
2237       // different addresses for the same function in different translation
2238       // units.  However, this means that we must dynamically initialize the
2239       // expression with the contents of the import address table at runtime.
2240       //
2241       // The C language has no notion of ODR; furthermore, it has no notion of
2242       // dynamic initialization.  This means that we are permitted to
2243       // perform initialization with the address of the thunk.
2244       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2245           FD->hasAttr<DLLImportAttr>())
2246         // FIXME: Diagnostic!
2247         return false;
2248     }
2249   } else if (const auto *MTE =
2250                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2251     if (CheckedTemps.insert(MTE).second) {
2252       QualType TempType = getType(Base);
2253       if (TempType.isDestructedType()) {
2254         Info.FFDiag(MTE->getExprLoc(),
2255                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2256             << TempType;
2257         return false;
2258       }
2259 
2260       APValue *V = MTE->getOrCreateValue(false);
2261       assert(V && "evasluation result refers to uninitialised temporary");
2262       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2263                                  Info, MTE->getExprLoc(), TempType, *V,
2264                                  Kind, SourceLocation(), CheckedTemps))
2265         return false;
2266     }
2267   }
2268 
2269   // Allow address constant expressions to be past-the-end pointers. This is
2270   // an extension: the standard requires them to point to an object.
2271   if (!IsReferenceType)
2272     return true;
2273 
2274   // A reference constant expression must refer to an object.
2275   if (!Base) {
2276     // FIXME: diagnostic
2277     Info.CCEDiag(Loc);
2278     return true;
2279   }
2280 
2281   // Does this refer one past the end of some object?
2282   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2283     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2284       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2285     NoteLValueLocation(Info, Base);
2286   }
2287 
2288   return true;
2289 }
2290 
2291 /// Member pointers are constant expressions unless they point to a
2292 /// non-virtual dllimport member function.
2293 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2294                                                  SourceLocation Loc,
2295                                                  QualType Type,
2296                                                  const APValue &Value,
2297                                                  ConstantExprKind Kind) {
2298   const ValueDecl *Member = Value.getMemberPointerDecl();
2299   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2300   if (!FD)
2301     return true;
2302   if (FD->isConsteval()) {
2303     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2304     Info.Note(FD->getLocation(), diag::note_declared_at);
2305     return false;
2306   }
2307   return isForManglingOnly(Kind) || FD->isVirtual() ||
2308          !FD->hasAttr<DLLImportAttr>();
2309 }
2310 
2311 /// Check that this core constant expression is of literal type, and if not,
2312 /// produce an appropriate diagnostic.
2313 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2314                              const LValue *This = nullptr) {
2315   if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2316     return true;
2317 
2318   // C++1y: A constant initializer for an object o [...] may also invoke
2319   // constexpr constructors for o and its subobjects even if those objects
2320   // are of non-literal class types.
2321   //
2322   // C++11 missed this detail for aggregates, so classes like this:
2323   //   struct foo_t { union { int i; volatile int j; } u; };
2324   // are not (obviously) initializable like so:
2325   //   __attribute__((__require_constant_initialization__))
2326   //   static const foo_t x = {{0}};
2327   // because "i" is a subobject with non-literal initialization (due to the
2328   // volatile member of the union). See:
2329   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2330   // Therefore, we use the C++1y behavior.
2331   if (This && Info.EvaluatingDecl == This->getLValueBase())
2332     return true;
2333 
2334   // Prvalue constant expressions must be of literal types.
2335   if (Info.getLangOpts().CPlusPlus11)
2336     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2337       << E->getType();
2338   else
2339     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2340   return false;
2341 }
2342 
2343 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2344                                   EvalInfo &Info, SourceLocation DiagLoc,
2345                                   QualType Type, const APValue &Value,
2346                                   ConstantExprKind Kind,
2347                                   SourceLocation SubobjectLoc,
2348                                   CheckedTemporaries &CheckedTemps) {
2349   if (!Value.hasValue()) {
2350     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2351       << true << Type;
2352     if (SubobjectLoc.isValid())
2353       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2354     return false;
2355   }
2356 
2357   // We allow _Atomic(T) to be initialized from anything that T can be
2358   // initialized from.
2359   if (const AtomicType *AT = Type->getAs<AtomicType>())
2360     Type = AT->getValueType();
2361 
2362   // Core issue 1454: For a literal constant expression of array or class type,
2363   // each subobject of its value shall have been initialized by a constant
2364   // expression.
2365   if (Value.isArray()) {
2366     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2367     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2368       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2369                                  Value.getArrayInitializedElt(I), Kind,
2370                                  SubobjectLoc, CheckedTemps))
2371         return false;
2372     }
2373     if (!Value.hasArrayFiller())
2374       return true;
2375     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2376                                  Value.getArrayFiller(), Kind, SubobjectLoc,
2377                                  CheckedTemps);
2378   }
2379   if (Value.isUnion() && Value.getUnionField()) {
2380     return CheckEvaluationResult(
2381         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2382         Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2383         CheckedTemps);
2384   }
2385   if (Value.isStruct()) {
2386     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2387     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2388       unsigned BaseIndex = 0;
2389       for (const CXXBaseSpecifier &BS : CD->bases()) {
2390         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2391                                    Value.getStructBase(BaseIndex), Kind,
2392                                    BS.getBeginLoc(), CheckedTemps))
2393           return false;
2394         ++BaseIndex;
2395       }
2396     }
2397     for (const auto *I : RD->fields()) {
2398       if (I->isUnnamedBitfield())
2399         continue;
2400 
2401       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2402                                  Value.getStructField(I->getFieldIndex()),
2403                                  Kind, I->getLocation(), CheckedTemps))
2404         return false;
2405     }
2406   }
2407 
2408   if (Value.isLValue() &&
2409       CERK == CheckEvaluationResultKind::ConstantExpression) {
2410     LValue LVal;
2411     LVal.setFrom(Info.Ctx, Value);
2412     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2413                                          CheckedTemps);
2414   }
2415 
2416   if (Value.isMemberPointer() &&
2417       CERK == CheckEvaluationResultKind::ConstantExpression)
2418     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2419 
2420   // Everything else is fine.
2421   return true;
2422 }
2423 
2424 /// Check that this core constant expression value is a valid value for a
2425 /// constant expression. If not, report an appropriate diagnostic. Does not
2426 /// check that the expression is of literal type.
2427 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2428                                     QualType Type, const APValue &Value,
2429                                     ConstantExprKind Kind) {
2430   // Nothing to check for a constant expression of type 'cv void'.
2431   if (Type->isVoidType())
2432     return true;
2433 
2434   CheckedTemporaries CheckedTemps;
2435   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2436                                Info, DiagLoc, Type, Value, Kind,
2437                                SourceLocation(), CheckedTemps);
2438 }
2439 
2440 /// Check that this evaluated value is fully-initialized and can be loaded by
2441 /// an lvalue-to-rvalue conversion.
2442 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2443                                   QualType Type, const APValue &Value) {
2444   CheckedTemporaries CheckedTemps;
2445   return CheckEvaluationResult(
2446       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2447       ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2448 }
2449 
2450 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2451 /// "the allocated storage is deallocated within the evaluation".
2452 static bool CheckMemoryLeaks(EvalInfo &Info) {
2453   if (!Info.HeapAllocs.empty()) {
2454     // We can still fold to a constant despite a compile-time memory leak,
2455     // so long as the heap allocation isn't referenced in the result (we check
2456     // that in CheckConstantExpression).
2457     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2458                  diag::note_constexpr_memory_leak)
2459         << unsigned(Info.HeapAllocs.size() - 1);
2460   }
2461   return true;
2462 }
2463 
2464 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2465   // A null base expression indicates a null pointer.  These are always
2466   // evaluatable, and they are false unless the offset is zero.
2467   if (!Value.getLValueBase()) {
2468     Result = !Value.getLValueOffset().isZero();
2469     return true;
2470   }
2471 
2472   // We have a non-null base.  These are generally known to be true, but if it's
2473   // a weak declaration it can be null at runtime.
2474   Result = true;
2475   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2476   return !Decl || !Decl->isWeak();
2477 }
2478 
2479 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2480   switch (Val.getKind()) {
2481   case APValue::None:
2482   case APValue::Indeterminate:
2483     return false;
2484   case APValue::Int:
2485     Result = Val.getInt().getBoolValue();
2486     return true;
2487   case APValue::FixedPoint:
2488     Result = Val.getFixedPoint().getBoolValue();
2489     return true;
2490   case APValue::Float:
2491     Result = !Val.getFloat().isZero();
2492     return true;
2493   case APValue::ComplexInt:
2494     Result = Val.getComplexIntReal().getBoolValue() ||
2495              Val.getComplexIntImag().getBoolValue();
2496     return true;
2497   case APValue::ComplexFloat:
2498     Result = !Val.getComplexFloatReal().isZero() ||
2499              !Val.getComplexFloatImag().isZero();
2500     return true;
2501   case APValue::LValue:
2502     return EvalPointerValueAsBool(Val, Result);
2503   case APValue::MemberPointer:
2504     Result = Val.getMemberPointerDecl();
2505     return true;
2506   case APValue::Vector:
2507   case APValue::Array:
2508   case APValue::Struct:
2509   case APValue::Union:
2510   case APValue::AddrLabelDiff:
2511     return false;
2512   }
2513 
2514   llvm_unreachable("unknown APValue kind");
2515 }
2516 
2517 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2518                                        EvalInfo &Info) {
2519   assert(!E->isValueDependent());
2520   assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2521   APValue Val;
2522   if (!Evaluate(Val, Info, E))
2523     return false;
2524   return HandleConversionToBool(Val, Result);
2525 }
2526 
2527 template<typename T>
2528 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2529                            const T &SrcValue, QualType DestType) {
2530   Info.CCEDiag(E, diag::note_constexpr_overflow)
2531     << SrcValue << DestType;
2532   return Info.noteUndefinedBehavior();
2533 }
2534 
2535 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2536                                  QualType SrcType, const APFloat &Value,
2537                                  QualType DestType, APSInt &Result) {
2538   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2539   // Determine whether we are converting to unsigned or signed.
2540   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2541 
2542   Result = APSInt(DestWidth, !DestSigned);
2543   bool ignored;
2544   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2545       & APFloat::opInvalidOp)
2546     return HandleOverflow(Info, E, Value, DestType);
2547   return true;
2548 }
2549 
2550 /// Get rounding mode used for evaluation of the specified expression.
2551 /// \param[out] DynamicRM Is set to true is the requested rounding mode is
2552 ///                       dynamic.
2553 /// If rounding mode is unknown at compile time, still try to evaluate the
2554 /// expression. If the result is exact, it does not depend on rounding mode.
2555 /// So return "tonearest" mode instead of "dynamic".
2556 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
2557                                                 bool &DynamicRM) {
2558   llvm::RoundingMode RM =
2559       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2560   DynamicRM = (RM == llvm::RoundingMode::Dynamic);
2561   if (DynamicRM)
2562     RM = llvm::RoundingMode::NearestTiesToEven;
2563   return RM;
2564 }
2565 
2566 /// Check if the given evaluation result is allowed for constant evaluation.
2567 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2568                                      APFloat::opStatus St) {
2569   // In a constant context, assume that any dynamic rounding mode or FP
2570   // exception state matches the default floating-point environment.
2571   if (Info.InConstantContext)
2572     return true;
2573 
2574   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2575   if ((St & APFloat::opInexact) &&
2576       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2577     // Inexact result means that it depends on rounding mode. If the requested
2578     // mode is dynamic, the evaluation cannot be made in compile time.
2579     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2580     return false;
2581   }
2582 
2583   if ((St != APFloat::opOK) &&
2584       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2585        FPO.getFPExceptionMode() != LangOptions::FPE_Ignore ||
2586        FPO.getAllowFEnvAccess())) {
2587     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2588     return false;
2589   }
2590 
2591   if ((St & APFloat::opStatus::opInvalidOp) &&
2592       FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) {
2593     // There is no usefully definable result.
2594     Info.FFDiag(E);
2595     return false;
2596   }
2597 
2598   // FIXME: if:
2599   // - evaluation triggered other FP exception, and
2600   // - exception mode is not "ignore", and
2601   // - the expression being evaluated is not a part of global variable
2602   //   initializer,
2603   // the evaluation probably need to be rejected.
2604   return true;
2605 }
2606 
2607 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2608                                    QualType SrcType, QualType DestType,
2609                                    APFloat &Result) {
2610   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2611   bool DynamicRM;
2612   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2613   APFloat::opStatus St;
2614   APFloat Value = Result;
2615   bool ignored;
2616   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2617   return checkFloatingPointResult(Info, E, St);
2618 }
2619 
2620 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2621                                  QualType DestType, QualType SrcType,
2622                                  const APSInt &Value) {
2623   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2624   // Figure out if this is a truncate, extend or noop cast.
2625   // If the input is signed, do a sign extend, noop, or truncate.
2626   APSInt Result = Value.extOrTrunc(DestWidth);
2627   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2628   if (DestType->isBooleanType())
2629     Result = Value.getBoolValue();
2630   return Result;
2631 }
2632 
2633 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2634                                  const FPOptions FPO,
2635                                  QualType SrcType, const APSInt &Value,
2636                                  QualType DestType, APFloat &Result) {
2637   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2638   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2639        APFloat::rmNearestTiesToEven);
2640   if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
2641       FPO.isFPConstrained()) {
2642     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2643     return false;
2644   }
2645   return true;
2646 }
2647 
2648 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2649                                   APValue &Value, const FieldDecl *FD) {
2650   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2651 
2652   if (!Value.isInt()) {
2653     // Trying to store a pointer-cast-to-integer into a bitfield.
2654     // FIXME: In this case, we should provide the diagnostic for casting
2655     // a pointer to an integer.
2656     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2657     Info.FFDiag(E);
2658     return false;
2659   }
2660 
2661   APSInt &Int = Value.getInt();
2662   unsigned OldBitWidth = Int.getBitWidth();
2663   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2664   if (NewBitWidth < OldBitWidth)
2665     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2666   return true;
2667 }
2668 
2669 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2670                                   llvm::APInt &Res) {
2671   APValue SVal;
2672   if (!Evaluate(SVal, Info, E))
2673     return false;
2674   if (SVal.isInt()) {
2675     Res = SVal.getInt();
2676     return true;
2677   }
2678   if (SVal.isFloat()) {
2679     Res = SVal.getFloat().bitcastToAPInt();
2680     return true;
2681   }
2682   if (SVal.isVector()) {
2683     QualType VecTy = E->getType();
2684     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2685     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2686     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2687     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2688     Res = llvm::APInt::getZero(VecSize);
2689     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2690       APValue &Elt = SVal.getVectorElt(i);
2691       llvm::APInt EltAsInt;
2692       if (Elt.isInt()) {
2693         EltAsInt = Elt.getInt();
2694       } else if (Elt.isFloat()) {
2695         EltAsInt = Elt.getFloat().bitcastToAPInt();
2696       } else {
2697         // Don't try to handle vectors of anything other than int or float
2698         // (not sure if it's possible to hit this case).
2699         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2700         return false;
2701       }
2702       unsigned BaseEltSize = EltAsInt.getBitWidth();
2703       if (BigEndian)
2704         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2705       else
2706         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2707     }
2708     return true;
2709   }
2710   // Give up if the input isn't an int, float, or vector.  For example, we
2711   // reject "(v4i16)(intptr_t)&a".
2712   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2713   return false;
2714 }
2715 
2716 /// Perform the given integer operation, which is known to need at most BitWidth
2717 /// bits, and check for overflow in the original type (if that type was not an
2718 /// unsigned type).
2719 template<typename Operation>
2720 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2721                                  const APSInt &LHS, const APSInt &RHS,
2722                                  unsigned BitWidth, Operation Op,
2723                                  APSInt &Result) {
2724   if (LHS.isUnsigned()) {
2725     Result = Op(LHS, RHS);
2726     return true;
2727   }
2728 
2729   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2730   Result = Value.trunc(LHS.getBitWidth());
2731   if (Result.extend(BitWidth) != Value) {
2732     if (Info.checkingForUndefinedBehavior())
2733       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2734                                        diag::warn_integer_constant_overflow)
2735           << toString(Result, 10) << E->getType();
2736     return HandleOverflow(Info, E, Value, E->getType());
2737   }
2738   return true;
2739 }
2740 
2741 /// Perform the given binary integer operation.
2742 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2743                               BinaryOperatorKind Opcode, APSInt RHS,
2744                               APSInt &Result) {
2745   switch (Opcode) {
2746   default:
2747     Info.FFDiag(E);
2748     return false;
2749   case BO_Mul:
2750     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2751                                 std::multiplies<APSInt>(), Result);
2752   case BO_Add:
2753     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2754                                 std::plus<APSInt>(), Result);
2755   case BO_Sub:
2756     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2757                                 std::minus<APSInt>(), Result);
2758   case BO_And: Result = LHS & RHS; return true;
2759   case BO_Xor: Result = LHS ^ RHS; return true;
2760   case BO_Or:  Result = LHS | RHS; return true;
2761   case BO_Div:
2762   case BO_Rem:
2763     if (RHS == 0) {
2764       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2765       return false;
2766     }
2767     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2768     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2769     // this operation and gives the two's complement result.
2770     if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2771         LHS.isMinSignedValue())
2772       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2773                             E->getType());
2774     return true;
2775   case BO_Shl: {
2776     if (Info.getLangOpts().OpenCL)
2777       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2778       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2779                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2780                     RHS.isUnsigned());
2781     else if (RHS.isSigned() && RHS.isNegative()) {
2782       // During constant-folding, a negative shift is an opposite shift. Such
2783       // a shift is not a constant expression.
2784       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2785       RHS = -RHS;
2786       goto shift_right;
2787     }
2788   shift_left:
2789     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2790     // the shifted type.
2791     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2792     if (SA != RHS) {
2793       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2794         << RHS << E->getType() << LHS.getBitWidth();
2795     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2796       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2797       // operand, and must not overflow the corresponding unsigned type.
2798       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2799       // E1 x 2^E2 module 2^N.
2800       if (LHS.isNegative())
2801         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2802       else if (LHS.countLeadingZeros() < SA)
2803         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2804     }
2805     Result = LHS << SA;
2806     return true;
2807   }
2808   case BO_Shr: {
2809     if (Info.getLangOpts().OpenCL)
2810       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2811       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2812                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2813                     RHS.isUnsigned());
2814     else if (RHS.isSigned() && RHS.isNegative()) {
2815       // During constant-folding, a negative shift is an opposite shift. Such a
2816       // shift is not a constant expression.
2817       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2818       RHS = -RHS;
2819       goto shift_left;
2820     }
2821   shift_right:
2822     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2823     // shifted type.
2824     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2825     if (SA != RHS)
2826       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2827         << RHS << E->getType() << LHS.getBitWidth();
2828     Result = LHS >> SA;
2829     return true;
2830   }
2831 
2832   case BO_LT: Result = LHS < RHS; return true;
2833   case BO_GT: Result = LHS > RHS; return true;
2834   case BO_LE: Result = LHS <= RHS; return true;
2835   case BO_GE: Result = LHS >= RHS; return true;
2836   case BO_EQ: Result = LHS == RHS; return true;
2837   case BO_NE: Result = LHS != RHS; return true;
2838   case BO_Cmp:
2839     llvm_unreachable("BO_Cmp should be handled elsewhere");
2840   }
2841 }
2842 
2843 /// Perform the given binary floating-point operation, in-place, on LHS.
2844 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2845                                   APFloat &LHS, BinaryOperatorKind Opcode,
2846                                   const APFloat &RHS) {
2847   bool DynamicRM;
2848   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2849   APFloat::opStatus St;
2850   switch (Opcode) {
2851   default:
2852     Info.FFDiag(E);
2853     return false;
2854   case BO_Mul:
2855     St = LHS.multiply(RHS, RM);
2856     break;
2857   case BO_Add:
2858     St = LHS.add(RHS, RM);
2859     break;
2860   case BO_Sub:
2861     St = LHS.subtract(RHS, RM);
2862     break;
2863   case BO_Div:
2864     // [expr.mul]p4:
2865     //   If the second operand of / or % is zero the behavior is undefined.
2866     if (RHS.isZero())
2867       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2868     St = LHS.divide(RHS, RM);
2869     break;
2870   }
2871 
2872   // [expr.pre]p4:
2873   //   If during the evaluation of an expression, the result is not
2874   //   mathematically defined [...], the behavior is undefined.
2875   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2876   if (LHS.isNaN()) {
2877     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2878     return Info.noteUndefinedBehavior();
2879   }
2880 
2881   return checkFloatingPointResult(Info, E, St);
2882 }
2883 
2884 static bool handleLogicalOpForVector(const APInt &LHSValue,
2885                                      BinaryOperatorKind Opcode,
2886                                      const APInt &RHSValue, APInt &Result) {
2887   bool LHS = (LHSValue != 0);
2888   bool RHS = (RHSValue != 0);
2889 
2890   if (Opcode == BO_LAnd)
2891     Result = LHS && RHS;
2892   else
2893     Result = LHS || RHS;
2894   return true;
2895 }
2896 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2897                                      BinaryOperatorKind Opcode,
2898                                      const APFloat &RHSValue, APInt &Result) {
2899   bool LHS = !LHSValue.isZero();
2900   bool RHS = !RHSValue.isZero();
2901 
2902   if (Opcode == BO_LAnd)
2903     Result = LHS && RHS;
2904   else
2905     Result = LHS || RHS;
2906   return true;
2907 }
2908 
2909 static bool handleLogicalOpForVector(const APValue &LHSValue,
2910                                      BinaryOperatorKind Opcode,
2911                                      const APValue &RHSValue, APInt &Result) {
2912   // The result is always an int type, however operands match the first.
2913   if (LHSValue.getKind() == APValue::Int)
2914     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2915                                     RHSValue.getInt(), Result);
2916   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2917   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2918                                   RHSValue.getFloat(), Result);
2919 }
2920 
2921 template <typename APTy>
2922 static bool
2923 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2924                                const APTy &RHSValue, APInt &Result) {
2925   switch (Opcode) {
2926   default:
2927     llvm_unreachable("unsupported binary operator");
2928   case BO_EQ:
2929     Result = (LHSValue == RHSValue);
2930     break;
2931   case BO_NE:
2932     Result = (LHSValue != RHSValue);
2933     break;
2934   case BO_LT:
2935     Result = (LHSValue < RHSValue);
2936     break;
2937   case BO_GT:
2938     Result = (LHSValue > RHSValue);
2939     break;
2940   case BO_LE:
2941     Result = (LHSValue <= RHSValue);
2942     break;
2943   case BO_GE:
2944     Result = (LHSValue >= RHSValue);
2945     break;
2946   }
2947 
2948   // The boolean operations on these vector types use an instruction that
2949   // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2950   // to -1 to make sure that we produce the correct value.
2951   Result.negate();
2952 
2953   return true;
2954 }
2955 
2956 static bool handleCompareOpForVector(const APValue &LHSValue,
2957                                      BinaryOperatorKind Opcode,
2958                                      const APValue &RHSValue, APInt &Result) {
2959   // The result is always an int type, however operands match the first.
2960   if (LHSValue.getKind() == APValue::Int)
2961     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2962                                           RHSValue.getInt(), Result);
2963   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2964   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2965                                         RHSValue.getFloat(), Result);
2966 }
2967 
2968 // Perform binary operations for vector types, in place on the LHS.
2969 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2970                                     BinaryOperatorKind Opcode,
2971                                     APValue &LHSValue,
2972                                     const APValue &RHSValue) {
2973   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2974          "Operation not supported on vector types");
2975 
2976   const auto *VT = E->getType()->castAs<VectorType>();
2977   unsigned NumElements = VT->getNumElements();
2978   QualType EltTy = VT->getElementType();
2979 
2980   // In the cases (typically C as I've observed) where we aren't evaluating
2981   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2982   // just give up.
2983   if (!LHSValue.isVector()) {
2984     assert(LHSValue.isLValue() &&
2985            "A vector result that isn't a vector OR uncalculated LValue");
2986     Info.FFDiag(E);
2987     return false;
2988   }
2989 
2990   assert(LHSValue.getVectorLength() == NumElements &&
2991          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2992 
2993   SmallVector<APValue, 4> ResultElements;
2994 
2995   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2996     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2997     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2998 
2999     if (EltTy->isIntegerType()) {
3000       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3001                        EltTy->isUnsignedIntegerType()};
3002       bool Success = true;
3003 
3004       if (BinaryOperator::isLogicalOp(Opcode))
3005         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3006       else if (BinaryOperator::isComparisonOp(Opcode))
3007         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3008       else
3009         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3010                                     RHSElt.getInt(), EltResult);
3011 
3012       if (!Success) {
3013         Info.FFDiag(E);
3014         return false;
3015       }
3016       ResultElements.emplace_back(EltResult);
3017 
3018     } else if (EltTy->isFloatingType()) {
3019       assert(LHSElt.getKind() == APValue::Float &&
3020              RHSElt.getKind() == APValue::Float &&
3021              "Mismatched LHS/RHS/Result Type");
3022       APFloat LHSFloat = LHSElt.getFloat();
3023 
3024       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3025                                  RHSElt.getFloat())) {
3026         Info.FFDiag(E);
3027         return false;
3028       }
3029 
3030       ResultElements.emplace_back(LHSFloat);
3031     }
3032   }
3033 
3034   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3035   return true;
3036 }
3037 
3038 /// Cast an lvalue referring to a base subobject to a derived class, by
3039 /// truncating the lvalue's path to the given length.
3040 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3041                                const RecordDecl *TruncatedType,
3042                                unsigned TruncatedElements) {
3043   SubobjectDesignator &D = Result.Designator;
3044 
3045   // Check we actually point to a derived class object.
3046   if (TruncatedElements == D.Entries.size())
3047     return true;
3048   assert(TruncatedElements >= D.MostDerivedPathLength &&
3049          "not casting to a derived class");
3050   if (!Result.checkSubobject(Info, E, CSK_Derived))
3051     return false;
3052 
3053   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3054   const RecordDecl *RD = TruncatedType;
3055   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3056     if (RD->isInvalidDecl()) return false;
3057     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3058     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3059     if (isVirtualBaseClass(D.Entries[I]))
3060       Result.Offset -= Layout.getVBaseClassOffset(Base);
3061     else
3062       Result.Offset -= Layout.getBaseClassOffset(Base);
3063     RD = Base;
3064   }
3065   D.Entries.resize(TruncatedElements);
3066   return true;
3067 }
3068 
3069 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3070                                    const CXXRecordDecl *Derived,
3071                                    const CXXRecordDecl *Base,
3072                                    const ASTRecordLayout *RL = nullptr) {
3073   if (!RL) {
3074     if (Derived->isInvalidDecl()) return false;
3075     RL = &Info.Ctx.getASTRecordLayout(Derived);
3076   }
3077 
3078   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3079   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3080   return true;
3081 }
3082 
3083 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3084                              const CXXRecordDecl *DerivedDecl,
3085                              const CXXBaseSpecifier *Base) {
3086   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3087 
3088   if (!Base->isVirtual())
3089     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3090 
3091   SubobjectDesignator &D = Obj.Designator;
3092   if (D.Invalid)
3093     return false;
3094 
3095   // Extract most-derived object and corresponding type.
3096   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3097   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3098     return false;
3099 
3100   // Find the virtual base class.
3101   if (DerivedDecl->isInvalidDecl()) return false;
3102   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3103   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3104   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3105   return true;
3106 }
3107 
3108 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3109                                  QualType Type, LValue &Result) {
3110   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3111                                      PathE = E->path_end();
3112        PathI != PathE; ++PathI) {
3113     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3114                           *PathI))
3115       return false;
3116     Type = (*PathI)->getType();
3117   }
3118   return true;
3119 }
3120 
3121 /// Cast an lvalue referring to a derived class to a known base subobject.
3122 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3123                             const CXXRecordDecl *DerivedRD,
3124                             const CXXRecordDecl *BaseRD) {
3125   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3126                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3127   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3128     llvm_unreachable("Class must be derived from the passed in base class!");
3129 
3130   for (CXXBasePathElement &Elem : Paths.front())
3131     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3132       return false;
3133   return true;
3134 }
3135 
3136 /// Update LVal to refer to the given field, which must be a member of the type
3137 /// currently described by LVal.
3138 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3139                                const FieldDecl *FD,
3140                                const ASTRecordLayout *RL = nullptr) {
3141   if (!RL) {
3142     if (FD->getParent()->isInvalidDecl()) return false;
3143     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3144   }
3145 
3146   unsigned I = FD->getFieldIndex();
3147   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3148   LVal.addDecl(Info, E, FD);
3149   return true;
3150 }
3151 
3152 /// Update LVal to refer to the given indirect field.
3153 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3154                                        LValue &LVal,
3155                                        const IndirectFieldDecl *IFD) {
3156   for (const auto *C : IFD->chain())
3157     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3158       return false;
3159   return true;
3160 }
3161 
3162 /// Get the size of the given type in char units.
3163 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3164                          QualType Type, CharUnits &Size) {
3165   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3166   // extension.
3167   if (Type->isVoidType() || Type->isFunctionType()) {
3168     Size = CharUnits::One();
3169     return true;
3170   }
3171 
3172   if (Type->isDependentType()) {
3173     Info.FFDiag(Loc);
3174     return false;
3175   }
3176 
3177   if (!Type->isConstantSizeType()) {
3178     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3179     // FIXME: Better diagnostic.
3180     Info.FFDiag(Loc);
3181     return false;
3182   }
3183 
3184   Size = Info.Ctx.getTypeSizeInChars(Type);
3185   return true;
3186 }
3187 
3188 /// Update a pointer value to model pointer arithmetic.
3189 /// \param Info - Information about the ongoing evaluation.
3190 /// \param E - The expression being evaluated, for diagnostic purposes.
3191 /// \param LVal - The pointer value to be updated.
3192 /// \param EltTy - The pointee type represented by LVal.
3193 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3194 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3195                                         LValue &LVal, QualType EltTy,
3196                                         APSInt Adjustment) {
3197   CharUnits SizeOfPointee;
3198   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3199     return false;
3200 
3201   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3202   return true;
3203 }
3204 
3205 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3206                                         LValue &LVal, QualType EltTy,
3207                                         int64_t Adjustment) {
3208   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3209                                      APSInt::get(Adjustment));
3210 }
3211 
3212 /// Update an lvalue to refer to a component of a complex number.
3213 /// \param Info - Information about the ongoing evaluation.
3214 /// \param LVal - The lvalue to be updated.
3215 /// \param EltTy - The complex number's component type.
3216 /// \param Imag - False for the real component, true for the imaginary.
3217 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3218                                        LValue &LVal, QualType EltTy,
3219                                        bool Imag) {
3220   if (Imag) {
3221     CharUnits SizeOfComponent;
3222     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3223       return false;
3224     LVal.Offset += SizeOfComponent;
3225   }
3226   LVal.addComplex(Info, E, EltTy, Imag);
3227   return true;
3228 }
3229 
3230 /// Try to evaluate the initializer for a variable declaration.
3231 ///
3232 /// \param Info   Information about the ongoing evaluation.
3233 /// \param E      An expression to be used when printing diagnostics.
3234 /// \param VD     The variable whose initializer should be obtained.
3235 /// \param Version The version of the variable within the frame.
3236 /// \param Frame  The frame in which the variable was created. Must be null
3237 ///               if this variable is not local to the evaluation.
3238 /// \param Result Filled in with a pointer to the value of the variable.
3239 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3240                                 const VarDecl *VD, CallStackFrame *Frame,
3241                                 unsigned Version, APValue *&Result) {
3242   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3243 
3244   // If this is a local variable, dig out its value.
3245   if (Frame) {
3246     Result = Frame->getTemporary(VD, Version);
3247     if (Result)
3248       return true;
3249 
3250     if (!isa<ParmVarDecl>(VD)) {
3251       // Assume variables referenced within a lambda's call operator that were
3252       // not declared within the call operator are captures and during checking
3253       // of a potential constant expression, assume they are unknown constant
3254       // expressions.
3255       assert(isLambdaCallOperator(Frame->Callee) &&
3256              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3257              "missing value for local variable");
3258       if (Info.checkingPotentialConstantExpression())
3259         return false;
3260       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3261       // still reachable at all?
3262       Info.FFDiag(E->getBeginLoc(),
3263                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3264           << "captures not currently allowed";
3265       return false;
3266     }
3267   }
3268 
3269   // If we're currently evaluating the initializer of this declaration, use that
3270   // in-flight value.
3271   if (Info.EvaluatingDecl == Base) {
3272     Result = Info.EvaluatingDeclValue;
3273     return true;
3274   }
3275 
3276   if (isa<ParmVarDecl>(VD)) {
3277     // Assume parameters of a potential constant expression are usable in
3278     // constant expressions.
3279     if (!Info.checkingPotentialConstantExpression() ||
3280         !Info.CurrentCall->Callee ||
3281         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3282       if (Info.getLangOpts().CPlusPlus11) {
3283         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3284             << VD;
3285         NoteLValueLocation(Info, Base);
3286       } else {
3287         Info.FFDiag(E);
3288       }
3289     }
3290     return false;
3291   }
3292 
3293   // Dig out the initializer, and use the declaration which it's attached to.
3294   // FIXME: We should eventually check whether the variable has a reachable
3295   // initializing declaration.
3296   const Expr *Init = VD->getAnyInitializer(VD);
3297   if (!Init) {
3298     // Don't diagnose during potential constant expression checking; an
3299     // initializer might be added later.
3300     if (!Info.checkingPotentialConstantExpression()) {
3301       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3302         << VD;
3303       NoteLValueLocation(Info, Base);
3304     }
3305     return false;
3306   }
3307 
3308   if (Init->isValueDependent()) {
3309     // The DeclRefExpr is not value-dependent, but the variable it refers to
3310     // has a value-dependent initializer. This should only happen in
3311     // constant-folding cases, where the variable is not actually of a suitable
3312     // type for use in a constant expression (otherwise the DeclRefExpr would
3313     // have been value-dependent too), so diagnose that.
3314     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3315     if (!Info.checkingPotentialConstantExpression()) {
3316       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3317                          ? diag::note_constexpr_ltor_non_constexpr
3318                          : diag::note_constexpr_ltor_non_integral, 1)
3319           << VD << VD->getType();
3320       NoteLValueLocation(Info, Base);
3321     }
3322     return false;
3323   }
3324 
3325   // Check that we can fold the initializer. In C++, we will have already done
3326   // this in the cases where it matters for conformance.
3327   if (!VD->evaluateValue()) {
3328     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3329     NoteLValueLocation(Info, Base);
3330     return false;
3331   }
3332 
3333   // Check that the variable is actually usable in constant expressions. For a
3334   // const integral variable or a reference, we might have a non-constant
3335   // initializer that we can nonetheless evaluate the initializer for. Such
3336   // variables are not usable in constant expressions. In C++98, the
3337   // initializer also syntactically needs to be an ICE.
3338   //
3339   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3340   // expressions here; doing so would regress diagnostics for things like
3341   // reading from a volatile constexpr variable.
3342   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3343        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3344       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3345        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3346     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3347     NoteLValueLocation(Info, Base);
3348   }
3349 
3350   // Never use the initializer of a weak variable, not even for constant
3351   // folding. We can't be sure that this is the definition that will be used.
3352   if (VD->isWeak()) {
3353     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3354     NoteLValueLocation(Info, Base);
3355     return false;
3356   }
3357 
3358   Result = VD->getEvaluatedValue();
3359   return true;
3360 }
3361 
3362 /// Get the base index of the given base class within an APValue representing
3363 /// the given derived class.
3364 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3365                              const CXXRecordDecl *Base) {
3366   Base = Base->getCanonicalDecl();
3367   unsigned Index = 0;
3368   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3369          E = Derived->bases_end(); I != E; ++I, ++Index) {
3370     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3371       return Index;
3372   }
3373 
3374   llvm_unreachable("base class missing from derived class's bases list");
3375 }
3376 
3377 /// Extract the value of a character from a string literal.
3378 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3379                                             uint64_t Index) {
3380   assert(!isa<SourceLocExpr>(Lit) &&
3381          "SourceLocExpr should have already been converted to a StringLiteral");
3382 
3383   // FIXME: Support MakeStringConstant
3384   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3385     std::string Str;
3386     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3387     assert(Index <= Str.size() && "Index too large");
3388     return APSInt::getUnsigned(Str.c_str()[Index]);
3389   }
3390 
3391   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3392     Lit = PE->getFunctionName();
3393   const StringLiteral *S = cast<StringLiteral>(Lit);
3394   const ConstantArrayType *CAT =
3395       Info.Ctx.getAsConstantArrayType(S->getType());
3396   assert(CAT && "string literal isn't an array");
3397   QualType CharType = CAT->getElementType();
3398   assert(CharType->isIntegerType() && "unexpected character type");
3399 
3400   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3401                CharType->isUnsignedIntegerType());
3402   if (Index < S->getLength())
3403     Value = S->getCodeUnit(Index);
3404   return Value;
3405 }
3406 
3407 // Expand a string literal into an array of characters.
3408 //
3409 // FIXME: This is inefficient; we should probably introduce something similar
3410 // to the LLVM ConstantDataArray to make this cheaper.
3411 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3412                                 APValue &Result,
3413                                 QualType AllocType = QualType()) {
3414   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3415       AllocType.isNull() ? S->getType() : AllocType);
3416   assert(CAT && "string literal isn't an array");
3417   QualType CharType = CAT->getElementType();
3418   assert(CharType->isIntegerType() && "unexpected character type");
3419 
3420   unsigned Elts = CAT->getSize().getZExtValue();
3421   Result = APValue(APValue::UninitArray(),
3422                    std::min(S->getLength(), Elts), Elts);
3423   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3424                CharType->isUnsignedIntegerType());
3425   if (Result.hasArrayFiller())
3426     Result.getArrayFiller() = APValue(Value);
3427   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3428     Value = S->getCodeUnit(I);
3429     Result.getArrayInitializedElt(I) = APValue(Value);
3430   }
3431 }
3432 
3433 // Expand an array so that it has more than Index filled elements.
3434 static void expandArray(APValue &Array, unsigned Index) {
3435   unsigned Size = Array.getArraySize();
3436   assert(Index < Size);
3437 
3438   // Always at least double the number of elements for which we store a value.
3439   unsigned OldElts = Array.getArrayInitializedElts();
3440   unsigned NewElts = std::max(Index+1, OldElts * 2);
3441   NewElts = std::min(Size, std::max(NewElts, 8u));
3442 
3443   // Copy the data across.
3444   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3445   for (unsigned I = 0; I != OldElts; ++I)
3446     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3447   for (unsigned I = OldElts; I != NewElts; ++I)
3448     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3449   if (NewValue.hasArrayFiller())
3450     NewValue.getArrayFiller() = Array.getArrayFiller();
3451   Array.swap(NewValue);
3452 }
3453 
3454 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3455 /// conversion. If it's of class type, we may assume that the copy operation
3456 /// is trivial. Note that this is never true for a union type with fields
3457 /// (because the copy always "reads" the active member) and always true for
3458 /// a non-class type.
3459 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3460 static bool isReadByLvalueToRvalueConversion(QualType T) {
3461   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3462   return !RD || isReadByLvalueToRvalueConversion(RD);
3463 }
3464 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3465   // FIXME: A trivial copy of a union copies the object representation, even if
3466   // the union is empty.
3467   if (RD->isUnion())
3468     return !RD->field_empty();
3469   if (RD->isEmpty())
3470     return false;
3471 
3472   for (auto *Field : RD->fields())
3473     if (!Field->isUnnamedBitfield() &&
3474         isReadByLvalueToRvalueConversion(Field->getType()))
3475       return true;
3476 
3477   for (auto &BaseSpec : RD->bases())
3478     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3479       return true;
3480 
3481   return false;
3482 }
3483 
3484 /// Diagnose an attempt to read from any unreadable field within the specified
3485 /// type, which might be a class type.
3486 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3487                                   QualType T) {
3488   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3489   if (!RD)
3490     return false;
3491 
3492   if (!RD->hasMutableFields())
3493     return false;
3494 
3495   for (auto *Field : RD->fields()) {
3496     // If we're actually going to read this field in some way, then it can't
3497     // be mutable. If we're in a union, then assigning to a mutable field
3498     // (even an empty one) can change the active member, so that's not OK.
3499     // FIXME: Add core issue number for the union case.
3500     if (Field->isMutable() &&
3501         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3502       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3503       Info.Note(Field->getLocation(), diag::note_declared_at);
3504       return true;
3505     }
3506 
3507     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3508       return true;
3509   }
3510 
3511   for (auto &BaseSpec : RD->bases())
3512     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3513       return true;
3514 
3515   // All mutable fields were empty, and thus not actually read.
3516   return false;
3517 }
3518 
3519 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3520                                         APValue::LValueBase Base,
3521                                         bool MutableSubobject = false) {
3522   // A temporary or transient heap allocation we created.
3523   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3524     return true;
3525 
3526   switch (Info.IsEvaluatingDecl) {
3527   case EvalInfo::EvaluatingDeclKind::None:
3528     return false;
3529 
3530   case EvalInfo::EvaluatingDeclKind::Ctor:
3531     // The variable whose initializer we're evaluating.
3532     if (Info.EvaluatingDecl == Base)
3533       return true;
3534 
3535     // A temporary lifetime-extended by the variable whose initializer we're
3536     // evaluating.
3537     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3538       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3539         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3540     return false;
3541 
3542   case EvalInfo::EvaluatingDeclKind::Dtor:
3543     // C++2a [expr.const]p6:
3544     //   [during constant destruction] the lifetime of a and its non-mutable
3545     //   subobjects (but not its mutable subobjects) [are] considered to start
3546     //   within e.
3547     if (MutableSubobject || Base != Info.EvaluatingDecl)
3548       return false;
3549     // FIXME: We can meaningfully extend this to cover non-const objects, but
3550     // we will need special handling: we should be able to access only
3551     // subobjects of such objects that are themselves declared const.
3552     QualType T = getType(Base);
3553     return T.isConstQualified() || T->isReferenceType();
3554   }
3555 
3556   llvm_unreachable("unknown evaluating decl kind");
3557 }
3558 
3559 namespace {
3560 /// A handle to a complete object (an object that is not a subobject of
3561 /// another object).
3562 struct CompleteObject {
3563   /// The identity of the object.
3564   APValue::LValueBase Base;
3565   /// The value of the complete object.
3566   APValue *Value;
3567   /// The type of the complete object.
3568   QualType Type;
3569 
3570   CompleteObject() : Value(nullptr) {}
3571   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3572       : Base(Base), Value(Value), Type(Type) {}
3573 
3574   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3575     // If this isn't a "real" access (eg, if it's just accessing the type
3576     // info), allow it. We assume the type doesn't change dynamically for
3577     // subobjects of constexpr objects (even though we'd hit UB here if it
3578     // did). FIXME: Is this right?
3579     if (!isAnyAccess(AK))
3580       return true;
3581 
3582     // In C++14 onwards, it is permitted to read a mutable member whose
3583     // lifetime began within the evaluation.
3584     // FIXME: Should we also allow this in C++11?
3585     if (!Info.getLangOpts().CPlusPlus14)
3586       return false;
3587     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3588   }
3589 
3590   explicit operator bool() const { return !Type.isNull(); }
3591 };
3592 } // end anonymous namespace
3593 
3594 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3595                                  bool IsMutable = false) {
3596   // C++ [basic.type.qualifier]p1:
3597   // - A const object is an object of type const T or a non-mutable subobject
3598   //   of a const object.
3599   if (ObjType.isConstQualified() && !IsMutable)
3600     SubobjType.addConst();
3601   // - A volatile object is an object of type const T or a subobject of a
3602   //   volatile object.
3603   if (ObjType.isVolatileQualified())
3604     SubobjType.addVolatile();
3605   return SubobjType;
3606 }
3607 
3608 /// Find the designated sub-object of an rvalue.
3609 template<typename SubobjectHandler>
3610 typename SubobjectHandler::result_type
3611 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3612               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3613   if (Sub.Invalid)
3614     // A diagnostic will have already been produced.
3615     return handler.failed();
3616   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3617     if (Info.getLangOpts().CPlusPlus11)
3618       Info.FFDiag(E, Sub.isOnePastTheEnd()
3619                          ? diag::note_constexpr_access_past_end
3620                          : diag::note_constexpr_access_unsized_array)
3621           << handler.AccessKind;
3622     else
3623       Info.FFDiag(E);
3624     return handler.failed();
3625   }
3626 
3627   APValue *O = Obj.Value;
3628   QualType ObjType = Obj.Type;
3629   const FieldDecl *LastField = nullptr;
3630   const FieldDecl *VolatileField = nullptr;
3631 
3632   // Walk the designator's path to find the subobject.
3633   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3634     // Reading an indeterminate value is undefined, but assigning over one is OK.
3635     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3636         (O->isIndeterminate() &&
3637          !isValidIndeterminateAccess(handler.AccessKind))) {
3638       if (!Info.checkingPotentialConstantExpression())
3639         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3640             << handler.AccessKind << O->isIndeterminate();
3641       return handler.failed();
3642     }
3643 
3644     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3645     //    const and volatile semantics are not applied on an object under
3646     //    {con,de}struction.
3647     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3648         ObjType->isRecordType() &&
3649         Info.isEvaluatingCtorDtor(
3650             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3651                                          Sub.Entries.begin() + I)) !=
3652                           ConstructionPhase::None) {
3653       ObjType = Info.Ctx.getCanonicalType(ObjType);
3654       ObjType.removeLocalConst();
3655       ObjType.removeLocalVolatile();
3656     }
3657 
3658     // If this is our last pass, check that the final object type is OK.
3659     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3660       // Accesses to volatile objects are prohibited.
3661       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3662         if (Info.getLangOpts().CPlusPlus) {
3663           int DiagKind;
3664           SourceLocation Loc;
3665           const NamedDecl *Decl = nullptr;
3666           if (VolatileField) {
3667             DiagKind = 2;
3668             Loc = VolatileField->getLocation();
3669             Decl = VolatileField;
3670           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3671             DiagKind = 1;
3672             Loc = VD->getLocation();
3673             Decl = VD;
3674           } else {
3675             DiagKind = 0;
3676             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3677               Loc = E->getExprLoc();
3678           }
3679           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3680               << handler.AccessKind << DiagKind << Decl;
3681           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3682         } else {
3683           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3684         }
3685         return handler.failed();
3686       }
3687 
3688       // If we are reading an object of class type, there may still be more
3689       // things we need to check: if there are any mutable subobjects, we
3690       // cannot perform this read. (This only happens when performing a trivial
3691       // copy or assignment.)
3692       if (ObjType->isRecordType() &&
3693           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3694           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3695         return handler.failed();
3696     }
3697 
3698     if (I == N) {
3699       if (!handler.found(*O, ObjType))
3700         return false;
3701 
3702       // If we modified a bit-field, truncate it to the right width.
3703       if (isModification(handler.AccessKind) &&
3704           LastField && LastField->isBitField() &&
3705           !truncateBitfieldValue(Info, E, *O, LastField))
3706         return false;
3707 
3708       return true;
3709     }
3710 
3711     LastField = nullptr;
3712     if (ObjType->isArrayType()) {
3713       // Next subobject is an array element.
3714       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3715       assert(CAT && "vla in literal type?");
3716       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3717       if (CAT->getSize().ule(Index)) {
3718         // Note, it should not be possible to form a pointer with a valid
3719         // designator which points more than one past the end of the array.
3720         if (Info.getLangOpts().CPlusPlus11)
3721           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3722             << handler.AccessKind;
3723         else
3724           Info.FFDiag(E);
3725         return handler.failed();
3726       }
3727 
3728       ObjType = CAT->getElementType();
3729 
3730       if (O->getArrayInitializedElts() > Index)
3731         O = &O->getArrayInitializedElt(Index);
3732       else if (!isRead(handler.AccessKind)) {
3733         expandArray(*O, Index);
3734         O = &O->getArrayInitializedElt(Index);
3735       } else
3736         O = &O->getArrayFiller();
3737     } else if (ObjType->isAnyComplexType()) {
3738       // Next subobject is a complex number.
3739       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3740       if (Index > 1) {
3741         if (Info.getLangOpts().CPlusPlus11)
3742           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3743             << handler.AccessKind;
3744         else
3745           Info.FFDiag(E);
3746         return handler.failed();
3747       }
3748 
3749       ObjType = getSubobjectType(
3750           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3751 
3752       assert(I == N - 1 && "extracting subobject of scalar?");
3753       if (O->isComplexInt()) {
3754         return handler.found(Index ? O->getComplexIntImag()
3755                                    : O->getComplexIntReal(), ObjType);
3756       } else {
3757         assert(O->isComplexFloat());
3758         return handler.found(Index ? O->getComplexFloatImag()
3759                                    : O->getComplexFloatReal(), ObjType);
3760       }
3761     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3762       if (Field->isMutable() &&
3763           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3764         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3765           << handler.AccessKind << Field;
3766         Info.Note(Field->getLocation(), diag::note_declared_at);
3767         return handler.failed();
3768       }
3769 
3770       // Next subobject is a class, struct or union field.
3771       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3772       if (RD->isUnion()) {
3773         const FieldDecl *UnionField = O->getUnionField();
3774         if (!UnionField ||
3775             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3776           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3777             // Placement new onto an inactive union member makes it active.
3778             O->setUnion(Field, APValue());
3779           } else {
3780             // FIXME: If O->getUnionValue() is absent, report that there's no
3781             // active union member rather than reporting the prior active union
3782             // member. We'll need to fix nullptr_t to not use APValue() as its
3783             // representation first.
3784             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3785                 << handler.AccessKind << Field << !UnionField << UnionField;
3786             return handler.failed();
3787           }
3788         }
3789         O = &O->getUnionValue();
3790       } else
3791         O = &O->getStructField(Field->getFieldIndex());
3792 
3793       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3794       LastField = Field;
3795       if (Field->getType().isVolatileQualified())
3796         VolatileField = Field;
3797     } else {
3798       // Next subobject is a base class.
3799       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3800       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3801       O = &O->getStructBase(getBaseIndex(Derived, Base));
3802 
3803       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3804     }
3805   }
3806 }
3807 
3808 namespace {
3809 struct ExtractSubobjectHandler {
3810   EvalInfo &Info;
3811   const Expr *E;
3812   APValue &Result;
3813   const AccessKinds AccessKind;
3814 
3815   typedef bool result_type;
3816   bool failed() { return false; }
3817   bool found(APValue &Subobj, QualType SubobjType) {
3818     Result = Subobj;
3819     if (AccessKind == AK_ReadObjectRepresentation)
3820       return true;
3821     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3822   }
3823   bool found(APSInt &Value, QualType SubobjType) {
3824     Result = APValue(Value);
3825     return true;
3826   }
3827   bool found(APFloat &Value, QualType SubobjType) {
3828     Result = APValue(Value);
3829     return true;
3830   }
3831 };
3832 } // end anonymous namespace
3833 
3834 /// Extract the designated sub-object of an rvalue.
3835 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3836                              const CompleteObject &Obj,
3837                              const SubobjectDesignator &Sub, APValue &Result,
3838                              AccessKinds AK = AK_Read) {
3839   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3840   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3841   return findSubobject(Info, E, Obj, Sub, Handler);
3842 }
3843 
3844 namespace {
3845 struct ModifySubobjectHandler {
3846   EvalInfo &Info;
3847   APValue &NewVal;
3848   const Expr *E;
3849 
3850   typedef bool result_type;
3851   static const AccessKinds AccessKind = AK_Assign;
3852 
3853   bool checkConst(QualType QT) {
3854     // Assigning to a const object has undefined behavior.
3855     if (QT.isConstQualified()) {
3856       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3857       return false;
3858     }
3859     return true;
3860   }
3861 
3862   bool failed() { return false; }
3863   bool found(APValue &Subobj, QualType SubobjType) {
3864     if (!checkConst(SubobjType))
3865       return false;
3866     // We've been given ownership of NewVal, so just swap it in.
3867     Subobj.swap(NewVal);
3868     return true;
3869   }
3870   bool found(APSInt &Value, QualType SubobjType) {
3871     if (!checkConst(SubobjType))
3872       return false;
3873     if (!NewVal.isInt()) {
3874       // Maybe trying to write a cast pointer value into a complex?
3875       Info.FFDiag(E);
3876       return false;
3877     }
3878     Value = NewVal.getInt();
3879     return true;
3880   }
3881   bool found(APFloat &Value, QualType SubobjType) {
3882     if (!checkConst(SubobjType))
3883       return false;
3884     Value = NewVal.getFloat();
3885     return true;
3886   }
3887 };
3888 } // end anonymous namespace
3889 
3890 const AccessKinds ModifySubobjectHandler::AccessKind;
3891 
3892 /// Update the designated sub-object of an rvalue to the given value.
3893 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3894                             const CompleteObject &Obj,
3895                             const SubobjectDesignator &Sub,
3896                             APValue &NewVal) {
3897   ModifySubobjectHandler Handler = { Info, NewVal, E };
3898   return findSubobject(Info, E, Obj, Sub, Handler);
3899 }
3900 
3901 /// Find the position where two subobject designators diverge, or equivalently
3902 /// the length of the common initial subsequence.
3903 static unsigned FindDesignatorMismatch(QualType ObjType,
3904                                        const SubobjectDesignator &A,
3905                                        const SubobjectDesignator &B,
3906                                        bool &WasArrayIndex) {
3907   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3908   for (/**/; I != N; ++I) {
3909     if (!ObjType.isNull() &&
3910         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3911       // Next subobject is an array element.
3912       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3913         WasArrayIndex = true;
3914         return I;
3915       }
3916       if (ObjType->isAnyComplexType())
3917         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3918       else
3919         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3920     } else {
3921       if (A.Entries[I].getAsBaseOrMember() !=
3922           B.Entries[I].getAsBaseOrMember()) {
3923         WasArrayIndex = false;
3924         return I;
3925       }
3926       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3927         // Next subobject is a field.
3928         ObjType = FD->getType();
3929       else
3930         // Next subobject is a base class.
3931         ObjType = QualType();
3932     }
3933   }
3934   WasArrayIndex = false;
3935   return I;
3936 }
3937 
3938 /// Determine whether the given subobject designators refer to elements of the
3939 /// same array object.
3940 static bool AreElementsOfSameArray(QualType ObjType,
3941                                    const SubobjectDesignator &A,
3942                                    const SubobjectDesignator &B) {
3943   if (A.Entries.size() != B.Entries.size())
3944     return false;
3945 
3946   bool IsArray = A.MostDerivedIsArrayElement;
3947   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3948     // A is a subobject of the array element.
3949     return false;
3950 
3951   // If A (and B) designates an array element, the last entry will be the array
3952   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3953   // of length 1' case, and the entire path must match.
3954   bool WasArrayIndex;
3955   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3956   return CommonLength >= A.Entries.size() - IsArray;
3957 }
3958 
3959 /// Find the complete object to which an LValue refers.
3960 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3961                                          AccessKinds AK, const LValue &LVal,
3962                                          QualType LValType) {
3963   if (LVal.InvalidBase) {
3964     Info.FFDiag(E);
3965     return CompleteObject();
3966   }
3967 
3968   if (!LVal.Base) {
3969     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3970     return CompleteObject();
3971   }
3972 
3973   CallStackFrame *Frame = nullptr;
3974   unsigned Depth = 0;
3975   if (LVal.getLValueCallIndex()) {
3976     std::tie(Frame, Depth) =
3977         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3978     if (!Frame) {
3979       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3980         << AK << LVal.Base.is<const ValueDecl*>();
3981       NoteLValueLocation(Info, LVal.Base);
3982       return CompleteObject();
3983     }
3984   }
3985 
3986   bool IsAccess = isAnyAccess(AK);
3987 
3988   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3989   // is not a constant expression (even if the object is non-volatile). We also
3990   // apply this rule to C++98, in order to conform to the expected 'volatile'
3991   // semantics.
3992   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3993     if (Info.getLangOpts().CPlusPlus)
3994       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3995         << AK << LValType;
3996     else
3997       Info.FFDiag(E);
3998     return CompleteObject();
3999   }
4000 
4001   // Compute value storage location and type of base object.
4002   APValue *BaseVal = nullptr;
4003   QualType BaseType = getType(LVal.Base);
4004 
4005   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4006       lifetimeStartedInEvaluation(Info, LVal.Base)) {
4007     // This is the object whose initializer we're evaluating, so its lifetime
4008     // started in the current evaluation.
4009     BaseVal = Info.EvaluatingDeclValue;
4010   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4011     // Allow reading from a GUID declaration.
4012     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4013       if (isModification(AK)) {
4014         // All the remaining cases do not permit modification of the object.
4015         Info.FFDiag(E, diag::note_constexpr_modify_global);
4016         return CompleteObject();
4017       }
4018       APValue &V = GD->getAsAPValue();
4019       if (V.isAbsent()) {
4020         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4021             << GD->getType();
4022         return CompleteObject();
4023       }
4024       return CompleteObject(LVal.Base, &V, GD->getType());
4025     }
4026 
4027     // Allow reading from template parameter objects.
4028     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4029       if (isModification(AK)) {
4030         Info.FFDiag(E, diag::note_constexpr_modify_global);
4031         return CompleteObject();
4032       }
4033       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4034                             TPO->getType());
4035     }
4036 
4037     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4038     // In C++11, constexpr, non-volatile variables initialized with constant
4039     // expressions are constant expressions too. Inside constexpr functions,
4040     // parameters are constant expressions even if they're non-const.
4041     // In C++1y, objects local to a constant expression (those with a Frame) are
4042     // both readable and writable inside constant expressions.
4043     // In C, such things can also be folded, although they are not ICEs.
4044     const VarDecl *VD = dyn_cast<VarDecl>(D);
4045     if (VD) {
4046       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4047         VD = VDef;
4048     }
4049     if (!VD || VD->isInvalidDecl()) {
4050       Info.FFDiag(E);
4051       return CompleteObject();
4052     }
4053 
4054     bool IsConstant = BaseType.isConstant(Info.Ctx);
4055 
4056     // Unless we're looking at a local variable or argument in a constexpr call,
4057     // the variable we're reading must be const.
4058     if (!Frame) {
4059       if (IsAccess && isa<ParmVarDecl>(VD)) {
4060         // Access of a parameter that's not associated with a frame isn't going
4061         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4062         // suitable diagnostic.
4063       } else if (Info.getLangOpts().CPlusPlus14 &&
4064                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4065         // OK, we can read and modify an object if we're in the process of
4066         // evaluating its initializer, because its lifetime began in this
4067         // evaluation.
4068       } else if (isModification(AK)) {
4069         // All the remaining cases do not permit modification of the object.
4070         Info.FFDiag(E, diag::note_constexpr_modify_global);
4071         return CompleteObject();
4072       } else if (VD->isConstexpr()) {
4073         // OK, we can read this variable.
4074       } else if (BaseType->isIntegralOrEnumerationType()) {
4075         if (!IsConstant) {
4076           if (!IsAccess)
4077             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4078           if (Info.getLangOpts().CPlusPlus) {
4079             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4080             Info.Note(VD->getLocation(), diag::note_declared_at);
4081           } else {
4082             Info.FFDiag(E);
4083           }
4084           return CompleteObject();
4085         }
4086       } else if (!IsAccess) {
4087         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4088       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4089                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4090         // This variable might end up being constexpr. Don't diagnose it yet.
4091       } else if (IsConstant) {
4092         // Keep evaluating to see what we can do. In particular, we support
4093         // folding of const floating-point types, in order to make static const
4094         // data members of such types (supported as an extension) more useful.
4095         if (Info.getLangOpts().CPlusPlus) {
4096           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4097                               ? diag::note_constexpr_ltor_non_constexpr
4098                               : diag::note_constexpr_ltor_non_integral, 1)
4099               << VD << BaseType;
4100           Info.Note(VD->getLocation(), diag::note_declared_at);
4101         } else {
4102           Info.CCEDiag(E);
4103         }
4104       } else {
4105         // Never allow reading a non-const value.
4106         if (Info.getLangOpts().CPlusPlus) {
4107           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4108                              ? diag::note_constexpr_ltor_non_constexpr
4109                              : diag::note_constexpr_ltor_non_integral, 1)
4110               << VD << BaseType;
4111           Info.Note(VD->getLocation(), diag::note_declared_at);
4112         } else {
4113           Info.FFDiag(E);
4114         }
4115         return CompleteObject();
4116       }
4117     }
4118 
4119     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4120       return CompleteObject();
4121   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4122     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4123     if (!Alloc) {
4124       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4125       return CompleteObject();
4126     }
4127     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4128                           LVal.Base.getDynamicAllocType());
4129   } else {
4130     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4131 
4132     if (!Frame) {
4133       if (const MaterializeTemporaryExpr *MTE =
4134               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4135         assert(MTE->getStorageDuration() == SD_Static &&
4136                "should have a frame for a non-global materialized temporary");
4137 
4138         // C++20 [expr.const]p4: [DR2126]
4139         //   An object or reference is usable in constant expressions if it is
4140         //   - a temporary object of non-volatile const-qualified literal type
4141         //     whose lifetime is extended to that of a variable that is usable
4142         //     in constant expressions
4143         //
4144         // C++20 [expr.const]p5:
4145         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4146         //   - a non-volatile glvalue that refers to an object that is usable
4147         //     in constant expressions, or
4148         //   - a non-volatile glvalue of literal type that refers to a
4149         //     non-volatile object whose lifetime began within the evaluation
4150         //     of E;
4151         //
4152         // C++11 misses the 'began within the evaluation of e' check and
4153         // instead allows all temporaries, including things like:
4154         //   int &&r = 1;
4155         //   int x = ++r;
4156         //   constexpr int k = r;
4157         // Therefore we use the C++14-onwards rules in C++11 too.
4158         //
4159         // Note that temporaries whose lifetimes began while evaluating a
4160         // variable's constructor are not usable while evaluating the
4161         // corresponding destructor, not even if they're of const-qualified
4162         // types.
4163         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4164             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4165           if (!IsAccess)
4166             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4167           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4168           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4169           return CompleteObject();
4170         }
4171 
4172         BaseVal = MTE->getOrCreateValue(false);
4173         assert(BaseVal && "got reference to unevaluated temporary");
4174       } else {
4175         if (!IsAccess)
4176           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4177         APValue Val;
4178         LVal.moveInto(Val);
4179         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4180             << AK
4181             << Val.getAsString(Info.Ctx,
4182                                Info.Ctx.getLValueReferenceType(LValType));
4183         NoteLValueLocation(Info, LVal.Base);
4184         return CompleteObject();
4185       }
4186     } else {
4187       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4188       assert(BaseVal && "missing value for temporary");
4189     }
4190   }
4191 
4192   // In C++14, we can't safely access any mutable state when we might be
4193   // evaluating after an unmodeled side effect. Parameters are modeled as state
4194   // in the caller, but aren't visible once the call returns, so they can be
4195   // modified in a speculatively-evaluated call.
4196   //
4197   // FIXME: Not all local state is mutable. Allow local constant subobjects
4198   // to be read here (but take care with 'mutable' fields).
4199   unsigned VisibleDepth = Depth;
4200   if (llvm::isa_and_nonnull<ParmVarDecl>(
4201           LVal.Base.dyn_cast<const ValueDecl *>()))
4202     ++VisibleDepth;
4203   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4204        Info.EvalStatus.HasSideEffects) ||
4205       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4206     return CompleteObject();
4207 
4208   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4209 }
4210 
4211 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4212 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4213 /// glvalue referred to by an entity of reference type.
4214 ///
4215 /// \param Info - Information about the ongoing evaluation.
4216 /// \param Conv - The expression for which we are performing the conversion.
4217 ///               Used for diagnostics.
4218 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4219 ///               case of a non-class type).
4220 /// \param LVal - The glvalue on which we are attempting to perform this action.
4221 /// \param RVal - The produced value will be placed here.
4222 /// \param WantObjectRepresentation - If true, we're looking for the object
4223 ///               representation rather than the value, and in particular,
4224 ///               there is no requirement that the result be fully initialized.
4225 static bool
4226 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4227                                const LValue &LVal, APValue &RVal,
4228                                bool WantObjectRepresentation = false) {
4229   if (LVal.Designator.Invalid)
4230     return false;
4231 
4232   // Check for special cases where there is no existing APValue to look at.
4233   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4234 
4235   AccessKinds AK =
4236       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4237 
4238   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4239     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4240       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4241       // initializer until now for such expressions. Such an expression can't be
4242       // an ICE in C, so this only matters for fold.
4243       if (Type.isVolatileQualified()) {
4244         Info.FFDiag(Conv);
4245         return false;
4246       }
4247       APValue Lit;
4248       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4249         return false;
4250       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4251       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4252     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4253       // Special-case character extraction so we don't have to construct an
4254       // APValue for the whole string.
4255       assert(LVal.Designator.Entries.size() <= 1 &&
4256              "Can only read characters from string literals");
4257       if (LVal.Designator.Entries.empty()) {
4258         // Fail for now for LValue to RValue conversion of an array.
4259         // (This shouldn't show up in C/C++, but it could be triggered by a
4260         // weird EvaluateAsRValue call from a tool.)
4261         Info.FFDiag(Conv);
4262         return false;
4263       }
4264       if (LVal.Designator.isOnePastTheEnd()) {
4265         if (Info.getLangOpts().CPlusPlus11)
4266           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4267         else
4268           Info.FFDiag(Conv);
4269         return false;
4270       }
4271       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4272       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4273       return true;
4274     }
4275   }
4276 
4277   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4278   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4279 }
4280 
4281 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4282 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4283                              QualType LValType, APValue &Val) {
4284   if (LVal.Designator.Invalid)
4285     return false;
4286 
4287   if (!Info.getLangOpts().CPlusPlus14) {
4288     Info.FFDiag(E);
4289     return false;
4290   }
4291 
4292   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4293   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4294 }
4295 
4296 namespace {
4297 struct CompoundAssignSubobjectHandler {
4298   EvalInfo &Info;
4299   const CompoundAssignOperator *E;
4300   QualType PromotedLHSType;
4301   BinaryOperatorKind Opcode;
4302   const APValue &RHS;
4303 
4304   static const AccessKinds AccessKind = AK_Assign;
4305 
4306   typedef bool result_type;
4307 
4308   bool checkConst(QualType QT) {
4309     // Assigning to a const object has undefined behavior.
4310     if (QT.isConstQualified()) {
4311       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4312       return false;
4313     }
4314     return true;
4315   }
4316 
4317   bool failed() { return false; }
4318   bool found(APValue &Subobj, QualType SubobjType) {
4319     switch (Subobj.getKind()) {
4320     case APValue::Int:
4321       return found(Subobj.getInt(), SubobjType);
4322     case APValue::Float:
4323       return found(Subobj.getFloat(), SubobjType);
4324     case APValue::ComplexInt:
4325     case APValue::ComplexFloat:
4326       // FIXME: Implement complex compound assignment.
4327       Info.FFDiag(E);
4328       return false;
4329     case APValue::LValue:
4330       return foundPointer(Subobj, SubobjType);
4331     case APValue::Vector:
4332       return foundVector(Subobj, SubobjType);
4333     default:
4334       // FIXME: can this happen?
4335       Info.FFDiag(E);
4336       return false;
4337     }
4338   }
4339 
4340   bool foundVector(APValue &Value, QualType SubobjType) {
4341     if (!checkConst(SubobjType))
4342       return false;
4343 
4344     if (!SubobjType->isVectorType()) {
4345       Info.FFDiag(E);
4346       return false;
4347     }
4348     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4349   }
4350 
4351   bool found(APSInt &Value, QualType SubobjType) {
4352     if (!checkConst(SubobjType))
4353       return false;
4354 
4355     if (!SubobjType->isIntegerType()) {
4356       // We don't support compound assignment on integer-cast-to-pointer
4357       // values.
4358       Info.FFDiag(E);
4359       return false;
4360     }
4361 
4362     if (RHS.isInt()) {
4363       APSInt LHS =
4364           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4365       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4366         return false;
4367       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4368       return true;
4369     } else if (RHS.isFloat()) {
4370       const FPOptions FPO = E->getFPFeaturesInEffect(
4371                                     Info.Ctx.getLangOpts());
4372       APFloat FValue(0.0);
4373       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4374                                   PromotedLHSType, FValue) &&
4375              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4376              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4377                                   Value);
4378     }
4379 
4380     Info.FFDiag(E);
4381     return false;
4382   }
4383   bool found(APFloat &Value, QualType SubobjType) {
4384     return checkConst(SubobjType) &&
4385            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4386                                   Value) &&
4387            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4388            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4389   }
4390   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4391     if (!checkConst(SubobjType))
4392       return false;
4393 
4394     QualType PointeeType;
4395     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4396       PointeeType = PT->getPointeeType();
4397 
4398     if (PointeeType.isNull() || !RHS.isInt() ||
4399         (Opcode != BO_Add && Opcode != BO_Sub)) {
4400       Info.FFDiag(E);
4401       return false;
4402     }
4403 
4404     APSInt Offset = RHS.getInt();
4405     if (Opcode == BO_Sub)
4406       negateAsSigned(Offset);
4407 
4408     LValue LVal;
4409     LVal.setFrom(Info.Ctx, Subobj);
4410     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4411       return false;
4412     LVal.moveInto(Subobj);
4413     return true;
4414   }
4415 };
4416 } // end anonymous namespace
4417 
4418 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4419 
4420 /// Perform a compound assignment of LVal <op>= RVal.
4421 static bool handleCompoundAssignment(EvalInfo &Info,
4422                                      const CompoundAssignOperator *E,
4423                                      const LValue &LVal, QualType LValType,
4424                                      QualType PromotedLValType,
4425                                      BinaryOperatorKind Opcode,
4426                                      const APValue &RVal) {
4427   if (LVal.Designator.Invalid)
4428     return false;
4429 
4430   if (!Info.getLangOpts().CPlusPlus14) {
4431     Info.FFDiag(E);
4432     return false;
4433   }
4434 
4435   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4436   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4437                                              RVal };
4438   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4439 }
4440 
4441 namespace {
4442 struct IncDecSubobjectHandler {
4443   EvalInfo &Info;
4444   const UnaryOperator *E;
4445   AccessKinds AccessKind;
4446   APValue *Old;
4447 
4448   typedef bool result_type;
4449 
4450   bool checkConst(QualType QT) {
4451     // Assigning to a const object has undefined behavior.
4452     if (QT.isConstQualified()) {
4453       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4454       return false;
4455     }
4456     return true;
4457   }
4458 
4459   bool failed() { return false; }
4460   bool found(APValue &Subobj, QualType SubobjType) {
4461     // Stash the old value. Also clear Old, so we don't clobber it later
4462     // if we're post-incrementing a complex.
4463     if (Old) {
4464       *Old = Subobj;
4465       Old = nullptr;
4466     }
4467 
4468     switch (Subobj.getKind()) {
4469     case APValue::Int:
4470       return found(Subobj.getInt(), SubobjType);
4471     case APValue::Float:
4472       return found(Subobj.getFloat(), SubobjType);
4473     case APValue::ComplexInt:
4474       return found(Subobj.getComplexIntReal(),
4475                    SubobjType->castAs<ComplexType>()->getElementType()
4476                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4477     case APValue::ComplexFloat:
4478       return found(Subobj.getComplexFloatReal(),
4479                    SubobjType->castAs<ComplexType>()->getElementType()
4480                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4481     case APValue::LValue:
4482       return foundPointer(Subobj, SubobjType);
4483     default:
4484       // FIXME: can this happen?
4485       Info.FFDiag(E);
4486       return false;
4487     }
4488   }
4489   bool found(APSInt &Value, QualType SubobjType) {
4490     if (!checkConst(SubobjType))
4491       return false;
4492 
4493     if (!SubobjType->isIntegerType()) {
4494       // We don't support increment / decrement on integer-cast-to-pointer
4495       // values.
4496       Info.FFDiag(E);
4497       return false;
4498     }
4499 
4500     if (Old) *Old = APValue(Value);
4501 
4502     // bool arithmetic promotes to int, and the conversion back to bool
4503     // doesn't reduce mod 2^n, so special-case it.
4504     if (SubobjType->isBooleanType()) {
4505       if (AccessKind == AK_Increment)
4506         Value = 1;
4507       else
4508         Value = !Value;
4509       return true;
4510     }
4511 
4512     bool WasNegative = Value.isNegative();
4513     if (AccessKind == AK_Increment) {
4514       ++Value;
4515 
4516       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4517         APSInt ActualValue(Value, /*IsUnsigned*/true);
4518         return HandleOverflow(Info, E, ActualValue, SubobjType);
4519       }
4520     } else {
4521       --Value;
4522 
4523       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4524         unsigned BitWidth = Value.getBitWidth();
4525         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4526         ActualValue.setBit(BitWidth);
4527         return HandleOverflow(Info, E, ActualValue, SubobjType);
4528       }
4529     }
4530     return true;
4531   }
4532   bool found(APFloat &Value, QualType SubobjType) {
4533     if (!checkConst(SubobjType))
4534       return false;
4535 
4536     if (Old) *Old = APValue(Value);
4537 
4538     APFloat One(Value.getSemantics(), 1);
4539     if (AccessKind == AK_Increment)
4540       Value.add(One, APFloat::rmNearestTiesToEven);
4541     else
4542       Value.subtract(One, APFloat::rmNearestTiesToEven);
4543     return true;
4544   }
4545   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4546     if (!checkConst(SubobjType))
4547       return false;
4548 
4549     QualType PointeeType;
4550     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4551       PointeeType = PT->getPointeeType();
4552     else {
4553       Info.FFDiag(E);
4554       return false;
4555     }
4556 
4557     LValue LVal;
4558     LVal.setFrom(Info.Ctx, Subobj);
4559     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4560                                      AccessKind == AK_Increment ? 1 : -1))
4561       return false;
4562     LVal.moveInto(Subobj);
4563     return true;
4564   }
4565 };
4566 } // end anonymous namespace
4567 
4568 /// Perform an increment or decrement on LVal.
4569 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4570                          QualType LValType, bool IsIncrement, APValue *Old) {
4571   if (LVal.Designator.Invalid)
4572     return false;
4573 
4574   if (!Info.getLangOpts().CPlusPlus14) {
4575     Info.FFDiag(E);
4576     return false;
4577   }
4578 
4579   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4580   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4581   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4582   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4583 }
4584 
4585 /// Build an lvalue for the object argument of a member function call.
4586 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4587                                    LValue &This) {
4588   if (Object->getType()->isPointerType() && Object->isPRValue())
4589     return EvaluatePointer(Object, This, Info);
4590 
4591   if (Object->isGLValue())
4592     return EvaluateLValue(Object, This, Info);
4593 
4594   if (Object->getType()->isLiteralType(Info.Ctx))
4595     return EvaluateTemporary(Object, This, Info);
4596 
4597   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4598   return false;
4599 }
4600 
4601 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4602 /// lvalue referring to the result.
4603 ///
4604 /// \param Info - Information about the ongoing evaluation.
4605 /// \param LV - An lvalue referring to the base of the member pointer.
4606 /// \param RHS - The member pointer expression.
4607 /// \param IncludeMember - Specifies whether the member itself is included in
4608 ///        the resulting LValue subobject designator. This is not possible when
4609 ///        creating a bound member function.
4610 /// \return The field or method declaration to which the member pointer refers,
4611 ///         or 0 if evaluation fails.
4612 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4613                                                   QualType LVType,
4614                                                   LValue &LV,
4615                                                   const Expr *RHS,
4616                                                   bool IncludeMember = true) {
4617   MemberPtr MemPtr;
4618   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4619     return nullptr;
4620 
4621   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4622   // member value, the behavior is undefined.
4623   if (!MemPtr.getDecl()) {
4624     // FIXME: Specific diagnostic.
4625     Info.FFDiag(RHS);
4626     return nullptr;
4627   }
4628 
4629   if (MemPtr.isDerivedMember()) {
4630     // This is a member of some derived class. Truncate LV appropriately.
4631     // The end of the derived-to-base path for the base object must match the
4632     // derived-to-base path for the member pointer.
4633     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4634         LV.Designator.Entries.size()) {
4635       Info.FFDiag(RHS);
4636       return nullptr;
4637     }
4638     unsigned PathLengthToMember =
4639         LV.Designator.Entries.size() - MemPtr.Path.size();
4640     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4641       const CXXRecordDecl *LVDecl = getAsBaseClass(
4642           LV.Designator.Entries[PathLengthToMember + I]);
4643       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4644       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4645         Info.FFDiag(RHS);
4646         return nullptr;
4647       }
4648     }
4649 
4650     // Truncate the lvalue to the appropriate derived class.
4651     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4652                             PathLengthToMember))
4653       return nullptr;
4654   } else if (!MemPtr.Path.empty()) {
4655     // Extend the LValue path with the member pointer's path.
4656     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4657                                   MemPtr.Path.size() + IncludeMember);
4658 
4659     // Walk down to the appropriate base class.
4660     if (const PointerType *PT = LVType->getAs<PointerType>())
4661       LVType = PT->getPointeeType();
4662     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4663     assert(RD && "member pointer access on non-class-type expression");
4664     // The first class in the path is that of the lvalue.
4665     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4666       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4667       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4668         return nullptr;
4669       RD = Base;
4670     }
4671     // Finally cast to the class containing the member.
4672     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4673                                 MemPtr.getContainingRecord()))
4674       return nullptr;
4675   }
4676 
4677   // Add the member. Note that we cannot build bound member functions here.
4678   if (IncludeMember) {
4679     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4680       if (!HandleLValueMember(Info, RHS, LV, FD))
4681         return nullptr;
4682     } else if (const IndirectFieldDecl *IFD =
4683                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4684       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4685         return nullptr;
4686     } else {
4687       llvm_unreachable("can't construct reference to bound member function");
4688     }
4689   }
4690 
4691   return MemPtr.getDecl();
4692 }
4693 
4694 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4695                                                   const BinaryOperator *BO,
4696                                                   LValue &LV,
4697                                                   bool IncludeMember = true) {
4698   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4699 
4700   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4701     if (Info.noteFailure()) {
4702       MemberPtr MemPtr;
4703       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4704     }
4705     return nullptr;
4706   }
4707 
4708   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4709                                    BO->getRHS(), IncludeMember);
4710 }
4711 
4712 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4713 /// the provided lvalue, which currently refers to the base object.
4714 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4715                                     LValue &Result) {
4716   SubobjectDesignator &D = Result.Designator;
4717   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4718     return false;
4719 
4720   QualType TargetQT = E->getType();
4721   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4722     TargetQT = PT->getPointeeType();
4723 
4724   // Check this cast lands within the final derived-to-base subobject path.
4725   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4726     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4727       << D.MostDerivedType << TargetQT;
4728     return false;
4729   }
4730 
4731   // Check the type of the final cast. We don't need to check the path,
4732   // since a cast can only be formed if the path is unique.
4733   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4734   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4735   const CXXRecordDecl *FinalType;
4736   if (NewEntriesSize == D.MostDerivedPathLength)
4737     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4738   else
4739     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4740   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4741     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4742       << D.MostDerivedType << TargetQT;
4743     return false;
4744   }
4745 
4746   // Truncate the lvalue to the appropriate derived class.
4747   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4748 }
4749 
4750 /// Get the value to use for a default-initialized object of type T.
4751 /// Return false if it encounters something invalid.
4752 static bool getDefaultInitValue(QualType T, APValue &Result) {
4753   bool Success = true;
4754   if (auto *RD = T->getAsCXXRecordDecl()) {
4755     if (RD->isInvalidDecl()) {
4756       Result = APValue();
4757       return false;
4758     }
4759     if (RD->isUnion()) {
4760       Result = APValue((const FieldDecl *)nullptr);
4761       return true;
4762     }
4763     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4764                      std::distance(RD->field_begin(), RD->field_end()));
4765 
4766     unsigned Index = 0;
4767     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4768                                                   End = RD->bases_end();
4769          I != End; ++I, ++Index)
4770       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4771 
4772     for (const auto *I : RD->fields()) {
4773       if (I->isUnnamedBitfield())
4774         continue;
4775       Success &= getDefaultInitValue(I->getType(),
4776                                      Result.getStructField(I->getFieldIndex()));
4777     }
4778     return Success;
4779   }
4780 
4781   if (auto *AT =
4782           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4783     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4784     if (Result.hasArrayFiller())
4785       Success &=
4786           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4787 
4788     return Success;
4789   }
4790 
4791   Result = APValue::IndeterminateValue();
4792   return true;
4793 }
4794 
4795 namespace {
4796 enum EvalStmtResult {
4797   /// Evaluation failed.
4798   ESR_Failed,
4799   /// Hit a 'return' statement.
4800   ESR_Returned,
4801   /// Evaluation succeeded.
4802   ESR_Succeeded,
4803   /// Hit a 'continue' statement.
4804   ESR_Continue,
4805   /// Hit a 'break' statement.
4806   ESR_Break,
4807   /// Still scanning for 'case' or 'default' statement.
4808   ESR_CaseNotFound
4809 };
4810 }
4811 
4812 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4813   // We don't need to evaluate the initializer for a static local.
4814   if (!VD->hasLocalStorage())
4815     return true;
4816 
4817   LValue Result;
4818   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4819                                                    ScopeKind::Block, Result);
4820 
4821   const Expr *InitE = VD->getInit();
4822   if (!InitE) {
4823     if (VD->getType()->isDependentType())
4824       return Info.noteSideEffect();
4825     return getDefaultInitValue(VD->getType(), Val);
4826   }
4827   if (InitE->isValueDependent())
4828     return false;
4829 
4830   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4831     // Wipe out any partially-computed value, to allow tracking that this
4832     // evaluation failed.
4833     Val = APValue();
4834     return false;
4835   }
4836 
4837   return true;
4838 }
4839 
4840 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4841   bool OK = true;
4842 
4843   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4844     OK &= EvaluateVarDecl(Info, VD);
4845 
4846   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4847     for (auto *BD : DD->bindings())
4848       if (auto *VD = BD->getHoldingVar())
4849         OK &= EvaluateDecl(Info, VD);
4850 
4851   return OK;
4852 }
4853 
4854 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4855   assert(E->isValueDependent());
4856   if (Info.noteSideEffect())
4857     return true;
4858   assert(E->containsErrors() && "valid value-dependent expression should never "
4859                                 "reach invalid code path.");
4860   return false;
4861 }
4862 
4863 /// Evaluate a condition (either a variable declaration or an expression).
4864 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4865                          const Expr *Cond, bool &Result) {
4866   if (Cond->isValueDependent())
4867     return false;
4868   FullExpressionRAII Scope(Info);
4869   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4870     return false;
4871   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4872     return false;
4873   return Scope.destroy();
4874 }
4875 
4876 namespace {
4877 /// A location where the result (returned value) of evaluating a
4878 /// statement should be stored.
4879 struct StmtResult {
4880   /// The APValue that should be filled in with the returned value.
4881   APValue &Value;
4882   /// The location containing the result, if any (used to support RVO).
4883   const LValue *Slot;
4884 };
4885 
4886 struct TempVersionRAII {
4887   CallStackFrame &Frame;
4888 
4889   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4890     Frame.pushTempVersion();
4891   }
4892 
4893   ~TempVersionRAII() {
4894     Frame.popTempVersion();
4895   }
4896 };
4897 
4898 }
4899 
4900 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4901                                    const Stmt *S,
4902                                    const SwitchCase *SC = nullptr);
4903 
4904 /// Evaluate the body of a loop, and translate the result as appropriate.
4905 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4906                                        const Stmt *Body,
4907                                        const SwitchCase *Case = nullptr) {
4908   BlockScopeRAII Scope(Info);
4909 
4910   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4911   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4912     ESR = ESR_Failed;
4913 
4914   switch (ESR) {
4915   case ESR_Break:
4916     return ESR_Succeeded;
4917   case ESR_Succeeded:
4918   case ESR_Continue:
4919     return ESR_Continue;
4920   case ESR_Failed:
4921   case ESR_Returned:
4922   case ESR_CaseNotFound:
4923     return ESR;
4924   }
4925   llvm_unreachable("Invalid EvalStmtResult!");
4926 }
4927 
4928 /// Evaluate a switch statement.
4929 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4930                                      const SwitchStmt *SS) {
4931   BlockScopeRAII Scope(Info);
4932 
4933   // Evaluate the switch condition.
4934   APSInt Value;
4935   {
4936     if (const Stmt *Init = SS->getInit()) {
4937       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4938       if (ESR != ESR_Succeeded) {
4939         if (ESR != ESR_Failed && !Scope.destroy())
4940           ESR = ESR_Failed;
4941         return ESR;
4942       }
4943     }
4944 
4945     FullExpressionRAII CondScope(Info);
4946     if (SS->getConditionVariable() &&
4947         !EvaluateDecl(Info, SS->getConditionVariable()))
4948       return ESR_Failed;
4949     if (SS->getCond()->isValueDependent()) {
4950       if (!EvaluateDependentExpr(SS->getCond(), Info))
4951         return ESR_Failed;
4952     } else {
4953       if (!EvaluateInteger(SS->getCond(), Value, Info))
4954         return ESR_Failed;
4955     }
4956     if (!CondScope.destroy())
4957       return ESR_Failed;
4958   }
4959 
4960   // Find the switch case corresponding to the value of the condition.
4961   // FIXME: Cache this lookup.
4962   const SwitchCase *Found = nullptr;
4963   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4964        SC = SC->getNextSwitchCase()) {
4965     if (isa<DefaultStmt>(SC)) {
4966       Found = SC;
4967       continue;
4968     }
4969 
4970     const CaseStmt *CS = cast<CaseStmt>(SC);
4971     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4972     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4973                               : LHS;
4974     if (LHS <= Value && Value <= RHS) {
4975       Found = SC;
4976       break;
4977     }
4978   }
4979 
4980   if (!Found)
4981     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4982 
4983   // Search the switch body for the switch case and evaluate it from there.
4984   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4985   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4986     return ESR_Failed;
4987 
4988   switch (ESR) {
4989   case ESR_Break:
4990     return ESR_Succeeded;
4991   case ESR_Succeeded:
4992   case ESR_Continue:
4993   case ESR_Failed:
4994   case ESR_Returned:
4995     return ESR;
4996   case ESR_CaseNotFound:
4997     // This can only happen if the switch case is nested within a statement
4998     // expression. We have no intention of supporting that.
4999     Info.FFDiag(Found->getBeginLoc(),
5000                 diag::note_constexpr_stmt_expr_unsupported);
5001     return ESR_Failed;
5002   }
5003   llvm_unreachable("Invalid EvalStmtResult!");
5004 }
5005 
5006 // Evaluate a statement.
5007 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5008                                    const Stmt *S, const SwitchCase *Case) {
5009   if (!Info.nextStep(S))
5010     return ESR_Failed;
5011 
5012   // If we're hunting down a 'case' or 'default' label, recurse through
5013   // substatements until we hit the label.
5014   if (Case) {
5015     switch (S->getStmtClass()) {
5016     case Stmt::CompoundStmtClass:
5017       // FIXME: Precompute which substatement of a compound statement we
5018       // would jump to, and go straight there rather than performing a
5019       // linear scan each time.
5020     case Stmt::LabelStmtClass:
5021     case Stmt::AttributedStmtClass:
5022     case Stmt::DoStmtClass:
5023       break;
5024 
5025     case Stmt::CaseStmtClass:
5026     case Stmt::DefaultStmtClass:
5027       if (Case == S)
5028         Case = nullptr;
5029       break;
5030 
5031     case Stmt::IfStmtClass: {
5032       // FIXME: Precompute which side of an 'if' we would jump to, and go
5033       // straight there rather than scanning both sides.
5034       const IfStmt *IS = cast<IfStmt>(S);
5035 
5036       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5037       // preceded by our switch label.
5038       BlockScopeRAII Scope(Info);
5039 
5040       // Step into the init statement in case it brings an (uninitialized)
5041       // variable into scope.
5042       if (const Stmt *Init = IS->getInit()) {
5043         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5044         if (ESR != ESR_CaseNotFound) {
5045           assert(ESR != ESR_Succeeded);
5046           return ESR;
5047         }
5048       }
5049 
5050       // Condition variable must be initialized if it exists.
5051       // FIXME: We can skip evaluating the body if there's a condition
5052       // variable, as there can't be any case labels within it.
5053       // (The same is true for 'for' statements.)
5054 
5055       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5056       if (ESR == ESR_Failed)
5057         return ESR;
5058       if (ESR != ESR_CaseNotFound)
5059         return Scope.destroy() ? ESR : ESR_Failed;
5060       if (!IS->getElse())
5061         return ESR_CaseNotFound;
5062 
5063       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5064       if (ESR == ESR_Failed)
5065         return ESR;
5066       if (ESR != ESR_CaseNotFound)
5067         return Scope.destroy() ? ESR : ESR_Failed;
5068       return ESR_CaseNotFound;
5069     }
5070 
5071     case Stmt::WhileStmtClass: {
5072       EvalStmtResult ESR =
5073           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5074       if (ESR != ESR_Continue)
5075         return ESR;
5076       break;
5077     }
5078 
5079     case Stmt::ForStmtClass: {
5080       const ForStmt *FS = cast<ForStmt>(S);
5081       BlockScopeRAII Scope(Info);
5082 
5083       // Step into the init statement in case it brings an (uninitialized)
5084       // variable into scope.
5085       if (const Stmt *Init = FS->getInit()) {
5086         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5087         if (ESR != ESR_CaseNotFound) {
5088           assert(ESR != ESR_Succeeded);
5089           return ESR;
5090         }
5091       }
5092 
5093       EvalStmtResult ESR =
5094           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5095       if (ESR != ESR_Continue)
5096         return ESR;
5097       if (const auto *Inc = FS->getInc()) {
5098         if (Inc->isValueDependent()) {
5099           if (!EvaluateDependentExpr(Inc, Info))
5100             return ESR_Failed;
5101         } else {
5102           FullExpressionRAII IncScope(Info);
5103           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5104             return ESR_Failed;
5105         }
5106       }
5107       break;
5108     }
5109 
5110     case Stmt::DeclStmtClass: {
5111       // Start the lifetime of any uninitialized variables we encounter. They
5112       // might be used by the selected branch of the switch.
5113       const DeclStmt *DS = cast<DeclStmt>(S);
5114       for (const auto *D : DS->decls()) {
5115         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5116           if (VD->hasLocalStorage() && !VD->getInit())
5117             if (!EvaluateVarDecl(Info, VD))
5118               return ESR_Failed;
5119           // FIXME: If the variable has initialization that can't be jumped
5120           // over, bail out of any immediately-surrounding compound-statement
5121           // too. There can't be any case labels here.
5122         }
5123       }
5124       return ESR_CaseNotFound;
5125     }
5126 
5127     default:
5128       return ESR_CaseNotFound;
5129     }
5130   }
5131 
5132   switch (S->getStmtClass()) {
5133   default:
5134     if (const Expr *E = dyn_cast<Expr>(S)) {
5135       if (E->isValueDependent()) {
5136         if (!EvaluateDependentExpr(E, Info))
5137           return ESR_Failed;
5138       } else {
5139         // Don't bother evaluating beyond an expression-statement which couldn't
5140         // be evaluated.
5141         // FIXME: Do we need the FullExpressionRAII object here?
5142         // VisitExprWithCleanups should create one when necessary.
5143         FullExpressionRAII Scope(Info);
5144         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5145           return ESR_Failed;
5146       }
5147       return ESR_Succeeded;
5148     }
5149 
5150     Info.FFDiag(S->getBeginLoc());
5151     return ESR_Failed;
5152 
5153   case Stmt::NullStmtClass:
5154     return ESR_Succeeded;
5155 
5156   case Stmt::DeclStmtClass: {
5157     const DeclStmt *DS = cast<DeclStmt>(S);
5158     for (const auto *D : DS->decls()) {
5159       // Each declaration initialization is its own full-expression.
5160       FullExpressionRAII Scope(Info);
5161       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5162         return ESR_Failed;
5163       if (!Scope.destroy())
5164         return ESR_Failed;
5165     }
5166     return ESR_Succeeded;
5167   }
5168 
5169   case Stmt::ReturnStmtClass: {
5170     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5171     FullExpressionRAII Scope(Info);
5172     if (RetExpr && RetExpr->isValueDependent()) {
5173       EvaluateDependentExpr(RetExpr, Info);
5174       // We know we returned, but we don't know what the value is.
5175       return ESR_Failed;
5176     }
5177     if (RetExpr &&
5178         !(Result.Slot
5179               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5180               : Evaluate(Result.Value, Info, RetExpr)))
5181       return ESR_Failed;
5182     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5183   }
5184 
5185   case Stmt::CompoundStmtClass: {
5186     BlockScopeRAII Scope(Info);
5187 
5188     const CompoundStmt *CS = cast<CompoundStmt>(S);
5189     for (const auto *BI : CS->body()) {
5190       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5191       if (ESR == ESR_Succeeded)
5192         Case = nullptr;
5193       else if (ESR != ESR_CaseNotFound) {
5194         if (ESR != ESR_Failed && !Scope.destroy())
5195           return ESR_Failed;
5196         return ESR;
5197       }
5198     }
5199     if (Case)
5200       return ESR_CaseNotFound;
5201     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5202   }
5203 
5204   case Stmt::IfStmtClass: {
5205     const IfStmt *IS = cast<IfStmt>(S);
5206 
5207     // Evaluate the condition, as either a var decl or as an expression.
5208     BlockScopeRAII Scope(Info);
5209     if (const Stmt *Init = IS->getInit()) {
5210       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5211       if (ESR != ESR_Succeeded) {
5212         if (ESR != ESR_Failed && !Scope.destroy())
5213           return ESR_Failed;
5214         return ESR;
5215       }
5216     }
5217     bool Cond;
5218     if (IS->isConsteval())
5219       Cond = IS->isNonNegatedConsteval();
5220     else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5221                            Cond))
5222       return ESR_Failed;
5223 
5224     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5225       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5226       if (ESR != ESR_Succeeded) {
5227         if (ESR != ESR_Failed && !Scope.destroy())
5228           return ESR_Failed;
5229         return ESR;
5230       }
5231     }
5232     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5233   }
5234 
5235   case Stmt::WhileStmtClass: {
5236     const WhileStmt *WS = cast<WhileStmt>(S);
5237     while (true) {
5238       BlockScopeRAII Scope(Info);
5239       bool Continue;
5240       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5241                         Continue))
5242         return ESR_Failed;
5243       if (!Continue)
5244         break;
5245 
5246       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5247       if (ESR != ESR_Continue) {
5248         if (ESR != ESR_Failed && !Scope.destroy())
5249           return ESR_Failed;
5250         return ESR;
5251       }
5252       if (!Scope.destroy())
5253         return ESR_Failed;
5254     }
5255     return ESR_Succeeded;
5256   }
5257 
5258   case Stmt::DoStmtClass: {
5259     const DoStmt *DS = cast<DoStmt>(S);
5260     bool Continue;
5261     do {
5262       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5263       if (ESR != ESR_Continue)
5264         return ESR;
5265       Case = nullptr;
5266 
5267       if (DS->getCond()->isValueDependent()) {
5268         EvaluateDependentExpr(DS->getCond(), Info);
5269         // Bailout as we don't know whether to keep going or terminate the loop.
5270         return ESR_Failed;
5271       }
5272       FullExpressionRAII CondScope(Info);
5273       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5274           !CondScope.destroy())
5275         return ESR_Failed;
5276     } while (Continue);
5277     return ESR_Succeeded;
5278   }
5279 
5280   case Stmt::ForStmtClass: {
5281     const ForStmt *FS = cast<ForStmt>(S);
5282     BlockScopeRAII ForScope(Info);
5283     if (FS->getInit()) {
5284       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5285       if (ESR != ESR_Succeeded) {
5286         if (ESR != ESR_Failed && !ForScope.destroy())
5287           return ESR_Failed;
5288         return ESR;
5289       }
5290     }
5291     while (true) {
5292       BlockScopeRAII IterScope(Info);
5293       bool Continue = true;
5294       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5295                                          FS->getCond(), Continue))
5296         return ESR_Failed;
5297       if (!Continue)
5298         break;
5299 
5300       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5301       if (ESR != ESR_Continue) {
5302         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5303           return ESR_Failed;
5304         return ESR;
5305       }
5306 
5307       if (const auto *Inc = FS->getInc()) {
5308         if (Inc->isValueDependent()) {
5309           if (!EvaluateDependentExpr(Inc, Info))
5310             return ESR_Failed;
5311         } else {
5312           FullExpressionRAII IncScope(Info);
5313           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5314             return ESR_Failed;
5315         }
5316       }
5317 
5318       if (!IterScope.destroy())
5319         return ESR_Failed;
5320     }
5321     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5322   }
5323 
5324   case Stmt::CXXForRangeStmtClass: {
5325     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5326     BlockScopeRAII Scope(Info);
5327 
5328     // Evaluate the init-statement if present.
5329     if (FS->getInit()) {
5330       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5331       if (ESR != ESR_Succeeded) {
5332         if (ESR != ESR_Failed && !Scope.destroy())
5333           return ESR_Failed;
5334         return ESR;
5335       }
5336     }
5337 
5338     // Initialize the __range variable.
5339     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5340     if (ESR != ESR_Succeeded) {
5341       if (ESR != ESR_Failed && !Scope.destroy())
5342         return ESR_Failed;
5343       return ESR;
5344     }
5345 
5346     // In error-recovery cases it's possible to get here even if we failed to
5347     // synthesize the __begin and __end variables.
5348     if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5349       return ESR_Failed;
5350 
5351     // Create the __begin and __end iterators.
5352     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5353     if (ESR != ESR_Succeeded) {
5354       if (ESR != ESR_Failed && !Scope.destroy())
5355         return ESR_Failed;
5356       return ESR;
5357     }
5358     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5359     if (ESR != ESR_Succeeded) {
5360       if (ESR != ESR_Failed && !Scope.destroy())
5361         return ESR_Failed;
5362       return ESR;
5363     }
5364 
5365     while (true) {
5366       // Condition: __begin != __end.
5367       {
5368         if (FS->getCond()->isValueDependent()) {
5369           EvaluateDependentExpr(FS->getCond(), Info);
5370           // We don't know whether to keep going or terminate the loop.
5371           return ESR_Failed;
5372         }
5373         bool Continue = true;
5374         FullExpressionRAII CondExpr(Info);
5375         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5376           return ESR_Failed;
5377         if (!Continue)
5378           break;
5379       }
5380 
5381       // User's variable declaration, initialized by *__begin.
5382       BlockScopeRAII InnerScope(Info);
5383       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5384       if (ESR != ESR_Succeeded) {
5385         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5386           return ESR_Failed;
5387         return ESR;
5388       }
5389 
5390       // Loop body.
5391       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5392       if (ESR != ESR_Continue) {
5393         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5394           return ESR_Failed;
5395         return ESR;
5396       }
5397       if (FS->getInc()->isValueDependent()) {
5398         if (!EvaluateDependentExpr(FS->getInc(), Info))
5399           return ESR_Failed;
5400       } else {
5401         // Increment: ++__begin
5402         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5403           return ESR_Failed;
5404       }
5405 
5406       if (!InnerScope.destroy())
5407         return ESR_Failed;
5408     }
5409 
5410     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5411   }
5412 
5413   case Stmt::SwitchStmtClass:
5414     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5415 
5416   case Stmt::ContinueStmtClass:
5417     return ESR_Continue;
5418 
5419   case Stmt::BreakStmtClass:
5420     return ESR_Break;
5421 
5422   case Stmt::LabelStmtClass:
5423     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5424 
5425   case Stmt::AttributedStmtClass:
5426     // As a general principle, C++11 attributes can be ignored without
5427     // any semantic impact.
5428     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5429                         Case);
5430 
5431   case Stmt::CaseStmtClass:
5432   case Stmt::DefaultStmtClass:
5433     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5434   case Stmt::CXXTryStmtClass:
5435     // Evaluate try blocks by evaluating all sub statements.
5436     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5437   }
5438 }
5439 
5440 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5441 /// default constructor. If so, we'll fold it whether or not it's marked as
5442 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5443 /// so we need special handling.
5444 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5445                                            const CXXConstructorDecl *CD,
5446                                            bool IsValueInitialization) {
5447   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5448     return false;
5449 
5450   // Value-initialization does not call a trivial default constructor, so such a
5451   // call is a core constant expression whether or not the constructor is
5452   // constexpr.
5453   if (!CD->isConstexpr() && !IsValueInitialization) {
5454     if (Info.getLangOpts().CPlusPlus11) {
5455       // FIXME: If DiagDecl is an implicitly-declared special member function,
5456       // we should be much more explicit about why it's not constexpr.
5457       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5458         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5459       Info.Note(CD->getLocation(), diag::note_declared_at);
5460     } else {
5461       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5462     }
5463   }
5464   return true;
5465 }
5466 
5467 /// CheckConstexprFunction - Check that a function can be called in a constant
5468 /// expression.
5469 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5470                                    const FunctionDecl *Declaration,
5471                                    const FunctionDecl *Definition,
5472                                    const Stmt *Body) {
5473   // Potential constant expressions can contain calls to declared, but not yet
5474   // defined, constexpr functions.
5475   if (Info.checkingPotentialConstantExpression() && !Definition &&
5476       Declaration->isConstexpr())
5477     return false;
5478 
5479   // Bail out if the function declaration itself is invalid.  We will
5480   // have produced a relevant diagnostic while parsing it, so just
5481   // note the problematic sub-expression.
5482   if (Declaration->isInvalidDecl()) {
5483     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5484     return false;
5485   }
5486 
5487   // DR1872: An instantiated virtual constexpr function can't be called in a
5488   // constant expression (prior to C++20). We can still constant-fold such a
5489   // call.
5490   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5491       cast<CXXMethodDecl>(Declaration)->isVirtual())
5492     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5493 
5494   if (Definition && Definition->isInvalidDecl()) {
5495     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5496     return false;
5497   }
5498 
5499   // Can we evaluate this function call?
5500   if (Definition && Definition->isConstexpr() && Body)
5501     return true;
5502 
5503   if (Info.getLangOpts().CPlusPlus11) {
5504     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5505 
5506     // If this function is not constexpr because it is an inherited
5507     // non-constexpr constructor, diagnose that directly.
5508     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5509     if (CD && CD->isInheritingConstructor()) {
5510       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5511       if (!Inherited->isConstexpr())
5512         DiagDecl = CD = Inherited;
5513     }
5514 
5515     // FIXME: If DiagDecl is an implicitly-declared special member function
5516     // or an inheriting constructor, we should be much more explicit about why
5517     // it's not constexpr.
5518     if (CD && CD->isInheritingConstructor())
5519       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5520         << CD->getInheritedConstructor().getConstructor()->getParent();
5521     else
5522       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5523         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5524     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5525   } else {
5526     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5527   }
5528   return false;
5529 }
5530 
5531 namespace {
5532 struct CheckDynamicTypeHandler {
5533   AccessKinds AccessKind;
5534   typedef bool result_type;
5535   bool failed() { return false; }
5536   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5537   bool found(APSInt &Value, QualType SubobjType) { return true; }
5538   bool found(APFloat &Value, QualType SubobjType) { return true; }
5539 };
5540 } // end anonymous namespace
5541 
5542 /// Check that we can access the notional vptr of an object / determine its
5543 /// dynamic type.
5544 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5545                              AccessKinds AK, bool Polymorphic) {
5546   if (This.Designator.Invalid)
5547     return false;
5548 
5549   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5550 
5551   if (!Obj)
5552     return false;
5553 
5554   if (!Obj.Value) {
5555     // The object is not usable in constant expressions, so we can't inspect
5556     // its value to see if it's in-lifetime or what the active union members
5557     // are. We can still check for a one-past-the-end lvalue.
5558     if (This.Designator.isOnePastTheEnd() ||
5559         This.Designator.isMostDerivedAnUnsizedArray()) {
5560       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5561                          ? diag::note_constexpr_access_past_end
5562                          : diag::note_constexpr_access_unsized_array)
5563           << AK;
5564       return false;
5565     } else if (Polymorphic) {
5566       // Conservatively refuse to perform a polymorphic operation if we would
5567       // not be able to read a notional 'vptr' value.
5568       APValue Val;
5569       This.moveInto(Val);
5570       QualType StarThisType =
5571           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5572       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5573           << AK << Val.getAsString(Info.Ctx, StarThisType);
5574       return false;
5575     }
5576     return true;
5577   }
5578 
5579   CheckDynamicTypeHandler Handler{AK};
5580   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5581 }
5582 
5583 /// Check that the pointee of the 'this' pointer in a member function call is
5584 /// either within its lifetime or in its period of construction or destruction.
5585 static bool
5586 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5587                                      const LValue &This,
5588                                      const CXXMethodDecl *NamedMember) {
5589   return checkDynamicType(
5590       Info, E, This,
5591       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5592 }
5593 
5594 struct DynamicType {
5595   /// The dynamic class type of the object.
5596   const CXXRecordDecl *Type;
5597   /// The corresponding path length in the lvalue.
5598   unsigned PathLength;
5599 };
5600 
5601 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5602                                              unsigned PathLength) {
5603   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5604       Designator.Entries.size() && "invalid path length");
5605   return (PathLength == Designator.MostDerivedPathLength)
5606              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5607              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5608 }
5609 
5610 /// Determine the dynamic type of an object.
5611 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5612                                                 LValue &This, AccessKinds AK) {
5613   // If we don't have an lvalue denoting an object of class type, there is no
5614   // meaningful dynamic type. (We consider objects of non-class type to have no
5615   // dynamic type.)
5616   if (!checkDynamicType(Info, E, This, AK, true))
5617     return None;
5618 
5619   // Refuse to compute a dynamic type in the presence of virtual bases. This
5620   // shouldn't happen other than in constant-folding situations, since literal
5621   // types can't have virtual bases.
5622   //
5623   // Note that consumers of DynamicType assume that the type has no virtual
5624   // bases, and will need modifications if this restriction is relaxed.
5625   const CXXRecordDecl *Class =
5626       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5627   if (!Class || Class->getNumVBases()) {
5628     Info.FFDiag(E);
5629     return None;
5630   }
5631 
5632   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5633   // binary search here instead. But the overwhelmingly common case is that
5634   // we're not in the middle of a constructor, so it probably doesn't matter
5635   // in practice.
5636   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5637   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5638        PathLength <= Path.size(); ++PathLength) {
5639     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5640                                       Path.slice(0, PathLength))) {
5641     case ConstructionPhase::Bases:
5642     case ConstructionPhase::DestroyingBases:
5643       // We're constructing or destroying a base class. This is not the dynamic
5644       // type.
5645       break;
5646 
5647     case ConstructionPhase::None:
5648     case ConstructionPhase::AfterBases:
5649     case ConstructionPhase::AfterFields:
5650     case ConstructionPhase::Destroying:
5651       // We've finished constructing the base classes and not yet started
5652       // destroying them again, so this is the dynamic type.
5653       return DynamicType{getBaseClassType(This.Designator, PathLength),
5654                          PathLength};
5655     }
5656   }
5657 
5658   // CWG issue 1517: we're constructing a base class of the object described by
5659   // 'This', so that object has not yet begun its period of construction and
5660   // any polymorphic operation on it results in undefined behavior.
5661   Info.FFDiag(E);
5662   return None;
5663 }
5664 
5665 /// Perform virtual dispatch.
5666 static const CXXMethodDecl *HandleVirtualDispatch(
5667     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5668     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5669   Optional<DynamicType> DynType = ComputeDynamicType(
5670       Info, E, This,
5671       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5672   if (!DynType)
5673     return nullptr;
5674 
5675   // Find the final overrider. It must be declared in one of the classes on the
5676   // path from the dynamic type to the static type.
5677   // FIXME: If we ever allow literal types to have virtual base classes, that
5678   // won't be true.
5679   const CXXMethodDecl *Callee = Found;
5680   unsigned PathLength = DynType->PathLength;
5681   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5682     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5683     const CXXMethodDecl *Overrider =
5684         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5685     if (Overrider) {
5686       Callee = Overrider;
5687       break;
5688     }
5689   }
5690 
5691   // C++2a [class.abstract]p6:
5692   //   the effect of making a virtual call to a pure virtual function [...] is
5693   //   undefined
5694   if (Callee->isPure()) {
5695     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5696     Info.Note(Callee->getLocation(), diag::note_declared_at);
5697     return nullptr;
5698   }
5699 
5700   // If necessary, walk the rest of the path to determine the sequence of
5701   // covariant adjustment steps to apply.
5702   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5703                                        Found->getReturnType())) {
5704     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5705     for (unsigned CovariantPathLength = PathLength + 1;
5706          CovariantPathLength != This.Designator.Entries.size();
5707          ++CovariantPathLength) {
5708       const CXXRecordDecl *NextClass =
5709           getBaseClassType(This.Designator, CovariantPathLength);
5710       const CXXMethodDecl *Next =
5711           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5712       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5713                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5714         CovariantAdjustmentPath.push_back(Next->getReturnType());
5715     }
5716     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5717                                          CovariantAdjustmentPath.back()))
5718       CovariantAdjustmentPath.push_back(Found->getReturnType());
5719   }
5720 
5721   // Perform 'this' adjustment.
5722   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5723     return nullptr;
5724 
5725   return Callee;
5726 }
5727 
5728 /// Perform the adjustment from a value returned by a virtual function to
5729 /// a value of the statically expected type, which may be a pointer or
5730 /// reference to a base class of the returned type.
5731 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5732                                             APValue &Result,
5733                                             ArrayRef<QualType> Path) {
5734   assert(Result.isLValue() &&
5735          "unexpected kind of APValue for covariant return");
5736   if (Result.isNullPointer())
5737     return true;
5738 
5739   LValue LVal;
5740   LVal.setFrom(Info.Ctx, Result);
5741 
5742   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5743   for (unsigned I = 1; I != Path.size(); ++I) {
5744     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5745     assert(OldClass && NewClass && "unexpected kind of covariant return");
5746     if (OldClass != NewClass &&
5747         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5748       return false;
5749     OldClass = NewClass;
5750   }
5751 
5752   LVal.moveInto(Result);
5753   return true;
5754 }
5755 
5756 /// Determine whether \p Base, which is known to be a direct base class of
5757 /// \p Derived, is a public base class.
5758 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5759                               const CXXRecordDecl *Base) {
5760   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5761     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5762     if (BaseClass && declaresSameEntity(BaseClass, Base))
5763       return BaseSpec.getAccessSpecifier() == AS_public;
5764   }
5765   llvm_unreachable("Base is not a direct base of Derived");
5766 }
5767 
5768 /// Apply the given dynamic cast operation on the provided lvalue.
5769 ///
5770 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5771 /// to find a suitable target subobject.
5772 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5773                               LValue &Ptr) {
5774   // We can't do anything with a non-symbolic pointer value.
5775   SubobjectDesignator &D = Ptr.Designator;
5776   if (D.Invalid)
5777     return false;
5778 
5779   // C++ [expr.dynamic.cast]p6:
5780   //   If v is a null pointer value, the result is a null pointer value.
5781   if (Ptr.isNullPointer() && !E->isGLValue())
5782     return true;
5783 
5784   // For all the other cases, we need the pointer to point to an object within
5785   // its lifetime / period of construction / destruction, and we need to know
5786   // its dynamic type.
5787   Optional<DynamicType> DynType =
5788       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5789   if (!DynType)
5790     return false;
5791 
5792   // C++ [expr.dynamic.cast]p7:
5793   //   If T is "pointer to cv void", then the result is a pointer to the most
5794   //   derived object
5795   if (E->getType()->isVoidPointerType())
5796     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5797 
5798   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5799   assert(C && "dynamic_cast target is not void pointer nor class");
5800   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5801 
5802   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5803     // C++ [expr.dynamic.cast]p9:
5804     if (!E->isGLValue()) {
5805       //   The value of a failed cast to pointer type is the null pointer value
5806       //   of the required result type.
5807       Ptr.setNull(Info.Ctx, E->getType());
5808       return true;
5809     }
5810 
5811     //   A failed cast to reference type throws [...] std::bad_cast.
5812     unsigned DiagKind;
5813     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5814                    DynType->Type->isDerivedFrom(C)))
5815       DiagKind = 0;
5816     else if (!Paths || Paths->begin() == Paths->end())
5817       DiagKind = 1;
5818     else if (Paths->isAmbiguous(CQT))
5819       DiagKind = 2;
5820     else {
5821       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5822       DiagKind = 3;
5823     }
5824     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5825         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5826         << Info.Ctx.getRecordType(DynType->Type)
5827         << E->getType().getUnqualifiedType();
5828     return false;
5829   };
5830 
5831   // Runtime check, phase 1:
5832   //   Walk from the base subobject towards the derived object looking for the
5833   //   target type.
5834   for (int PathLength = Ptr.Designator.Entries.size();
5835        PathLength >= (int)DynType->PathLength; --PathLength) {
5836     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5837     if (declaresSameEntity(Class, C))
5838       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5839     // We can only walk across public inheritance edges.
5840     if (PathLength > (int)DynType->PathLength &&
5841         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5842                            Class))
5843       return RuntimeCheckFailed(nullptr);
5844   }
5845 
5846   // Runtime check, phase 2:
5847   //   Search the dynamic type for an unambiguous public base of type C.
5848   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5849                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5850   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5851       Paths.front().Access == AS_public) {
5852     // Downcast to the dynamic type...
5853     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5854       return false;
5855     // ... then upcast to the chosen base class subobject.
5856     for (CXXBasePathElement &Elem : Paths.front())
5857       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5858         return false;
5859     return true;
5860   }
5861 
5862   // Otherwise, the runtime check fails.
5863   return RuntimeCheckFailed(&Paths);
5864 }
5865 
5866 namespace {
5867 struct StartLifetimeOfUnionMemberHandler {
5868   EvalInfo &Info;
5869   const Expr *LHSExpr;
5870   const FieldDecl *Field;
5871   bool DuringInit;
5872   bool Failed = false;
5873   static const AccessKinds AccessKind = AK_Assign;
5874 
5875   typedef bool result_type;
5876   bool failed() { return Failed; }
5877   bool found(APValue &Subobj, QualType SubobjType) {
5878     // We are supposed to perform no initialization but begin the lifetime of
5879     // the object. We interpret that as meaning to do what default
5880     // initialization of the object would do if all constructors involved were
5881     // trivial:
5882     //  * All base, non-variant member, and array element subobjects' lifetimes
5883     //    begin
5884     //  * No variant members' lifetimes begin
5885     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5886     assert(SubobjType->isUnionType());
5887     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5888       // This union member is already active. If it's also in-lifetime, there's
5889       // nothing to do.
5890       if (Subobj.getUnionValue().hasValue())
5891         return true;
5892     } else if (DuringInit) {
5893       // We're currently in the process of initializing a different union
5894       // member.  If we carried on, that initialization would attempt to
5895       // store to an inactive union member, resulting in undefined behavior.
5896       Info.FFDiag(LHSExpr,
5897                   diag::note_constexpr_union_member_change_during_init);
5898       return false;
5899     }
5900     APValue Result;
5901     Failed = !getDefaultInitValue(Field->getType(), Result);
5902     Subobj.setUnion(Field, Result);
5903     return true;
5904   }
5905   bool found(APSInt &Value, QualType SubobjType) {
5906     llvm_unreachable("wrong value kind for union object");
5907   }
5908   bool found(APFloat &Value, QualType SubobjType) {
5909     llvm_unreachable("wrong value kind for union object");
5910   }
5911 };
5912 } // end anonymous namespace
5913 
5914 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5915 
5916 /// Handle a builtin simple-assignment or a call to a trivial assignment
5917 /// operator whose left-hand side might involve a union member access. If it
5918 /// does, implicitly start the lifetime of any accessed union elements per
5919 /// C++20 [class.union]5.
5920 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5921                                           const LValue &LHS) {
5922   if (LHS.InvalidBase || LHS.Designator.Invalid)
5923     return false;
5924 
5925   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5926   // C++ [class.union]p5:
5927   //   define the set S(E) of subexpressions of E as follows:
5928   unsigned PathLength = LHS.Designator.Entries.size();
5929   for (const Expr *E = LHSExpr; E != nullptr;) {
5930     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5931     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5932       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5933       // Note that we can't implicitly start the lifetime of a reference,
5934       // so we don't need to proceed any further if we reach one.
5935       if (!FD || FD->getType()->isReferenceType())
5936         break;
5937 
5938       //    ... and also contains A.B if B names a union member ...
5939       if (FD->getParent()->isUnion()) {
5940         //    ... of a non-class, non-array type, or of a class type with a
5941         //    trivial default constructor that is not deleted, or an array of
5942         //    such types.
5943         auto *RD =
5944             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5945         if (!RD || RD->hasTrivialDefaultConstructor())
5946           UnionPathLengths.push_back({PathLength - 1, FD});
5947       }
5948 
5949       E = ME->getBase();
5950       --PathLength;
5951       assert(declaresSameEntity(FD,
5952                                 LHS.Designator.Entries[PathLength]
5953                                     .getAsBaseOrMember().getPointer()));
5954 
5955       //   -- If E is of the form A[B] and is interpreted as a built-in array
5956       //      subscripting operator, S(E) is [S(the array operand, if any)].
5957     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5958       // Step over an ArrayToPointerDecay implicit cast.
5959       auto *Base = ASE->getBase()->IgnoreImplicit();
5960       if (!Base->getType()->isArrayType())
5961         break;
5962 
5963       E = Base;
5964       --PathLength;
5965 
5966     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5967       // Step over a derived-to-base conversion.
5968       E = ICE->getSubExpr();
5969       if (ICE->getCastKind() == CK_NoOp)
5970         continue;
5971       if (ICE->getCastKind() != CK_DerivedToBase &&
5972           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5973         break;
5974       // Walk path backwards as we walk up from the base to the derived class.
5975       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5976         --PathLength;
5977         (void)Elt;
5978         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5979                                   LHS.Designator.Entries[PathLength]
5980                                       .getAsBaseOrMember().getPointer()));
5981       }
5982 
5983     //   -- Otherwise, S(E) is empty.
5984     } else {
5985       break;
5986     }
5987   }
5988 
5989   // Common case: no unions' lifetimes are started.
5990   if (UnionPathLengths.empty())
5991     return true;
5992 
5993   //   if modification of X [would access an inactive union member], an object
5994   //   of the type of X is implicitly created
5995   CompleteObject Obj =
5996       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5997   if (!Obj)
5998     return false;
5999   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6000            llvm::reverse(UnionPathLengths)) {
6001     // Form a designator for the union object.
6002     SubobjectDesignator D = LHS.Designator;
6003     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6004 
6005     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6006                       ConstructionPhase::AfterBases;
6007     StartLifetimeOfUnionMemberHandler StartLifetime{
6008         Info, LHSExpr, LengthAndField.second, DuringInit};
6009     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6010       return false;
6011   }
6012 
6013   return true;
6014 }
6015 
6016 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6017                             CallRef Call, EvalInfo &Info,
6018                             bool NonNull = false) {
6019   LValue LV;
6020   // Create the parameter slot and register its destruction. For a vararg
6021   // argument, create a temporary.
6022   // FIXME: For calling conventions that destroy parameters in the callee,
6023   // should we consider performing destruction when the function returns
6024   // instead?
6025   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6026                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6027                                                        ScopeKind::Call, LV);
6028   if (!EvaluateInPlace(V, Info, LV, Arg))
6029     return false;
6030 
6031   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6032   // undefined behavior, so is non-constant.
6033   if (NonNull && V.isLValue() && V.isNullPointer()) {
6034     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6035     return false;
6036   }
6037 
6038   return true;
6039 }
6040 
6041 /// Evaluate the arguments to a function call.
6042 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6043                          EvalInfo &Info, const FunctionDecl *Callee,
6044                          bool RightToLeft = false) {
6045   bool Success = true;
6046   llvm::SmallBitVector ForbiddenNullArgs;
6047   if (Callee->hasAttr<NonNullAttr>()) {
6048     ForbiddenNullArgs.resize(Args.size());
6049     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6050       if (!Attr->args_size()) {
6051         ForbiddenNullArgs.set();
6052         break;
6053       } else
6054         for (auto Idx : Attr->args()) {
6055           unsigned ASTIdx = Idx.getASTIndex();
6056           if (ASTIdx >= Args.size())
6057             continue;
6058           ForbiddenNullArgs[ASTIdx] = true;
6059         }
6060     }
6061   }
6062   for (unsigned I = 0; I < Args.size(); I++) {
6063     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6064     const ParmVarDecl *PVD =
6065         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6066     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6067     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6068       // If we're checking for a potential constant expression, evaluate all
6069       // initializers even if some of them fail.
6070       if (!Info.noteFailure())
6071         return false;
6072       Success = false;
6073     }
6074   }
6075   return Success;
6076 }
6077 
6078 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6079 /// constructor or assignment operator.
6080 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6081                               const Expr *E, APValue &Result,
6082                               bool CopyObjectRepresentation) {
6083   // Find the reference argument.
6084   CallStackFrame *Frame = Info.CurrentCall;
6085   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6086   if (!RefValue) {
6087     Info.FFDiag(E);
6088     return false;
6089   }
6090 
6091   // Copy out the contents of the RHS object.
6092   LValue RefLValue;
6093   RefLValue.setFrom(Info.Ctx, *RefValue);
6094   return handleLValueToRValueConversion(
6095       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6096       CopyObjectRepresentation);
6097 }
6098 
6099 /// Evaluate a function call.
6100 static bool HandleFunctionCall(SourceLocation CallLoc,
6101                                const FunctionDecl *Callee, const LValue *This,
6102                                ArrayRef<const Expr *> Args, CallRef Call,
6103                                const Stmt *Body, EvalInfo &Info,
6104                                APValue &Result, const LValue *ResultSlot) {
6105   if (!Info.CheckCallLimit(CallLoc))
6106     return false;
6107 
6108   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6109 
6110   // For a trivial copy or move assignment, perform an APValue copy. This is
6111   // essential for unions, where the operations performed by the assignment
6112   // operator cannot be represented as statements.
6113   //
6114   // Skip this for non-union classes with no fields; in that case, the defaulted
6115   // copy/move does not actually read the object.
6116   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6117   if (MD && MD->isDefaulted() &&
6118       (MD->getParent()->isUnion() ||
6119        (MD->isTrivial() &&
6120         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6121     assert(This &&
6122            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6123     APValue RHSValue;
6124     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6125                            MD->getParent()->isUnion()))
6126       return false;
6127     if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
6128         !HandleUnionActiveMemberChange(Info, Args[0], *This))
6129       return false;
6130     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6131                           RHSValue))
6132       return false;
6133     This->moveInto(Result);
6134     return true;
6135   } else if (MD && isLambdaCallOperator(MD)) {
6136     // We're in a lambda; determine the lambda capture field maps unless we're
6137     // just constexpr checking a lambda's call operator. constexpr checking is
6138     // done before the captures have been added to the closure object (unless
6139     // we're inferring constexpr-ness), so we don't have access to them in this
6140     // case. But since we don't need the captures to constexpr check, we can
6141     // just ignore them.
6142     if (!Info.checkingPotentialConstantExpression())
6143       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6144                                         Frame.LambdaThisCaptureField);
6145   }
6146 
6147   StmtResult Ret = {Result, ResultSlot};
6148   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6149   if (ESR == ESR_Succeeded) {
6150     if (Callee->getReturnType()->isVoidType())
6151       return true;
6152     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6153   }
6154   return ESR == ESR_Returned;
6155 }
6156 
6157 /// Evaluate a constructor call.
6158 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6159                                   CallRef Call,
6160                                   const CXXConstructorDecl *Definition,
6161                                   EvalInfo &Info, APValue &Result) {
6162   SourceLocation CallLoc = E->getExprLoc();
6163   if (!Info.CheckCallLimit(CallLoc))
6164     return false;
6165 
6166   const CXXRecordDecl *RD = Definition->getParent();
6167   if (RD->getNumVBases()) {
6168     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6169     return false;
6170   }
6171 
6172   EvalInfo::EvaluatingConstructorRAII EvalObj(
6173       Info,
6174       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6175       RD->getNumBases());
6176   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6177 
6178   // FIXME: Creating an APValue just to hold a nonexistent return value is
6179   // wasteful.
6180   APValue RetVal;
6181   StmtResult Ret = {RetVal, nullptr};
6182 
6183   // If it's a delegating constructor, delegate.
6184   if (Definition->isDelegatingConstructor()) {
6185     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6186     if ((*I)->getInit()->isValueDependent()) {
6187       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6188         return false;
6189     } else {
6190       FullExpressionRAII InitScope(Info);
6191       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6192           !InitScope.destroy())
6193         return false;
6194     }
6195     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6196   }
6197 
6198   // For a trivial copy or move constructor, perform an APValue copy. This is
6199   // essential for unions (or classes with anonymous union members), where the
6200   // operations performed by the constructor cannot be represented by
6201   // ctor-initializers.
6202   //
6203   // Skip this for empty non-union classes; we should not perform an
6204   // lvalue-to-rvalue conversion on them because their copy constructor does not
6205   // actually read them.
6206   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6207       (Definition->getParent()->isUnion() ||
6208        (Definition->isTrivial() &&
6209         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6210     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6211                              Definition->getParent()->isUnion());
6212   }
6213 
6214   // Reserve space for the struct members.
6215   if (!Result.hasValue()) {
6216     if (!RD->isUnion())
6217       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6218                        std::distance(RD->field_begin(), RD->field_end()));
6219     else
6220       // A union starts with no active member.
6221       Result = APValue((const FieldDecl*)nullptr);
6222   }
6223 
6224   if (RD->isInvalidDecl()) return false;
6225   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6226 
6227   // A scope for temporaries lifetime-extended by reference members.
6228   BlockScopeRAII LifetimeExtendedScope(Info);
6229 
6230   bool Success = true;
6231   unsigned BasesSeen = 0;
6232 #ifndef NDEBUG
6233   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6234 #endif
6235   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6236   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6237     // We might be initializing the same field again if this is an indirect
6238     // field initialization.
6239     if (FieldIt == RD->field_end() ||
6240         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6241       assert(Indirect && "fields out of order?");
6242       return;
6243     }
6244 
6245     // Default-initialize any fields with no explicit initializer.
6246     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6247       assert(FieldIt != RD->field_end() && "missing field?");
6248       if (!FieldIt->isUnnamedBitfield())
6249         Success &= getDefaultInitValue(
6250             FieldIt->getType(),
6251             Result.getStructField(FieldIt->getFieldIndex()));
6252     }
6253     ++FieldIt;
6254   };
6255   for (const auto *I : Definition->inits()) {
6256     LValue Subobject = This;
6257     LValue SubobjectParent = This;
6258     APValue *Value = &Result;
6259 
6260     // Determine the subobject to initialize.
6261     FieldDecl *FD = nullptr;
6262     if (I->isBaseInitializer()) {
6263       QualType BaseType(I->getBaseClass(), 0);
6264 #ifndef NDEBUG
6265       // Non-virtual base classes are initialized in the order in the class
6266       // definition. We have already checked for virtual base classes.
6267       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6268       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6269              "base class initializers not in expected order");
6270       ++BaseIt;
6271 #endif
6272       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6273                                   BaseType->getAsCXXRecordDecl(), &Layout))
6274         return false;
6275       Value = &Result.getStructBase(BasesSeen++);
6276     } else if ((FD = I->getMember())) {
6277       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6278         return false;
6279       if (RD->isUnion()) {
6280         Result = APValue(FD);
6281         Value = &Result.getUnionValue();
6282       } else {
6283         SkipToField(FD, false);
6284         Value = &Result.getStructField(FD->getFieldIndex());
6285       }
6286     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6287       // Walk the indirect field decl's chain to find the object to initialize,
6288       // and make sure we've initialized every step along it.
6289       auto IndirectFieldChain = IFD->chain();
6290       for (auto *C : IndirectFieldChain) {
6291         FD = cast<FieldDecl>(C);
6292         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6293         // Switch the union field if it differs. This happens if we had
6294         // preceding zero-initialization, and we're now initializing a union
6295         // subobject other than the first.
6296         // FIXME: In this case, the values of the other subobjects are
6297         // specified, since zero-initialization sets all padding bits to zero.
6298         if (!Value->hasValue() ||
6299             (Value->isUnion() && Value->getUnionField() != FD)) {
6300           if (CD->isUnion())
6301             *Value = APValue(FD);
6302           else
6303             // FIXME: This immediately starts the lifetime of all members of
6304             // an anonymous struct. It would be preferable to strictly start
6305             // member lifetime in initialization order.
6306             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6307         }
6308         // Store Subobject as its parent before updating it for the last element
6309         // in the chain.
6310         if (C == IndirectFieldChain.back())
6311           SubobjectParent = Subobject;
6312         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6313           return false;
6314         if (CD->isUnion())
6315           Value = &Value->getUnionValue();
6316         else {
6317           if (C == IndirectFieldChain.front() && !RD->isUnion())
6318             SkipToField(FD, true);
6319           Value = &Value->getStructField(FD->getFieldIndex());
6320         }
6321       }
6322     } else {
6323       llvm_unreachable("unknown base initializer kind");
6324     }
6325 
6326     // Need to override This for implicit field initializers as in this case
6327     // This refers to innermost anonymous struct/union containing initializer,
6328     // not to currently constructed class.
6329     const Expr *Init = I->getInit();
6330     if (Init->isValueDependent()) {
6331       if (!EvaluateDependentExpr(Init, Info))
6332         return false;
6333     } else {
6334       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6335                                     isa<CXXDefaultInitExpr>(Init));
6336       FullExpressionRAII InitScope(Info);
6337       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6338           (FD && FD->isBitField() &&
6339            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6340         // If we're checking for a potential constant expression, evaluate all
6341         // initializers even if some of them fail.
6342         if (!Info.noteFailure())
6343           return false;
6344         Success = false;
6345       }
6346     }
6347 
6348     // This is the point at which the dynamic type of the object becomes this
6349     // class type.
6350     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6351       EvalObj.finishedConstructingBases();
6352   }
6353 
6354   // Default-initialize any remaining fields.
6355   if (!RD->isUnion()) {
6356     for (; FieldIt != RD->field_end(); ++FieldIt) {
6357       if (!FieldIt->isUnnamedBitfield())
6358         Success &= getDefaultInitValue(
6359             FieldIt->getType(),
6360             Result.getStructField(FieldIt->getFieldIndex()));
6361     }
6362   }
6363 
6364   EvalObj.finishedConstructingFields();
6365 
6366   return Success &&
6367          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6368          LifetimeExtendedScope.destroy();
6369 }
6370 
6371 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6372                                   ArrayRef<const Expr*> Args,
6373                                   const CXXConstructorDecl *Definition,
6374                                   EvalInfo &Info, APValue &Result) {
6375   CallScopeRAII CallScope(Info);
6376   CallRef Call = Info.CurrentCall->createCall(Definition);
6377   if (!EvaluateArgs(Args, Call, Info, Definition))
6378     return false;
6379 
6380   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6381          CallScope.destroy();
6382 }
6383 
6384 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6385                                   const LValue &This, APValue &Value,
6386                                   QualType T) {
6387   // Objects can only be destroyed while they're within their lifetimes.
6388   // FIXME: We have no representation for whether an object of type nullptr_t
6389   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6390   // as indeterminate instead?
6391   if (Value.isAbsent() && !T->isNullPtrType()) {
6392     APValue Printable;
6393     This.moveInto(Printable);
6394     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6395       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6396     return false;
6397   }
6398 
6399   // Invent an expression for location purposes.
6400   // FIXME: We shouldn't need to do this.
6401   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6402 
6403   // For arrays, destroy elements right-to-left.
6404   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6405     uint64_t Size = CAT->getSize().getZExtValue();
6406     QualType ElemT = CAT->getElementType();
6407 
6408     LValue ElemLV = This;
6409     ElemLV.addArray(Info, &LocE, CAT);
6410     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6411       return false;
6412 
6413     // Ensure that we have actual array elements available to destroy; the
6414     // destructors might mutate the value, so we can't run them on the array
6415     // filler.
6416     if (Size && Size > Value.getArrayInitializedElts())
6417       expandArray(Value, Value.getArraySize() - 1);
6418 
6419     for (; Size != 0; --Size) {
6420       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6421       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6422           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6423         return false;
6424     }
6425 
6426     // End the lifetime of this array now.
6427     Value = APValue();
6428     return true;
6429   }
6430 
6431   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6432   if (!RD) {
6433     if (T.isDestructedType()) {
6434       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6435       return false;
6436     }
6437 
6438     Value = APValue();
6439     return true;
6440   }
6441 
6442   if (RD->getNumVBases()) {
6443     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6444     return false;
6445   }
6446 
6447   const CXXDestructorDecl *DD = RD->getDestructor();
6448   if (!DD && !RD->hasTrivialDestructor()) {
6449     Info.FFDiag(CallLoc);
6450     return false;
6451   }
6452 
6453   if (!DD || DD->isTrivial() ||
6454       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6455     // A trivial destructor just ends the lifetime of the object. Check for
6456     // this case before checking for a body, because we might not bother
6457     // building a body for a trivial destructor. Note that it doesn't matter
6458     // whether the destructor is constexpr in this case; all trivial
6459     // destructors are constexpr.
6460     //
6461     // If an anonymous union would be destroyed, some enclosing destructor must
6462     // have been explicitly defined, and the anonymous union destruction should
6463     // have no effect.
6464     Value = APValue();
6465     return true;
6466   }
6467 
6468   if (!Info.CheckCallLimit(CallLoc))
6469     return false;
6470 
6471   const FunctionDecl *Definition = nullptr;
6472   const Stmt *Body = DD->getBody(Definition);
6473 
6474   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6475     return false;
6476 
6477   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6478 
6479   // We're now in the period of destruction of this object.
6480   unsigned BasesLeft = RD->getNumBases();
6481   EvalInfo::EvaluatingDestructorRAII EvalObj(
6482       Info,
6483       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6484   if (!EvalObj.DidInsert) {
6485     // C++2a [class.dtor]p19:
6486     //   the behavior is undefined if the destructor is invoked for an object
6487     //   whose lifetime has ended
6488     // (Note that formally the lifetime ends when the period of destruction
6489     // begins, even though certain uses of the object remain valid until the
6490     // period of destruction ends.)
6491     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6492     return false;
6493   }
6494 
6495   // FIXME: Creating an APValue just to hold a nonexistent return value is
6496   // wasteful.
6497   APValue RetVal;
6498   StmtResult Ret = {RetVal, nullptr};
6499   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6500     return false;
6501 
6502   // A union destructor does not implicitly destroy its members.
6503   if (RD->isUnion())
6504     return true;
6505 
6506   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6507 
6508   // We don't have a good way to iterate fields in reverse, so collect all the
6509   // fields first and then walk them backwards.
6510   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6511   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6512     if (FD->isUnnamedBitfield())
6513       continue;
6514 
6515     LValue Subobject = This;
6516     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6517       return false;
6518 
6519     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6520     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6521                                FD->getType()))
6522       return false;
6523   }
6524 
6525   if (BasesLeft != 0)
6526     EvalObj.startedDestroyingBases();
6527 
6528   // Destroy base classes in reverse order.
6529   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6530     --BasesLeft;
6531 
6532     QualType BaseType = Base.getType();
6533     LValue Subobject = This;
6534     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6535                                 BaseType->getAsCXXRecordDecl(), &Layout))
6536       return false;
6537 
6538     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6539     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6540                                BaseType))
6541       return false;
6542   }
6543   assert(BasesLeft == 0 && "NumBases was wrong?");
6544 
6545   // The period of destruction ends now. The object is gone.
6546   Value = APValue();
6547   return true;
6548 }
6549 
6550 namespace {
6551 struct DestroyObjectHandler {
6552   EvalInfo &Info;
6553   const Expr *E;
6554   const LValue &This;
6555   const AccessKinds AccessKind;
6556 
6557   typedef bool result_type;
6558   bool failed() { return false; }
6559   bool found(APValue &Subobj, QualType SubobjType) {
6560     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6561                                  SubobjType);
6562   }
6563   bool found(APSInt &Value, QualType SubobjType) {
6564     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6565     return false;
6566   }
6567   bool found(APFloat &Value, QualType SubobjType) {
6568     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6569     return false;
6570   }
6571 };
6572 }
6573 
6574 /// Perform a destructor or pseudo-destructor call on the given object, which
6575 /// might in general not be a complete object.
6576 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6577                               const LValue &This, QualType ThisType) {
6578   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6579   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6580   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6581 }
6582 
6583 /// Destroy and end the lifetime of the given complete object.
6584 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6585                               APValue::LValueBase LVBase, APValue &Value,
6586                               QualType T) {
6587   // If we've had an unmodeled side-effect, we can't rely on mutable state
6588   // (such as the object we're about to destroy) being correct.
6589   if (Info.EvalStatus.HasSideEffects)
6590     return false;
6591 
6592   LValue LV;
6593   LV.set({LVBase});
6594   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6595 }
6596 
6597 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6598 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6599                                   LValue &Result) {
6600   if (Info.checkingPotentialConstantExpression() ||
6601       Info.SpeculativeEvaluationDepth)
6602     return false;
6603 
6604   // This is permitted only within a call to std::allocator<T>::allocate.
6605   auto Caller = Info.getStdAllocatorCaller("allocate");
6606   if (!Caller) {
6607     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6608                                      ? diag::note_constexpr_new_untyped
6609                                      : diag::note_constexpr_new);
6610     return false;
6611   }
6612 
6613   QualType ElemType = Caller.ElemType;
6614   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6615     Info.FFDiag(E->getExprLoc(),
6616                 diag::note_constexpr_new_not_complete_object_type)
6617         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6618     return false;
6619   }
6620 
6621   APSInt ByteSize;
6622   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6623     return false;
6624   bool IsNothrow = false;
6625   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6626     EvaluateIgnoredValue(Info, E->getArg(I));
6627     IsNothrow |= E->getType()->isNothrowT();
6628   }
6629 
6630   CharUnits ElemSize;
6631   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6632     return false;
6633   APInt Size, Remainder;
6634   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6635   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6636   if (Remainder != 0) {
6637     // This likely indicates a bug in the implementation of 'std::allocator'.
6638     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6639         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6640     return false;
6641   }
6642 
6643   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6644     if (IsNothrow) {
6645       Result.setNull(Info.Ctx, E->getType());
6646       return true;
6647     }
6648 
6649     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6650     return false;
6651   }
6652 
6653   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6654                                                      ArrayType::Normal, 0);
6655   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6656   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6657   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6658   return true;
6659 }
6660 
6661 static bool hasVirtualDestructor(QualType T) {
6662   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6663     if (CXXDestructorDecl *DD = RD->getDestructor())
6664       return DD->isVirtual();
6665   return false;
6666 }
6667 
6668 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6669   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6670     if (CXXDestructorDecl *DD = RD->getDestructor())
6671       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6672   return nullptr;
6673 }
6674 
6675 /// Check that the given object is a suitable pointer to a heap allocation that
6676 /// still exists and is of the right kind for the purpose of a deletion.
6677 ///
6678 /// On success, returns the heap allocation to deallocate. On failure, produces
6679 /// a diagnostic and returns None.
6680 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6681                                             const LValue &Pointer,
6682                                             DynAlloc::Kind DeallocKind) {
6683   auto PointerAsString = [&] {
6684     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6685   };
6686 
6687   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6688   if (!DA) {
6689     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6690         << PointerAsString();
6691     if (Pointer.Base)
6692       NoteLValueLocation(Info, Pointer.Base);
6693     return None;
6694   }
6695 
6696   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6697   if (!Alloc) {
6698     Info.FFDiag(E, diag::note_constexpr_double_delete);
6699     return None;
6700   }
6701 
6702   QualType AllocType = Pointer.Base.getDynamicAllocType();
6703   if (DeallocKind != (*Alloc)->getKind()) {
6704     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6705         << DeallocKind << (*Alloc)->getKind() << AllocType;
6706     NoteLValueLocation(Info, Pointer.Base);
6707     return None;
6708   }
6709 
6710   bool Subobject = false;
6711   if (DeallocKind == DynAlloc::New) {
6712     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6713                 Pointer.Designator.isOnePastTheEnd();
6714   } else {
6715     Subobject = Pointer.Designator.Entries.size() != 1 ||
6716                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6717   }
6718   if (Subobject) {
6719     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6720         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6721     return None;
6722   }
6723 
6724   return Alloc;
6725 }
6726 
6727 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6728 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6729   if (Info.checkingPotentialConstantExpression() ||
6730       Info.SpeculativeEvaluationDepth)
6731     return false;
6732 
6733   // This is permitted only within a call to std::allocator<T>::deallocate.
6734   if (!Info.getStdAllocatorCaller("deallocate")) {
6735     Info.FFDiag(E->getExprLoc());
6736     return true;
6737   }
6738 
6739   LValue Pointer;
6740   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6741     return false;
6742   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6743     EvaluateIgnoredValue(Info, E->getArg(I));
6744 
6745   if (Pointer.Designator.Invalid)
6746     return false;
6747 
6748   // Deleting a null pointer would have no effect, but it's not permitted by
6749   // std::allocator<T>::deallocate's contract.
6750   if (Pointer.isNullPointer()) {
6751     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6752     return true;
6753   }
6754 
6755   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6756     return false;
6757 
6758   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6759   return true;
6760 }
6761 
6762 //===----------------------------------------------------------------------===//
6763 // Generic Evaluation
6764 //===----------------------------------------------------------------------===//
6765 namespace {
6766 
6767 class BitCastBuffer {
6768   // FIXME: We're going to need bit-level granularity when we support
6769   // bit-fields.
6770   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6771   // we don't support a host or target where that is the case. Still, we should
6772   // use a more generic type in case we ever do.
6773   SmallVector<Optional<unsigned char>, 32> Bytes;
6774 
6775   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6776                 "Need at least 8 bit unsigned char");
6777 
6778   bool TargetIsLittleEndian;
6779 
6780 public:
6781   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6782       : Bytes(Width.getQuantity()),
6783         TargetIsLittleEndian(TargetIsLittleEndian) {}
6784 
6785   LLVM_NODISCARD
6786   bool readObject(CharUnits Offset, CharUnits Width,
6787                   SmallVectorImpl<unsigned char> &Output) const {
6788     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6789       // If a byte of an integer is uninitialized, then the whole integer is
6790       // uninitialized.
6791       if (!Bytes[I.getQuantity()])
6792         return false;
6793       Output.push_back(*Bytes[I.getQuantity()]);
6794     }
6795     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6796       std::reverse(Output.begin(), Output.end());
6797     return true;
6798   }
6799 
6800   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6801     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6802       std::reverse(Input.begin(), Input.end());
6803 
6804     size_t Index = 0;
6805     for (unsigned char Byte : Input) {
6806       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6807       Bytes[Offset.getQuantity() + Index] = Byte;
6808       ++Index;
6809     }
6810   }
6811 
6812   size_t size() { return Bytes.size(); }
6813 };
6814 
6815 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6816 /// target would represent the value at runtime.
6817 class APValueToBufferConverter {
6818   EvalInfo &Info;
6819   BitCastBuffer Buffer;
6820   const CastExpr *BCE;
6821 
6822   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6823                            const CastExpr *BCE)
6824       : Info(Info),
6825         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6826         BCE(BCE) {}
6827 
6828   bool visit(const APValue &Val, QualType Ty) {
6829     return visit(Val, Ty, CharUnits::fromQuantity(0));
6830   }
6831 
6832   // Write out Val with type Ty into Buffer starting at Offset.
6833   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6834     assert((size_t)Offset.getQuantity() <= Buffer.size());
6835 
6836     // As a special case, nullptr_t has an indeterminate value.
6837     if (Ty->isNullPtrType())
6838       return true;
6839 
6840     // Dig through Src to find the byte at SrcOffset.
6841     switch (Val.getKind()) {
6842     case APValue::Indeterminate:
6843     case APValue::None:
6844       return true;
6845 
6846     case APValue::Int:
6847       return visitInt(Val.getInt(), Ty, Offset);
6848     case APValue::Float:
6849       return visitFloat(Val.getFloat(), Ty, Offset);
6850     case APValue::Array:
6851       return visitArray(Val, Ty, Offset);
6852     case APValue::Struct:
6853       return visitRecord(Val, Ty, Offset);
6854 
6855     case APValue::ComplexInt:
6856     case APValue::ComplexFloat:
6857     case APValue::Vector:
6858     case APValue::FixedPoint:
6859       // FIXME: We should support these.
6860 
6861     case APValue::Union:
6862     case APValue::MemberPointer:
6863     case APValue::AddrLabelDiff: {
6864       Info.FFDiag(BCE->getBeginLoc(),
6865                   diag::note_constexpr_bit_cast_unsupported_type)
6866           << Ty;
6867       return false;
6868     }
6869 
6870     case APValue::LValue:
6871       llvm_unreachable("LValue subobject in bit_cast?");
6872     }
6873     llvm_unreachable("Unhandled APValue::ValueKind");
6874   }
6875 
6876   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6877     const RecordDecl *RD = Ty->getAsRecordDecl();
6878     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6879 
6880     // Visit the base classes.
6881     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6882       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6883         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6884         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6885 
6886         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6887                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6888           return false;
6889       }
6890     }
6891 
6892     // Visit the fields.
6893     unsigned FieldIdx = 0;
6894     for (FieldDecl *FD : RD->fields()) {
6895       if (FD->isBitField()) {
6896         Info.FFDiag(BCE->getBeginLoc(),
6897                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6898         return false;
6899       }
6900 
6901       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6902 
6903       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6904              "only bit-fields can have sub-char alignment");
6905       CharUnits FieldOffset =
6906           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6907       QualType FieldTy = FD->getType();
6908       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6909         return false;
6910       ++FieldIdx;
6911     }
6912 
6913     return true;
6914   }
6915 
6916   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6917     const auto *CAT =
6918         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6919     if (!CAT)
6920       return false;
6921 
6922     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6923     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6924     unsigned ArraySize = Val.getArraySize();
6925     // First, initialize the initialized elements.
6926     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6927       const APValue &SubObj = Val.getArrayInitializedElt(I);
6928       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6929         return false;
6930     }
6931 
6932     // Next, initialize the rest of the array using the filler.
6933     if (Val.hasArrayFiller()) {
6934       const APValue &Filler = Val.getArrayFiller();
6935       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6936         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6937           return false;
6938       }
6939     }
6940 
6941     return true;
6942   }
6943 
6944   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6945     APSInt AdjustedVal = Val;
6946     unsigned Width = AdjustedVal.getBitWidth();
6947     if (Ty->isBooleanType()) {
6948       Width = Info.Ctx.getTypeSize(Ty);
6949       AdjustedVal = AdjustedVal.extend(Width);
6950     }
6951 
6952     SmallVector<unsigned char, 8> Bytes(Width / 8);
6953     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6954     Buffer.writeObject(Offset, Bytes);
6955     return true;
6956   }
6957 
6958   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6959     APSInt AsInt(Val.bitcastToAPInt());
6960     return visitInt(AsInt, Ty, Offset);
6961   }
6962 
6963 public:
6964   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6965                                          const CastExpr *BCE) {
6966     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6967     APValueToBufferConverter Converter(Info, DstSize, BCE);
6968     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6969       return None;
6970     return Converter.Buffer;
6971   }
6972 };
6973 
6974 /// Write an BitCastBuffer into an APValue.
6975 class BufferToAPValueConverter {
6976   EvalInfo &Info;
6977   const BitCastBuffer &Buffer;
6978   const CastExpr *BCE;
6979 
6980   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6981                            const CastExpr *BCE)
6982       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6983 
6984   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6985   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6986   // Ideally this will be unreachable.
6987   llvm::NoneType unsupportedType(QualType Ty) {
6988     Info.FFDiag(BCE->getBeginLoc(),
6989                 diag::note_constexpr_bit_cast_unsupported_type)
6990         << Ty;
6991     return None;
6992   }
6993 
6994   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
6995     Info.FFDiag(BCE->getBeginLoc(),
6996                 diag::note_constexpr_bit_cast_unrepresentable_value)
6997         << Ty << toString(Val, /*Radix=*/10);
6998     return None;
6999   }
7000 
7001   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7002                           const EnumType *EnumSugar = nullptr) {
7003     if (T->isNullPtrType()) {
7004       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7005       return APValue((Expr *)nullptr,
7006                      /*Offset=*/CharUnits::fromQuantity(NullValue),
7007                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7008     }
7009 
7010     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7011 
7012     // Work around floating point types that contain unused padding bytes. This
7013     // is really just `long double` on x86, which is the only fundamental type
7014     // with padding bytes.
7015     if (T->isRealFloatingType()) {
7016       const llvm::fltSemantics &Semantics =
7017           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7018       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7019       assert(NumBits % 8 == 0);
7020       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7021       if (NumBytes != SizeOf)
7022         SizeOf = NumBytes;
7023     }
7024 
7025     SmallVector<uint8_t, 8> Bytes;
7026     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7027       // If this is std::byte or unsigned char, then its okay to store an
7028       // indeterminate value.
7029       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7030       bool IsUChar =
7031           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7032                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7033       if (!IsStdByte && !IsUChar) {
7034         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7035         Info.FFDiag(BCE->getExprLoc(),
7036                     diag::note_constexpr_bit_cast_indet_dest)
7037             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7038         return None;
7039       }
7040 
7041       return APValue::IndeterminateValue();
7042     }
7043 
7044     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7045     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7046 
7047     if (T->isIntegralOrEnumerationType()) {
7048       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7049 
7050       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7051       if (IntWidth != Val.getBitWidth()) {
7052         APSInt Truncated = Val.trunc(IntWidth);
7053         if (Truncated.extend(Val.getBitWidth()) != Val)
7054           return unrepresentableValue(QualType(T, 0), Val);
7055         Val = Truncated;
7056       }
7057 
7058       return APValue(Val);
7059     }
7060 
7061     if (T->isRealFloatingType()) {
7062       const llvm::fltSemantics &Semantics =
7063           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7064       return APValue(APFloat(Semantics, Val));
7065     }
7066 
7067     return unsupportedType(QualType(T, 0));
7068   }
7069 
7070   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7071     const RecordDecl *RD = RTy->getAsRecordDecl();
7072     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7073 
7074     unsigned NumBases = 0;
7075     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7076       NumBases = CXXRD->getNumBases();
7077 
7078     APValue ResultVal(APValue::UninitStruct(), NumBases,
7079                       std::distance(RD->field_begin(), RD->field_end()));
7080 
7081     // Visit the base classes.
7082     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7083       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7084         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7085         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7086         if (BaseDecl->isEmpty() ||
7087             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7088           continue;
7089 
7090         Optional<APValue> SubObj = visitType(
7091             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7092         if (!SubObj)
7093           return None;
7094         ResultVal.getStructBase(I) = *SubObj;
7095       }
7096     }
7097 
7098     // Visit the fields.
7099     unsigned FieldIdx = 0;
7100     for (FieldDecl *FD : RD->fields()) {
7101       // FIXME: We don't currently support bit-fields. A lot of the logic for
7102       // this is in CodeGen, so we need to factor it around.
7103       if (FD->isBitField()) {
7104         Info.FFDiag(BCE->getBeginLoc(),
7105                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7106         return None;
7107       }
7108 
7109       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7110       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7111 
7112       CharUnits FieldOffset =
7113           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7114           Offset;
7115       QualType FieldTy = FD->getType();
7116       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7117       if (!SubObj)
7118         return None;
7119       ResultVal.getStructField(FieldIdx) = *SubObj;
7120       ++FieldIdx;
7121     }
7122 
7123     return ResultVal;
7124   }
7125 
7126   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7127     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7128     assert(!RepresentationType.isNull() &&
7129            "enum forward decl should be caught by Sema");
7130     const auto *AsBuiltin =
7131         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7132     // Recurse into the underlying type. Treat std::byte transparently as
7133     // unsigned char.
7134     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7135   }
7136 
7137   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7138     size_t Size = Ty->getSize().getLimitedValue();
7139     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7140 
7141     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7142     for (size_t I = 0; I != Size; ++I) {
7143       Optional<APValue> ElementValue =
7144           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7145       if (!ElementValue)
7146         return None;
7147       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7148     }
7149 
7150     return ArrayValue;
7151   }
7152 
7153   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7154     return unsupportedType(QualType(Ty, 0));
7155   }
7156 
7157   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7158     QualType Can = Ty.getCanonicalType();
7159 
7160     switch (Can->getTypeClass()) {
7161 #define TYPE(Class, Base)                                                      \
7162   case Type::Class:                                                            \
7163     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7164 #define ABSTRACT_TYPE(Class, Base)
7165 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7166   case Type::Class:                                                            \
7167     llvm_unreachable("non-canonical type should be impossible!");
7168 #define DEPENDENT_TYPE(Class, Base)                                            \
7169   case Type::Class:                                                            \
7170     llvm_unreachable(                                                          \
7171         "dependent types aren't supported in the constant evaluator!");
7172 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7173   case Type::Class:                                                            \
7174     llvm_unreachable("either dependent or not canonical!");
7175 #include "clang/AST/TypeNodes.inc"
7176     }
7177     llvm_unreachable("Unhandled Type::TypeClass");
7178   }
7179 
7180 public:
7181   // Pull out a full value of type DstType.
7182   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7183                                    const CastExpr *BCE) {
7184     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7185     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7186   }
7187 };
7188 
7189 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7190                                                  QualType Ty, EvalInfo *Info,
7191                                                  const ASTContext &Ctx,
7192                                                  bool CheckingDest) {
7193   Ty = Ty.getCanonicalType();
7194 
7195   auto diag = [&](int Reason) {
7196     if (Info)
7197       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7198           << CheckingDest << (Reason == 4) << Reason;
7199     return false;
7200   };
7201   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7202     if (Info)
7203       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7204           << NoteTy << Construct << Ty;
7205     return false;
7206   };
7207 
7208   if (Ty->isUnionType())
7209     return diag(0);
7210   if (Ty->isPointerType())
7211     return diag(1);
7212   if (Ty->isMemberPointerType())
7213     return diag(2);
7214   if (Ty.isVolatileQualified())
7215     return diag(3);
7216 
7217   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7218     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7219       for (CXXBaseSpecifier &BS : CXXRD->bases())
7220         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7221                                                   CheckingDest))
7222           return note(1, BS.getType(), BS.getBeginLoc());
7223     }
7224     for (FieldDecl *FD : Record->fields()) {
7225       if (FD->getType()->isReferenceType())
7226         return diag(4);
7227       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7228                                                 CheckingDest))
7229         return note(0, FD->getType(), FD->getBeginLoc());
7230     }
7231   }
7232 
7233   if (Ty->isArrayType() &&
7234       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7235                                             Info, Ctx, CheckingDest))
7236     return false;
7237 
7238   return true;
7239 }
7240 
7241 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7242                                              const ASTContext &Ctx,
7243                                              const CastExpr *BCE) {
7244   bool DestOK = checkBitCastConstexprEligibilityType(
7245       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7246   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7247                                 BCE->getBeginLoc(),
7248                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7249   return SourceOK;
7250 }
7251 
7252 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7253                                         APValue &SourceValue,
7254                                         const CastExpr *BCE) {
7255   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7256          "no host or target supports non 8-bit chars");
7257   assert(SourceValue.isLValue() &&
7258          "LValueToRValueBitcast requires an lvalue operand!");
7259 
7260   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7261     return false;
7262 
7263   LValue SourceLValue;
7264   APValue SourceRValue;
7265   SourceLValue.setFrom(Info.Ctx, SourceValue);
7266   if (!handleLValueToRValueConversion(
7267           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7268           SourceRValue, /*WantObjectRepresentation=*/true))
7269     return false;
7270 
7271   // Read out SourceValue into a char buffer.
7272   Optional<BitCastBuffer> Buffer =
7273       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7274   if (!Buffer)
7275     return false;
7276 
7277   // Write out the buffer into a new APValue.
7278   Optional<APValue> MaybeDestValue =
7279       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7280   if (!MaybeDestValue)
7281     return false;
7282 
7283   DestValue = std::move(*MaybeDestValue);
7284   return true;
7285 }
7286 
7287 template <class Derived>
7288 class ExprEvaluatorBase
7289   : public ConstStmtVisitor<Derived, bool> {
7290 private:
7291   Derived &getDerived() { return static_cast<Derived&>(*this); }
7292   bool DerivedSuccess(const APValue &V, const Expr *E) {
7293     return getDerived().Success(V, E);
7294   }
7295   bool DerivedZeroInitialization(const Expr *E) {
7296     return getDerived().ZeroInitialization(E);
7297   }
7298 
7299   // Check whether a conditional operator with a non-constant condition is a
7300   // potential constant expression. If neither arm is a potential constant
7301   // expression, then the conditional operator is not either.
7302   template<typename ConditionalOperator>
7303   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7304     assert(Info.checkingPotentialConstantExpression());
7305 
7306     // Speculatively evaluate both arms.
7307     SmallVector<PartialDiagnosticAt, 8> Diag;
7308     {
7309       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7310       StmtVisitorTy::Visit(E->getFalseExpr());
7311       if (Diag.empty())
7312         return;
7313     }
7314 
7315     {
7316       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7317       Diag.clear();
7318       StmtVisitorTy::Visit(E->getTrueExpr());
7319       if (Diag.empty())
7320         return;
7321     }
7322 
7323     Error(E, diag::note_constexpr_conditional_never_const);
7324   }
7325 
7326 
7327   template<typename ConditionalOperator>
7328   bool HandleConditionalOperator(const ConditionalOperator *E) {
7329     bool BoolResult;
7330     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7331       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7332         CheckPotentialConstantConditional(E);
7333         return false;
7334       }
7335       if (Info.noteFailure()) {
7336         StmtVisitorTy::Visit(E->getTrueExpr());
7337         StmtVisitorTy::Visit(E->getFalseExpr());
7338       }
7339       return false;
7340     }
7341 
7342     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7343     return StmtVisitorTy::Visit(EvalExpr);
7344   }
7345 
7346 protected:
7347   EvalInfo &Info;
7348   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7349   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7350 
7351   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7352     return Info.CCEDiag(E, D);
7353   }
7354 
7355   bool ZeroInitialization(const Expr *E) { return Error(E); }
7356 
7357 public:
7358   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7359 
7360   EvalInfo &getEvalInfo() { return Info; }
7361 
7362   /// Report an evaluation error. This should only be called when an error is
7363   /// first discovered. When propagating an error, just return false.
7364   bool Error(const Expr *E, diag::kind D) {
7365     Info.FFDiag(E, D);
7366     return false;
7367   }
7368   bool Error(const Expr *E) {
7369     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7370   }
7371 
7372   bool VisitStmt(const Stmt *) {
7373     llvm_unreachable("Expression evaluator should not be called on stmts");
7374   }
7375   bool VisitExpr(const Expr *E) {
7376     return Error(E);
7377   }
7378 
7379   bool VisitConstantExpr(const ConstantExpr *E) {
7380     if (E->hasAPValueResult())
7381       return DerivedSuccess(E->getAPValueResult(), E);
7382 
7383     return StmtVisitorTy::Visit(E->getSubExpr());
7384   }
7385 
7386   bool VisitParenExpr(const ParenExpr *E)
7387     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7388   bool VisitUnaryExtension(const UnaryOperator *E)
7389     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7390   bool VisitUnaryPlus(const UnaryOperator *E)
7391     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7392   bool VisitChooseExpr(const ChooseExpr *E)
7393     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7394   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7395     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7396   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7397     { return StmtVisitorTy::Visit(E->getReplacement()); }
7398   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7399     TempVersionRAII RAII(*Info.CurrentCall);
7400     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7401     return StmtVisitorTy::Visit(E->getExpr());
7402   }
7403   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7404     TempVersionRAII RAII(*Info.CurrentCall);
7405     // The initializer may not have been parsed yet, or might be erroneous.
7406     if (!E->getExpr())
7407       return Error(E);
7408     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7409     return StmtVisitorTy::Visit(E->getExpr());
7410   }
7411 
7412   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7413     FullExpressionRAII Scope(Info);
7414     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7415   }
7416 
7417   // Temporaries are registered when created, so we don't care about
7418   // CXXBindTemporaryExpr.
7419   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7420     return StmtVisitorTy::Visit(E->getSubExpr());
7421   }
7422 
7423   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7424     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7425     return static_cast<Derived*>(this)->VisitCastExpr(E);
7426   }
7427   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7428     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7429       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7430     return static_cast<Derived*>(this)->VisitCastExpr(E);
7431   }
7432   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7433     return static_cast<Derived*>(this)->VisitCastExpr(E);
7434   }
7435 
7436   bool VisitBinaryOperator(const BinaryOperator *E) {
7437     switch (E->getOpcode()) {
7438     default:
7439       return Error(E);
7440 
7441     case BO_Comma:
7442       VisitIgnoredValue(E->getLHS());
7443       return StmtVisitorTy::Visit(E->getRHS());
7444 
7445     case BO_PtrMemD:
7446     case BO_PtrMemI: {
7447       LValue Obj;
7448       if (!HandleMemberPointerAccess(Info, E, Obj))
7449         return false;
7450       APValue Result;
7451       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7452         return false;
7453       return DerivedSuccess(Result, E);
7454     }
7455     }
7456   }
7457 
7458   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7459     return StmtVisitorTy::Visit(E->getSemanticForm());
7460   }
7461 
7462   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7463     // Evaluate and cache the common expression. We treat it as a temporary,
7464     // even though it's not quite the same thing.
7465     LValue CommonLV;
7466     if (!Evaluate(Info.CurrentCall->createTemporary(
7467                       E->getOpaqueValue(),
7468                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7469                       ScopeKind::FullExpression, CommonLV),
7470                   Info, E->getCommon()))
7471       return false;
7472 
7473     return HandleConditionalOperator(E);
7474   }
7475 
7476   bool VisitConditionalOperator(const ConditionalOperator *E) {
7477     bool IsBcpCall = false;
7478     // If the condition (ignoring parens) is a __builtin_constant_p call,
7479     // the result is a constant expression if it can be folded without
7480     // side-effects. This is an important GNU extension. See GCC PR38377
7481     // for discussion.
7482     if (const CallExpr *CallCE =
7483           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7484       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7485         IsBcpCall = true;
7486 
7487     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7488     // constant expression; we can't check whether it's potentially foldable.
7489     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7490     // it would return 'false' in this mode.
7491     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7492       return false;
7493 
7494     FoldConstant Fold(Info, IsBcpCall);
7495     if (!HandleConditionalOperator(E)) {
7496       Fold.keepDiagnostics();
7497       return false;
7498     }
7499 
7500     return true;
7501   }
7502 
7503   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7504     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7505       return DerivedSuccess(*Value, E);
7506 
7507     const Expr *Source = E->getSourceExpr();
7508     if (!Source)
7509       return Error(E);
7510     if (Source == E) {
7511       assert(0 && "OpaqueValueExpr recursively refers to itself");
7512       return Error(E);
7513     }
7514     return StmtVisitorTy::Visit(Source);
7515   }
7516 
7517   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7518     for (const Expr *SemE : E->semantics()) {
7519       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7520         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7521         // result expression: there could be two different LValues that would
7522         // refer to the same object in that case, and we can't model that.
7523         if (SemE == E->getResultExpr())
7524           return Error(E);
7525 
7526         // Unique OVEs get evaluated if and when we encounter them when
7527         // emitting the rest of the semantic form, rather than eagerly.
7528         if (OVE->isUnique())
7529           continue;
7530 
7531         LValue LV;
7532         if (!Evaluate(Info.CurrentCall->createTemporary(
7533                           OVE, getStorageType(Info.Ctx, OVE),
7534                           ScopeKind::FullExpression, LV),
7535                       Info, OVE->getSourceExpr()))
7536           return false;
7537       } else if (SemE == E->getResultExpr()) {
7538         if (!StmtVisitorTy::Visit(SemE))
7539           return false;
7540       } else {
7541         if (!EvaluateIgnoredValue(Info, SemE))
7542           return false;
7543       }
7544     }
7545     return true;
7546   }
7547 
7548   bool VisitCallExpr(const CallExpr *E) {
7549     APValue Result;
7550     if (!handleCallExpr(E, Result, nullptr))
7551       return false;
7552     return DerivedSuccess(Result, E);
7553   }
7554 
7555   bool handleCallExpr(const CallExpr *E, APValue &Result,
7556                      const LValue *ResultSlot) {
7557     CallScopeRAII CallScope(Info);
7558 
7559     const Expr *Callee = E->getCallee()->IgnoreParens();
7560     QualType CalleeType = Callee->getType();
7561 
7562     const FunctionDecl *FD = nullptr;
7563     LValue *This = nullptr, ThisVal;
7564     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7565     bool HasQualifier = false;
7566 
7567     CallRef Call;
7568 
7569     // Extract function decl and 'this' pointer from the callee.
7570     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7571       const CXXMethodDecl *Member = nullptr;
7572       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7573         // Explicit bound member calls, such as x.f() or p->g();
7574         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7575           return false;
7576         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7577         if (!Member)
7578           return Error(Callee);
7579         This = &ThisVal;
7580         HasQualifier = ME->hasQualifier();
7581       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7582         // Indirect bound member calls ('.*' or '->*').
7583         const ValueDecl *D =
7584             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7585         if (!D)
7586           return false;
7587         Member = dyn_cast<CXXMethodDecl>(D);
7588         if (!Member)
7589           return Error(Callee);
7590         This = &ThisVal;
7591       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7592         if (!Info.getLangOpts().CPlusPlus20)
7593           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7594         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7595                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7596       } else
7597         return Error(Callee);
7598       FD = Member;
7599     } else if (CalleeType->isFunctionPointerType()) {
7600       LValue CalleeLV;
7601       if (!EvaluatePointer(Callee, CalleeLV, Info))
7602         return false;
7603 
7604       if (!CalleeLV.getLValueOffset().isZero())
7605         return Error(Callee);
7606       FD = dyn_cast_or_null<FunctionDecl>(
7607           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7608       if (!FD)
7609         return Error(Callee);
7610       // Don't call function pointers which have been cast to some other type.
7611       // Per DR (no number yet), the caller and callee can differ in noexcept.
7612       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7613         CalleeType->getPointeeType(), FD->getType())) {
7614         return Error(E);
7615       }
7616 
7617       // For an (overloaded) assignment expression, evaluate the RHS before the
7618       // LHS.
7619       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7620       if (OCE && OCE->isAssignmentOp()) {
7621         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7622         Call = Info.CurrentCall->createCall(FD);
7623         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7624                           Info, FD, /*RightToLeft=*/true))
7625           return false;
7626       }
7627 
7628       // Overloaded operator calls to member functions are represented as normal
7629       // calls with '*this' as the first argument.
7630       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7631       if (MD && !MD->isStatic()) {
7632         // FIXME: When selecting an implicit conversion for an overloaded
7633         // operator delete, we sometimes try to evaluate calls to conversion
7634         // operators without a 'this' parameter!
7635         if (Args.empty())
7636           return Error(E);
7637 
7638         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7639           return false;
7640         This = &ThisVal;
7641         Args = Args.slice(1);
7642       } else if (MD && MD->isLambdaStaticInvoker()) {
7643         // Map the static invoker for the lambda back to the call operator.
7644         // Conveniently, we don't have to slice out the 'this' argument (as is
7645         // being done for the non-static case), since a static member function
7646         // doesn't have an implicit argument passed in.
7647         const CXXRecordDecl *ClosureClass = MD->getParent();
7648         assert(
7649             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7650             "Number of captures must be zero for conversion to function-ptr");
7651 
7652         const CXXMethodDecl *LambdaCallOp =
7653             ClosureClass->getLambdaCallOperator();
7654 
7655         // Set 'FD', the function that will be called below, to the call
7656         // operator.  If the closure object represents a generic lambda, find
7657         // the corresponding specialization of the call operator.
7658 
7659         if (ClosureClass->isGenericLambda()) {
7660           assert(MD->isFunctionTemplateSpecialization() &&
7661                  "A generic lambda's static-invoker function must be a "
7662                  "template specialization");
7663           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7664           FunctionTemplateDecl *CallOpTemplate =
7665               LambdaCallOp->getDescribedFunctionTemplate();
7666           void *InsertPos = nullptr;
7667           FunctionDecl *CorrespondingCallOpSpecialization =
7668               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7669           assert(CorrespondingCallOpSpecialization &&
7670                  "We must always have a function call operator specialization "
7671                  "that corresponds to our static invoker specialization");
7672           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7673         } else
7674           FD = LambdaCallOp;
7675       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7676         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7677             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7678           LValue Ptr;
7679           if (!HandleOperatorNewCall(Info, E, Ptr))
7680             return false;
7681           Ptr.moveInto(Result);
7682           return CallScope.destroy();
7683         } else {
7684           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7685         }
7686       }
7687     } else
7688       return Error(E);
7689 
7690     // Evaluate the arguments now if we've not already done so.
7691     if (!Call) {
7692       Call = Info.CurrentCall->createCall(FD);
7693       if (!EvaluateArgs(Args, Call, Info, FD))
7694         return false;
7695     }
7696 
7697     SmallVector<QualType, 4> CovariantAdjustmentPath;
7698     if (This) {
7699       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7700       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7701         // Perform virtual dispatch, if necessary.
7702         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7703                                    CovariantAdjustmentPath);
7704         if (!FD)
7705           return false;
7706       } else {
7707         // Check that the 'this' pointer points to an object of the right type.
7708         // FIXME: If this is an assignment operator call, we may need to change
7709         // the active union member before we check this.
7710         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7711           return false;
7712       }
7713     }
7714 
7715     // Destructor calls are different enough that they have their own codepath.
7716     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7717       assert(This && "no 'this' pointer for destructor call");
7718       return HandleDestruction(Info, E, *This,
7719                                Info.Ctx.getRecordType(DD->getParent())) &&
7720              CallScope.destroy();
7721     }
7722 
7723     const FunctionDecl *Definition = nullptr;
7724     Stmt *Body = FD->getBody(Definition);
7725 
7726     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7727         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7728                             Body, Info, Result, ResultSlot))
7729       return false;
7730 
7731     if (!CovariantAdjustmentPath.empty() &&
7732         !HandleCovariantReturnAdjustment(Info, E, Result,
7733                                          CovariantAdjustmentPath))
7734       return false;
7735 
7736     return CallScope.destroy();
7737   }
7738 
7739   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7740     return StmtVisitorTy::Visit(E->getInitializer());
7741   }
7742   bool VisitInitListExpr(const InitListExpr *E) {
7743     if (E->getNumInits() == 0)
7744       return DerivedZeroInitialization(E);
7745     if (E->getNumInits() == 1)
7746       return StmtVisitorTy::Visit(E->getInit(0));
7747     return Error(E);
7748   }
7749   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7750     return DerivedZeroInitialization(E);
7751   }
7752   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7753     return DerivedZeroInitialization(E);
7754   }
7755   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7756     return DerivedZeroInitialization(E);
7757   }
7758 
7759   /// A member expression where the object is a prvalue is itself a prvalue.
7760   bool VisitMemberExpr(const MemberExpr *E) {
7761     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7762            "missing temporary materialization conversion");
7763     assert(!E->isArrow() && "missing call to bound member function?");
7764 
7765     APValue Val;
7766     if (!Evaluate(Val, Info, E->getBase()))
7767       return false;
7768 
7769     QualType BaseTy = E->getBase()->getType();
7770 
7771     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7772     if (!FD) return Error(E);
7773     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7774     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7775            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7776 
7777     // Note: there is no lvalue base here. But this case should only ever
7778     // happen in C or in C++98, where we cannot be evaluating a constexpr
7779     // constructor, which is the only case the base matters.
7780     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7781     SubobjectDesignator Designator(BaseTy);
7782     Designator.addDeclUnchecked(FD);
7783 
7784     APValue Result;
7785     return extractSubobject(Info, E, Obj, Designator, Result) &&
7786            DerivedSuccess(Result, E);
7787   }
7788 
7789   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7790     APValue Val;
7791     if (!Evaluate(Val, Info, E->getBase()))
7792       return false;
7793 
7794     if (Val.isVector()) {
7795       SmallVector<uint32_t, 4> Indices;
7796       E->getEncodedElementAccess(Indices);
7797       if (Indices.size() == 1) {
7798         // Return scalar.
7799         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7800       } else {
7801         // Construct new APValue vector.
7802         SmallVector<APValue, 4> Elts;
7803         for (unsigned I = 0; I < Indices.size(); ++I) {
7804           Elts.push_back(Val.getVectorElt(Indices[I]));
7805         }
7806         APValue VecResult(Elts.data(), Indices.size());
7807         return DerivedSuccess(VecResult, E);
7808       }
7809     }
7810 
7811     return false;
7812   }
7813 
7814   bool VisitCastExpr(const CastExpr *E) {
7815     switch (E->getCastKind()) {
7816     default:
7817       break;
7818 
7819     case CK_AtomicToNonAtomic: {
7820       APValue AtomicVal;
7821       // This does not need to be done in place even for class/array types:
7822       // atomic-to-non-atomic conversion implies copying the object
7823       // representation.
7824       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7825         return false;
7826       return DerivedSuccess(AtomicVal, E);
7827     }
7828 
7829     case CK_NoOp:
7830     case CK_UserDefinedConversion:
7831       return StmtVisitorTy::Visit(E->getSubExpr());
7832 
7833     case CK_LValueToRValue: {
7834       LValue LVal;
7835       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7836         return false;
7837       APValue RVal;
7838       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7839       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7840                                           LVal, RVal))
7841         return false;
7842       return DerivedSuccess(RVal, E);
7843     }
7844     case CK_LValueToRValueBitCast: {
7845       APValue DestValue, SourceValue;
7846       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7847         return false;
7848       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7849         return false;
7850       return DerivedSuccess(DestValue, E);
7851     }
7852 
7853     case CK_AddressSpaceConversion: {
7854       APValue Value;
7855       if (!Evaluate(Value, Info, E->getSubExpr()))
7856         return false;
7857       return DerivedSuccess(Value, E);
7858     }
7859     }
7860 
7861     return Error(E);
7862   }
7863 
7864   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7865     return VisitUnaryPostIncDec(UO);
7866   }
7867   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7868     return VisitUnaryPostIncDec(UO);
7869   }
7870   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7871     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7872       return Error(UO);
7873 
7874     LValue LVal;
7875     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7876       return false;
7877     APValue RVal;
7878     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7879                       UO->isIncrementOp(), &RVal))
7880       return false;
7881     return DerivedSuccess(RVal, UO);
7882   }
7883 
7884   bool VisitStmtExpr(const StmtExpr *E) {
7885     // We will have checked the full-expressions inside the statement expression
7886     // when they were completed, and don't need to check them again now.
7887     llvm::SaveAndRestore<bool> NotCheckingForUB(
7888         Info.CheckingForUndefinedBehavior, false);
7889 
7890     const CompoundStmt *CS = E->getSubStmt();
7891     if (CS->body_empty())
7892       return true;
7893 
7894     BlockScopeRAII Scope(Info);
7895     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7896                                            BE = CS->body_end();
7897          /**/; ++BI) {
7898       if (BI + 1 == BE) {
7899         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7900         if (!FinalExpr) {
7901           Info.FFDiag((*BI)->getBeginLoc(),
7902                       diag::note_constexpr_stmt_expr_unsupported);
7903           return false;
7904         }
7905         return this->Visit(FinalExpr) && Scope.destroy();
7906       }
7907 
7908       APValue ReturnValue;
7909       StmtResult Result = { ReturnValue, nullptr };
7910       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7911       if (ESR != ESR_Succeeded) {
7912         // FIXME: If the statement-expression terminated due to 'return',
7913         // 'break', or 'continue', it would be nice to propagate that to
7914         // the outer statement evaluation rather than bailing out.
7915         if (ESR != ESR_Failed)
7916           Info.FFDiag((*BI)->getBeginLoc(),
7917                       diag::note_constexpr_stmt_expr_unsupported);
7918         return false;
7919       }
7920     }
7921 
7922     llvm_unreachable("Return from function from the loop above.");
7923   }
7924 
7925   /// Visit a value which is evaluated, but whose value is ignored.
7926   void VisitIgnoredValue(const Expr *E) {
7927     EvaluateIgnoredValue(Info, E);
7928   }
7929 
7930   /// Potentially visit a MemberExpr's base expression.
7931   void VisitIgnoredBaseExpression(const Expr *E) {
7932     // While MSVC doesn't evaluate the base expression, it does diagnose the
7933     // presence of side-effecting behavior.
7934     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7935       return;
7936     VisitIgnoredValue(E);
7937   }
7938 };
7939 
7940 } // namespace
7941 
7942 //===----------------------------------------------------------------------===//
7943 // Common base class for lvalue and temporary evaluation.
7944 //===----------------------------------------------------------------------===//
7945 namespace {
7946 template<class Derived>
7947 class LValueExprEvaluatorBase
7948   : public ExprEvaluatorBase<Derived> {
7949 protected:
7950   LValue &Result;
7951   bool InvalidBaseOK;
7952   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7953   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7954 
7955   bool Success(APValue::LValueBase B) {
7956     Result.set(B);
7957     return true;
7958   }
7959 
7960   bool evaluatePointer(const Expr *E, LValue &Result) {
7961     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7962   }
7963 
7964 public:
7965   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7966       : ExprEvaluatorBaseTy(Info), Result(Result),
7967         InvalidBaseOK(InvalidBaseOK) {}
7968 
7969   bool Success(const APValue &V, const Expr *E) {
7970     Result.setFrom(this->Info.Ctx, V);
7971     return true;
7972   }
7973 
7974   bool VisitMemberExpr(const MemberExpr *E) {
7975     // Handle non-static data members.
7976     QualType BaseTy;
7977     bool EvalOK;
7978     if (E->isArrow()) {
7979       EvalOK = evaluatePointer(E->getBase(), Result);
7980       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7981     } else if (E->getBase()->isPRValue()) {
7982       assert(E->getBase()->getType()->isRecordType());
7983       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7984       BaseTy = E->getBase()->getType();
7985     } else {
7986       EvalOK = this->Visit(E->getBase());
7987       BaseTy = E->getBase()->getType();
7988     }
7989     if (!EvalOK) {
7990       if (!InvalidBaseOK)
7991         return false;
7992       Result.setInvalid(E);
7993       return true;
7994     }
7995 
7996     const ValueDecl *MD = E->getMemberDecl();
7997     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7998       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7999              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8000       (void)BaseTy;
8001       if (!HandleLValueMember(this->Info, E, Result, FD))
8002         return false;
8003     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8004       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8005         return false;
8006     } else
8007       return this->Error(E);
8008 
8009     if (MD->getType()->isReferenceType()) {
8010       APValue RefValue;
8011       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8012                                           RefValue))
8013         return false;
8014       return Success(RefValue, E);
8015     }
8016     return true;
8017   }
8018 
8019   bool VisitBinaryOperator(const BinaryOperator *E) {
8020     switch (E->getOpcode()) {
8021     default:
8022       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8023 
8024     case BO_PtrMemD:
8025     case BO_PtrMemI:
8026       return HandleMemberPointerAccess(this->Info, E, Result);
8027     }
8028   }
8029 
8030   bool VisitCastExpr(const CastExpr *E) {
8031     switch (E->getCastKind()) {
8032     default:
8033       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8034 
8035     case CK_DerivedToBase:
8036     case CK_UncheckedDerivedToBase:
8037       if (!this->Visit(E->getSubExpr()))
8038         return false;
8039 
8040       // Now figure out the necessary offset to add to the base LV to get from
8041       // the derived class to the base class.
8042       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8043                                   Result);
8044     }
8045   }
8046 };
8047 }
8048 
8049 //===----------------------------------------------------------------------===//
8050 // LValue Evaluation
8051 //
8052 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8053 // function designators (in C), decl references to void objects (in C), and
8054 // temporaries (if building with -Wno-address-of-temporary).
8055 //
8056 // LValue evaluation produces values comprising a base expression of one of the
8057 // following types:
8058 // - Declarations
8059 //  * VarDecl
8060 //  * FunctionDecl
8061 // - Literals
8062 //  * CompoundLiteralExpr in C (and in global scope in C++)
8063 //  * StringLiteral
8064 //  * PredefinedExpr
8065 //  * ObjCStringLiteralExpr
8066 //  * ObjCEncodeExpr
8067 //  * AddrLabelExpr
8068 //  * BlockExpr
8069 //  * CallExpr for a MakeStringConstant builtin
8070 // - typeid(T) expressions, as TypeInfoLValues
8071 // - Locals and temporaries
8072 //  * MaterializeTemporaryExpr
8073 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8074 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8075 //    from the AST (FIXME).
8076 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8077 //    CallIndex, for a lifetime-extended temporary.
8078 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8079 //    immediate invocation.
8080 // plus an offset in bytes.
8081 //===----------------------------------------------------------------------===//
8082 namespace {
8083 class LValueExprEvaluator
8084   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8085 public:
8086   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8087     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8088 
8089   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8090   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8091 
8092   bool VisitDeclRefExpr(const DeclRefExpr *E);
8093   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8094   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8095   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8096   bool VisitMemberExpr(const MemberExpr *E);
8097   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8098   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8099   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8100   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8101   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8102   bool VisitUnaryDeref(const UnaryOperator *E);
8103   bool VisitUnaryReal(const UnaryOperator *E);
8104   bool VisitUnaryImag(const UnaryOperator *E);
8105   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8106     return VisitUnaryPreIncDec(UO);
8107   }
8108   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8109     return VisitUnaryPreIncDec(UO);
8110   }
8111   bool VisitBinAssign(const BinaryOperator *BO);
8112   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8113 
8114   bool VisitCastExpr(const CastExpr *E) {
8115     switch (E->getCastKind()) {
8116     default:
8117       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8118 
8119     case CK_LValueBitCast:
8120       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8121       if (!Visit(E->getSubExpr()))
8122         return false;
8123       Result.Designator.setInvalid();
8124       return true;
8125 
8126     case CK_BaseToDerived:
8127       if (!Visit(E->getSubExpr()))
8128         return false;
8129       return HandleBaseToDerivedCast(Info, E, Result);
8130 
8131     case CK_Dynamic:
8132       if (!Visit(E->getSubExpr()))
8133         return false;
8134       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8135     }
8136   }
8137 };
8138 } // end anonymous namespace
8139 
8140 /// Evaluate an expression as an lvalue. This can be legitimately called on
8141 /// expressions which are not glvalues, in three cases:
8142 ///  * function designators in C, and
8143 ///  * "extern void" objects
8144 ///  * @selector() expressions in Objective-C
8145 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8146                            bool InvalidBaseOK) {
8147   assert(!E->isValueDependent());
8148   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8149          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8150   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8151 }
8152 
8153 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8154   const NamedDecl *D = E->getDecl();
8155   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D))
8156     return Success(cast<ValueDecl>(D));
8157   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8158     return VisitVarDecl(E, VD);
8159   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8160     return Visit(BD->getBinding());
8161   return Error(E);
8162 }
8163 
8164 
8165 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8166 
8167   // If we are within a lambda's call operator, check whether the 'VD' referred
8168   // to within 'E' actually represents a lambda-capture that maps to a
8169   // data-member/field within the closure object, and if so, evaluate to the
8170   // field or what the field refers to.
8171   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8172       isa<DeclRefExpr>(E) &&
8173       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8174     // We don't always have a complete capture-map when checking or inferring if
8175     // the function call operator meets the requirements of a constexpr function
8176     // - but we don't need to evaluate the captures to determine constexprness
8177     // (dcl.constexpr C++17).
8178     if (Info.checkingPotentialConstantExpression())
8179       return false;
8180 
8181     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8182       // Start with 'Result' referring to the complete closure object...
8183       Result = *Info.CurrentCall->This;
8184       // ... then update it to refer to the field of the closure object
8185       // that represents the capture.
8186       if (!HandleLValueMember(Info, E, Result, FD))
8187         return false;
8188       // And if the field is of reference type, update 'Result' to refer to what
8189       // the field refers to.
8190       if (FD->getType()->isReferenceType()) {
8191         APValue RVal;
8192         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8193                                             RVal))
8194           return false;
8195         Result.setFrom(Info.Ctx, RVal);
8196       }
8197       return true;
8198     }
8199   }
8200 
8201   CallStackFrame *Frame = nullptr;
8202   unsigned Version = 0;
8203   if (VD->hasLocalStorage()) {
8204     // Only if a local variable was declared in the function currently being
8205     // evaluated, do we expect to be able to find its value in the current
8206     // frame. (Otherwise it was likely declared in an enclosing context and
8207     // could either have a valid evaluatable value (for e.g. a constexpr
8208     // variable) or be ill-formed (and trigger an appropriate evaluation
8209     // diagnostic)).
8210     CallStackFrame *CurrFrame = Info.CurrentCall;
8211     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8212       // Function parameters are stored in some caller's frame. (Usually the
8213       // immediate caller, but for an inherited constructor they may be more
8214       // distant.)
8215       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8216         if (CurrFrame->Arguments) {
8217           VD = CurrFrame->Arguments.getOrigParam(PVD);
8218           Frame =
8219               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8220           Version = CurrFrame->Arguments.Version;
8221         }
8222       } else {
8223         Frame = CurrFrame;
8224         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8225       }
8226     }
8227   }
8228 
8229   if (!VD->getType()->isReferenceType()) {
8230     if (Frame) {
8231       Result.set({VD, Frame->Index, Version});
8232       return true;
8233     }
8234     return Success(VD);
8235   }
8236 
8237   if (!Info.getLangOpts().CPlusPlus11) {
8238     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8239         << VD << VD->getType();
8240     Info.Note(VD->getLocation(), diag::note_declared_at);
8241   }
8242 
8243   APValue *V;
8244   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8245     return false;
8246   if (!V->hasValue()) {
8247     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8248     // adjust the diagnostic to say that.
8249     if (!Info.checkingPotentialConstantExpression())
8250       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8251     return false;
8252   }
8253   return Success(*V, E);
8254 }
8255 
8256 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8257     const MaterializeTemporaryExpr *E) {
8258   // Walk through the expression to find the materialized temporary itself.
8259   SmallVector<const Expr *, 2> CommaLHSs;
8260   SmallVector<SubobjectAdjustment, 2> Adjustments;
8261   const Expr *Inner =
8262       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8263 
8264   // If we passed any comma operators, evaluate their LHSs.
8265   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8266     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8267       return false;
8268 
8269   // A materialized temporary with static storage duration can appear within the
8270   // result of a constant expression evaluation, so we need to preserve its
8271   // value for use outside this evaluation.
8272   APValue *Value;
8273   if (E->getStorageDuration() == SD_Static) {
8274     // FIXME: What about SD_Thread?
8275     Value = E->getOrCreateValue(true);
8276     *Value = APValue();
8277     Result.set(E);
8278   } else {
8279     Value = &Info.CurrentCall->createTemporary(
8280         E, E->getType(),
8281         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8282                                                      : ScopeKind::Block,
8283         Result);
8284   }
8285 
8286   QualType Type = Inner->getType();
8287 
8288   // Materialize the temporary itself.
8289   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8290     *Value = APValue();
8291     return false;
8292   }
8293 
8294   // Adjust our lvalue to refer to the desired subobject.
8295   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8296     --I;
8297     switch (Adjustments[I].Kind) {
8298     case SubobjectAdjustment::DerivedToBaseAdjustment:
8299       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8300                                 Type, Result))
8301         return false;
8302       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8303       break;
8304 
8305     case SubobjectAdjustment::FieldAdjustment:
8306       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8307         return false;
8308       Type = Adjustments[I].Field->getType();
8309       break;
8310 
8311     case SubobjectAdjustment::MemberPointerAdjustment:
8312       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8313                                      Adjustments[I].Ptr.RHS))
8314         return false;
8315       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8316       break;
8317     }
8318   }
8319 
8320   return true;
8321 }
8322 
8323 bool
8324 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8325   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8326          "lvalue compound literal in c++?");
8327   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8328   // only see this when folding in C, so there's no standard to follow here.
8329   return Success(E);
8330 }
8331 
8332 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8333   TypeInfoLValue TypeInfo;
8334 
8335   if (!E->isPotentiallyEvaluated()) {
8336     if (E->isTypeOperand())
8337       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8338     else
8339       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8340   } else {
8341     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8342       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8343         << E->getExprOperand()->getType()
8344         << E->getExprOperand()->getSourceRange();
8345     }
8346 
8347     if (!Visit(E->getExprOperand()))
8348       return false;
8349 
8350     Optional<DynamicType> DynType =
8351         ComputeDynamicType(Info, E, Result, AK_TypeId);
8352     if (!DynType)
8353       return false;
8354 
8355     TypeInfo =
8356         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8357   }
8358 
8359   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8360 }
8361 
8362 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8363   return Success(E->getGuidDecl());
8364 }
8365 
8366 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8367   // Handle static data members.
8368   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8369     VisitIgnoredBaseExpression(E->getBase());
8370     return VisitVarDecl(E, VD);
8371   }
8372 
8373   // Handle static member functions.
8374   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8375     if (MD->isStatic()) {
8376       VisitIgnoredBaseExpression(E->getBase());
8377       return Success(MD);
8378     }
8379   }
8380 
8381   // Handle non-static data members.
8382   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8383 }
8384 
8385 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8386   // FIXME: Deal with vectors as array subscript bases.
8387   if (E->getBase()->getType()->isVectorType())
8388     return Error(E);
8389 
8390   APSInt Index;
8391   bool Success = true;
8392 
8393   // C++17's rules require us to evaluate the LHS first, regardless of which
8394   // side is the base.
8395   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8396     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8397                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8398       if (!Info.noteFailure())
8399         return false;
8400       Success = false;
8401     }
8402   }
8403 
8404   return Success &&
8405          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8406 }
8407 
8408 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8409   return evaluatePointer(E->getSubExpr(), Result);
8410 }
8411 
8412 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8413   if (!Visit(E->getSubExpr()))
8414     return false;
8415   // __real is a no-op on scalar lvalues.
8416   if (E->getSubExpr()->getType()->isAnyComplexType())
8417     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8418   return true;
8419 }
8420 
8421 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8422   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8423          "lvalue __imag__ on scalar?");
8424   if (!Visit(E->getSubExpr()))
8425     return false;
8426   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8427   return true;
8428 }
8429 
8430 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8431   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8432     return Error(UO);
8433 
8434   if (!this->Visit(UO->getSubExpr()))
8435     return false;
8436 
8437   return handleIncDec(
8438       this->Info, UO, Result, UO->getSubExpr()->getType(),
8439       UO->isIncrementOp(), nullptr);
8440 }
8441 
8442 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8443     const CompoundAssignOperator *CAO) {
8444   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8445     return Error(CAO);
8446 
8447   bool Success = true;
8448 
8449   // C++17 onwards require that we evaluate the RHS first.
8450   APValue RHS;
8451   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8452     if (!Info.noteFailure())
8453       return false;
8454     Success = false;
8455   }
8456 
8457   // The overall lvalue result is the result of evaluating the LHS.
8458   if (!this->Visit(CAO->getLHS()) || !Success)
8459     return false;
8460 
8461   return handleCompoundAssignment(
8462       this->Info, CAO,
8463       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8464       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8465 }
8466 
8467 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8468   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8469     return Error(E);
8470 
8471   bool Success = true;
8472 
8473   // C++17 onwards require that we evaluate the RHS first.
8474   APValue NewVal;
8475   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8476     if (!Info.noteFailure())
8477       return false;
8478     Success = false;
8479   }
8480 
8481   if (!this->Visit(E->getLHS()) || !Success)
8482     return false;
8483 
8484   if (Info.getLangOpts().CPlusPlus20 &&
8485       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8486     return false;
8487 
8488   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8489                           NewVal);
8490 }
8491 
8492 //===----------------------------------------------------------------------===//
8493 // Pointer Evaluation
8494 //===----------------------------------------------------------------------===//
8495 
8496 /// Attempts to compute the number of bytes available at the pointer
8497 /// returned by a function with the alloc_size attribute. Returns true if we
8498 /// were successful. Places an unsigned number into `Result`.
8499 ///
8500 /// This expects the given CallExpr to be a call to a function with an
8501 /// alloc_size attribute.
8502 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8503                                             const CallExpr *Call,
8504                                             llvm::APInt &Result) {
8505   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8506 
8507   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8508   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8509   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8510   if (Call->getNumArgs() <= SizeArgNo)
8511     return false;
8512 
8513   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8514     Expr::EvalResult ExprResult;
8515     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8516       return false;
8517     Into = ExprResult.Val.getInt();
8518     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8519       return false;
8520     Into = Into.zextOrSelf(BitsInSizeT);
8521     return true;
8522   };
8523 
8524   APSInt SizeOfElem;
8525   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8526     return false;
8527 
8528   if (!AllocSize->getNumElemsParam().isValid()) {
8529     Result = std::move(SizeOfElem);
8530     return true;
8531   }
8532 
8533   APSInt NumberOfElems;
8534   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8535   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8536     return false;
8537 
8538   bool Overflow;
8539   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8540   if (Overflow)
8541     return false;
8542 
8543   Result = std::move(BytesAvailable);
8544   return true;
8545 }
8546 
8547 /// Convenience function. LVal's base must be a call to an alloc_size
8548 /// function.
8549 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8550                                             const LValue &LVal,
8551                                             llvm::APInt &Result) {
8552   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8553          "Can't get the size of a non alloc_size function");
8554   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8555   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8556   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8557 }
8558 
8559 /// Attempts to evaluate the given LValueBase as the result of a call to
8560 /// a function with the alloc_size attribute. If it was possible to do so, this
8561 /// function will return true, make Result's Base point to said function call,
8562 /// and mark Result's Base as invalid.
8563 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8564                                       LValue &Result) {
8565   if (Base.isNull())
8566     return false;
8567 
8568   // Because we do no form of static analysis, we only support const variables.
8569   //
8570   // Additionally, we can't support parameters, nor can we support static
8571   // variables (in the latter case, use-before-assign isn't UB; in the former,
8572   // we have no clue what they'll be assigned to).
8573   const auto *VD =
8574       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8575   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8576     return false;
8577 
8578   const Expr *Init = VD->getAnyInitializer();
8579   if (!Init)
8580     return false;
8581 
8582   const Expr *E = Init->IgnoreParens();
8583   if (!tryUnwrapAllocSizeCall(E))
8584     return false;
8585 
8586   // Store E instead of E unwrapped so that the type of the LValue's base is
8587   // what the user wanted.
8588   Result.setInvalid(E);
8589 
8590   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8591   Result.addUnsizedArray(Info, E, Pointee);
8592   return true;
8593 }
8594 
8595 namespace {
8596 class PointerExprEvaluator
8597   : public ExprEvaluatorBase<PointerExprEvaluator> {
8598   LValue &Result;
8599   bool InvalidBaseOK;
8600 
8601   bool Success(const Expr *E) {
8602     Result.set(E);
8603     return true;
8604   }
8605 
8606   bool evaluateLValue(const Expr *E, LValue &Result) {
8607     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8608   }
8609 
8610   bool evaluatePointer(const Expr *E, LValue &Result) {
8611     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8612   }
8613 
8614   bool visitNonBuiltinCallExpr(const CallExpr *E);
8615 public:
8616 
8617   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8618       : ExprEvaluatorBaseTy(info), Result(Result),
8619         InvalidBaseOK(InvalidBaseOK) {}
8620 
8621   bool Success(const APValue &V, const Expr *E) {
8622     Result.setFrom(Info.Ctx, V);
8623     return true;
8624   }
8625   bool ZeroInitialization(const Expr *E) {
8626     Result.setNull(Info.Ctx, E->getType());
8627     return true;
8628   }
8629 
8630   bool VisitBinaryOperator(const BinaryOperator *E);
8631   bool VisitCastExpr(const CastExpr* E);
8632   bool VisitUnaryAddrOf(const UnaryOperator *E);
8633   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8634       { return Success(E); }
8635   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8636     if (E->isExpressibleAsConstantInitializer())
8637       return Success(E);
8638     if (Info.noteFailure())
8639       EvaluateIgnoredValue(Info, E->getSubExpr());
8640     return Error(E);
8641   }
8642   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8643       { return Success(E); }
8644   bool VisitCallExpr(const CallExpr *E);
8645   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8646   bool VisitBlockExpr(const BlockExpr *E) {
8647     if (!E->getBlockDecl()->hasCaptures())
8648       return Success(E);
8649     return Error(E);
8650   }
8651   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8652     // Can't look at 'this' when checking a potential constant expression.
8653     if (Info.checkingPotentialConstantExpression())
8654       return false;
8655     if (!Info.CurrentCall->This) {
8656       if (Info.getLangOpts().CPlusPlus11)
8657         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8658       else
8659         Info.FFDiag(E);
8660       return false;
8661     }
8662     Result = *Info.CurrentCall->This;
8663     // If we are inside a lambda's call operator, the 'this' expression refers
8664     // to the enclosing '*this' object (either by value or reference) which is
8665     // either copied into the closure object's field that represents the '*this'
8666     // or refers to '*this'.
8667     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8668       // Ensure we actually have captured 'this'. (an error will have
8669       // been previously reported if not).
8670       if (!Info.CurrentCall->LambdaThisCaptureField)
8671         return false;
8672 
8673       // Update 'Result' to refer to the data member/field of the closure object
8674       // that represents the '*this' capture.
8675       if (!HandleLValueMember(Info, E, Result,
8676                              Info.CurrentCall->LambdaThisCaptureField))
8677         return false;
8678       // If we captured '*this' by reference, replace the field with its referent.
8679       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8680               ->isPointerType()) {
8681         APValue RVal;
8682         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8683                                             RVal))
8684           return false;
8685 
8686         Result.setFrom(Info.Ctx, RVal);
8687       }
8688     }
8689     return true;
8690   }
8691 
8692   bool VisitCXXNewExpr(const CXXNewExpr *E);
8693 
8694   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8695     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8696     APValue LValResult = E->EvaluateInContext(
8697         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8698     Result.setFrom(Info.Ctx, LValResult);
8699     return true;
8700   }
8701 
8702   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8703     std::string ResultStr = E->ComputeName(Info.Ctx);
8704 
8705     QualType CharTy = Info.Ctx.CharTy.withConst();
8706     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8707                ResultStr.size() + 1);
8708     QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8709                                                      ArrayType::Normal, 0);
8710 
8711     StringLiteral *SL =
8712         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii,
8713                               /*Pascal*/ false, ArrayTy, E->getLocation());
8714 
8715     evaluateLValue(SL, Result);
8716     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8717     return true;
8718   }
8719 
8720   // FIXME: Missing: @protocol, @selector
8721 };
8722 } // end anonymous namespace
8723 
8724 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8725                             bool InvalidBaseOK) {
8726   assert(!E->isValueDependent());
8727   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
8728   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8729 }
8730 
8731 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8732   if (E->getOpcode() != BO_Add &&
8733       E->getOpcode() != BO_Sub)
8734     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8735 
8736   const Expr *PExp = E->getLHS();
8737   const Expr *IExp = E->getRHS();
8738   if (IExp->getType()->isPointerType())
8739     std::swap(PExp, IExp);
8740 
8741   bool EvalPtrOK = evaluatePointer(PExp, Result);
8742   if (!EvalPtrOK && !Info.noteFailure())
8743     return false;
8744 
8745   llvm::APSInt Offset;
8746   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8747     return false;
8748 
8749   if (E->getOpcode() == BO_Sub)
8750     negateAsSigned(Offset);
8751 
8752   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8753   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8754 }
8755 
8756 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8757   return evaluateLValue(E->getSubExpr(), Result);
8758 }
8759 
8760 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8761   const Expr *SubExpr = E->getSubExpr();
8762 
8763   switch (E->getCastKind()) {
8764   default:
8765     break;
8766   case CK_BitCast:
8767   case CK_CPointerToObjCPointerCast:
8768   case CK_BlockPointerToObjCPointerCast:
8769   case CK_AnyPointerToBlockPointerCast:
8770   case CK_AddressSpaceConversion:
8771     if (!Visit(SubExpr))
8772       return false;
8773     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8774     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8775     // also static_casts, but we disallow them as a resolution to DR1312.
8776     if (!E->getType()->isVoidPointerType()) {
8777       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8778           !Result.IsNullPtr &&
8779           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8780                                           E->getType()->getPointeeType()) &&
8781           Info.getStdAllocatorCaller("allocate")) {
8782         // Inside a call to std::allocator::allocate and friends, we permit
8783         // casting from void* back to cv1 T* for a pointer that points to a
8784         // cv2 T.
8785       } else {
8786         Result.Designator.setInvalid();
8787         if (SubExpr->getType()->isVoidPointerType())
8788           CCEDiag(E, diag::note_constexpr_invalid_cast)
8789             << 3 << SubExpr->getType();
8790         else
8791           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8792       }
8793     }
8794     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8795       ZeroInitialization(E);
8796     return true;
8797 
8798   case CK_DerivedToBase:
8799   case CK_UncheckedDerivedToBase:
8800     if (!evaluatePointer(E->getSubExpr(), Result))
8801       return false;
8802     if (!Result.Base && Result.Offset.isZero())
8803       return true;
8804 
8805     // Now figure out the necessary offset to add to the base LV to get from
8806     // the derived class to the base class.
8807     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8808                                   castAs<PointerType>()->getPointeeType(),
8809                                 Result);
8810 
8811   case CK_BaseToDerived:
8812     if (!Visit(E->getSubExpr()))
8813       return false;
8814     if (!Result.Base && Result.Offset.isZero())
8815       return true;
8816     return HandleBaseToDerivedCast(Info, E, Result);
8817 
8818   case CK_Dynamic:
8819     if (!Visit(E->getSubExpr()))
8820       return false;
8821     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8822 
8823   case CK_NullToPointer:
8824     VisitIgnoredValue(E->getSubExpr());
8825     return ZeroInitialization(E);
8826 
8827   case CK_IntegralToPointer: {
8828     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8829 
8830     APValue Value;
8831     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8832       break;
8833 
8834     if (Value.isInt()) {
8835       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8836       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8837       Result.Base = (Expr*)nullptr;
8838       Result.InvalidBase = false;
8839       Result.Offset = CharUnits::fromQuantity(N);
8840       Result.Designator.setInvalid();
8841       Result.IsNullPtr = false;
8842       return true;
8843     } else {
8844       // Cast is of an lvalue, no need to change value.
8845       Result.setFrom(Info.Ctx, Value);
8846       return true;
8847     }
8848   }
8849 
8850   case CK_ArrayToPointerDecay: {
8851     if (SubExpr->isGLValue()) {
8852       if (!evaluateLValue(SubExpr, Result))
8853         return false;
8854     } else {
8855       APValue &Value = Info.CurrentCall->createTemporary(
8856           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8857       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8858         return false;
8859     }
8860     // The result is a pointer to the first element of the array.
8861     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8862     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8863       Result.addArray(Info, E, CAT);
8864     else
8865       Result.addUnsizedArray(Info, E, AT->getElementType());
8866     return true;
8867   }
8868 
8869   case CK_FunctionToPointerDecay:
8870     return evaluateLValue(SubExpr, Result);
8871 
8872   case CK_LValueToRValue: {
8873     LValue LVal;
8874     if (!evaluateLValue(E->getSubExpr(), LVal))
8875       return false;
8876 
8877     APValue RVal;
8878     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8879     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8880                                         LVal, RVal))
8881       return InvalidBaseOK &&
8882              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8883     return Success(RVal, E);
8884   }
8885   }
8886 
8887   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8888 }
8889 
8890 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8891                                 UnaryExprOrTypeTrait ExprKind) {
8892   // C++ [expr.alignof]p3:
8893   //     When alignof is applied to a reference type, the result is the
8894   //     alignment of the referenced type.
8895   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8896     T = Ref->getPointeeType();
8897 
8898   if (T.getQualifiers().hasUnaligned())
8899     return CharUnits::One();
8900 
8901   const bool AlignOfReturnsPreferred =
8902       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8903 
8904   // __alignof is defined to return the preferred alignment.
8905   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8906   // as well.
8907   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8908     return Info.Ctx.toCharUnitsFromBits(
8909       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8910   // alignof and _Alignof are defined to return the ABI alignment.
8911   else if (ExprKind == UETT_AlignOf)
8912     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8913   else
8914     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8915 }
8916 
8917 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8918                                 UnaryExprOrTypeTrait ExprKind) {
8919   E = E->IgnoreParens();
8920 
8921   // The kinds of expressions that we have special-case logic here for
8922   // should be kept up to date with the special checks for those
8923   // expressions in Sema.
8924 
8925   // alignof decl is always accepted, even if it doesn't make sense: we default
8926   // to 1 in those cases.
8927   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8928     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8929                                  /*RefAsPointee*/true);
8930 
8931   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8932     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8933                                  /*RefAsPointee*/true);
8934 
8935   return GetAlignOfType(Info, E->getType(), ExprKind);
8936 }
8937 
8938 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8939   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8940     return Info.Ctx.getDeclAlign(VD);
8941   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8942     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8943   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8944 }
8945 
8946 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8947 /// __builtin_is_aligned and __builtin_assume_aligned.
8948 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8949                                  EvalInfo &Info, APSInt &Alignment) {
8950   if (!EvaluateInteger(E, Alignment, Info))
8951     return false;
8952   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8953     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8954     return false;
8955   }
8956   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8957   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8958   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8959     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8960         << MaxValue << ForType << Alignment;
8961     return false;
8962   }
8963   // Ensure both alignment and source value have the same bit width so that we
8964   // don't assert when computing the resulting value.
8965   APSInt ExtAlignment =
8966       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8967   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8968          "Alignment should not be changed by ext/trunc");
8969   Alignment = ExtAlignment;
8970   assert(Alignment.getBitWidth() == SrcWidth);
8971   return true;
8972 }
8973 
8974 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8975 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8976   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8977     return true;
8978 
8979   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8980     return false;
8981 
8982   Result.setInvalid(E);
8983   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8984   Result.addUnsizedArray(Info, E, PointeeTy);
8985   return true;
8986 }
8987 
8988 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8989   if (IsConstantCall(E))
8990     return Success(E);
8991 
8992   if (unsigned BuiltinOp = E->getBuiltinCallee())
8993     return VisitBuiltinCallExpr(E, BuiltinOp);
8994 
8995   return visitNonBuiltinCallExpr(E);
8996 }
8997 
8998 // Determine if T is a character type for which we guarantee that
8999 // sizeof(T) == 1.
9000 static bool isOneByteCharacterType(QualType T) {
9001   return T->isCharType() || T->isChar8Type();
9002 }
9003 
9004 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9005                                                 unsigned BuiltinOp) {
9006   switch (BuiltinOp) {
9007   case Builtin::BI__builtin_addressof:
9008     return evaluateLValue(E->getArg(0), Result);
9009   case Builtin::BI__builtin_assume_aligned: {
9010     // We need to be very careful here because: if the pointer does not have the
9011     // asserted alignment, then the behavior is undefined, and undefined
9012     // behavior is non-constant.
9013     if (!evaluatePointer(E->getArg(0), Result))
9014       return false;
9015 
9016     LValue OffsetResult(Result);
9017     APSInt Alignment;
9018     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9019                               Alignment))
9020       return false;
9021     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9022 
9023     if (E->getNumArgs() > 2) {
9024       APSInt Offset;
9025       if (!EvaluateInteger(E->getArg(2), Offset, Info))
9026         return false;
9027 
9028       int64_t AdditionalOffset = -Offset.getZExtValue();
9029       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9030     }
9031 
9032     // If there is a base object, then it must have the correct alignment.
9033     if (OffsetResult.Base) {
9034       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9035 
9036       if (BaseAlignment < Align) {
9037         Result.Designator.setInvalid();
9038         // FIXME: Add support to Diagnostic for long / long long.
9039         CCEDiag(E->getArg(0),
9040                 diag::note_constexpr_baa_insufficient_alignment) << 0
9041           << (unsigned)BaseAlignment.getQuantity()
9042           << (unsigned)Align.getQuantity();
9043         return false;
9044       }
9045     }
9046 
9047     // The offset must also have the correct alignment.
9048     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9049       Result.Designator.setInvalid();
9050 
9051       (OffsetResult.Base
9052            ? CCEDiag(E->getArg(0),
9053                      diag::note_constexpr_baa_insufficient_alignment) << 1
9054            : CCEDiag(E->getArg(0),
9055                      diag::note_constexpr_baa_value_insufficient_alignment))
9056         << (int)OffsetResult.Offset.getQuantity()
9057         << (unsigned)Align.getQuantity();
9058       return false;
9059     }
9060 
9061     return true;
9062   }
9063   case Builtin::BI__builtin_align_up:
9064   case Builtin::BI__builtin_align_down: {
9065     if (!evaluatePointer(E->getArg(0), Result))
9066       return false;
9067     APSInt Alignment;
9068     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9069                               Alignment))
9070       return false;
9071     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9072     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9073     // For align_up/align_down, we can return the same value if the alignment
9074     // is known to be greater or equal to the requested value.
9075     if (PtrAlign.getQuantity() >= Alignment)
9076       return true;
9077 
9078     // The alignment could be greater than the minimum at run-time, so we cannot
9079     // infer much about the resulting pointer value. One case is possible:
9080     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9081     // can infer the correct index if the requested alignment is smaller than
9082     // the base alignment so we can perform the computation on the offset.
9083     if (BaseAlignment.getQuantity() >= Alignment) {
9084       assert(Alignment.getBitWidth() <= 64 &&
9085              "Cannot handle > 64-bit address-space");
9086       uint64_t Alignment64 = Alignment.getZExtValue();
9087       CharUnits NewOffset = CharUnits::fromQuantity(
9088           BuiltinOp == Builtin::BI__builtin_align_down
9089               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9090               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9091       Result.adjustOffset(NewOffset - Result.Offset);
9092       // TODO: diagnose out-of-bounds values/only allow for arrays?
9093       return true;
9094     }
9095     // Otherwise, we cannot constant-evaluate the result.
9096     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9097         << Alignment;
9098     return false;
9099   }
9100   case Builtin::BI__builtin_operator_new:
9101     return HandleOperatorNewCall(Info, E, Result);
9102   case Builtin::BI__builtin_launder:
9103     return evaluatePointer(E->getArg(0), Result);
9104   case Builtin::BIstrchr:
9105   case Builtin::BIwcschr:
9106   case Builtin::BImemchr:
9107   case Builtin::BIwmemchr:
9108     if (Info.getLangOpts().CPlusPlus11)
9109       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9110         << /*isConstexpr*/0 << /*isConstructor*/0
9111         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9112     else
9113       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9114     LLVM_FALLTHROUGH;
9115   case Builtin::BI__builtin_strchr:
9116   case Builtin::BI__builtin_wcschr:
9117   case Builtin::BI__builtin_memchr:
9118   case Builtin::BI__builtin_char_memchr:
9119   case Builtin::BI__builtin_wmemchr: {
9120     if (!Visit(E->getArg(0)))
9121       return false;
9122     APSInt Desired;
9123     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9124       return false;
9125     uint64_t MaxLength = uint64_t(-1);
9126     if (BuiltinOp != Builtin::BIstrchr &&
9127         BuiltinOp != Builtin::BIwcschr &&
9128         BuiltinOp != Builtin::BI__builtin_strchr &&
9129         BuiltinOp != Builtin::BI__builtin_wcschr) {
9130       APSInt N;
9131       if (!EvaluateInteger(E->getArg(2), N, Info))
9132         return false;
9133       MaxLength = N.getExtValue();
9134     }
9135     // We cannot find the value if there are no candidates to match against.
9136     if (MaxLength == 0u)
9137       return ZeroInitialization(E);
9138     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9139         Result.Designator.Invalid)
9140       return false;
9141     QualType CharTy = Result.Designator.getType(Info.Ctx);
9142     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9143                      BuiltinOp == Builtin::BI__builtin_memchr;
9144     assert(IsRawByte ||
9145            Info.Ctx.hasSameUnqualifiedType(
9146                CharTy, E->getArg(0)->getType()->getPointeeType()));
9147     // Pointers to const void may point to objects of incomplete type.
9148     if (IsRawByte && CharTy->isIncompleteType()) {
9149       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9150       return false;
9151     }
9152     // Give up on byte-oriented matching against multibyte elements.
9153     // FIXME: We can compare the bytes in the correct order.
9154     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9155       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9156           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9157           << CharTy;
9158       return false;
9159     }
9160     // Figure out what value we're actually looking for (after converting to
9161     // the corresponding unsigned type if necessary).
9162     uint64_t DesiredVal;
9163     bool StopAtNull = false;
9164     switch (BuiltinOp) {
9165     case Builtin::BIstrchr:
9166     case Builtin::BI__builtin_strchr:
9167       // strchr compares directly to the passed integer, and therefore
9168       // always fails if given an int that is not a char.
9169       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9170                                                   E->getArg(1)->getType(),
9171                                                   Desired),
9172                                Desired))
9173         return ZeroInitialization(E);
9174       StopAtNull = true;
9175       LLVM_FALLTHROUGH;
9176     case Builtin::BImemchr:
9177     case Builtin::BI__builtin_memchr:
9178     case Builtin::BI__builtin_char_memchr:
9179       // memchr compares by converting both sides to unsigned char. That's also
9180       // correct for strchr if we get this far (to cope with plain char being
9181       // unsigned in the strchr case).
9182       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9183       break;
9184 
9185     case Builtin::BIwcschr:
9186     case Builtin::BI__builtin_wcschr:
9187       StopAtNull = true;
9188       LLVM_FALLTHROUGH;
9189     case Builtin::BIwmemchr:
9190     case Builtin::BI__builtin_wmemchr:
9191       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9192       DesiredVal = Desired.getZExtValue();
9193       break;
9194     }
9195 
9196     for (; MaxLength; --MaxLength) {
9197       APValue Char;
9198       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9199           !Char.isInt())
9200         return false;
9201       if (Char.getInt().getZExtValue() == DesiredVal)
9202         return true;
9203       if (StopAtNull && !Char.getInt())
9204         break;
9205       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9206         return false;
9207     }
9208     // Not found: return nullptr.
9209     return ZeroInitialization(E);
9210   }
9211 
9212   case Builtin::BImemcpy:
9213   case Builtin::BImemmove:
9214   case Builtin::BIwmemcpy:
9215   case Builtin::BIwmemmove:
9216     if (Info.getLangOpts().CPlusPlus11)
9217       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9218         << /*isConstexpr*/0 << /*isConstructor*/0
9219         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9220     else
9221       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9222     LLVM_FALLTHROUGH;
9223   case Builtin::BI__builtin_memcpy:
9224   case Builtin::BI__builtin_memmove:
9225   case Builtin::BI__builtin_wmemcpy:
9226   case Builtin::BI__builtin_wmemmove: {
9227     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9228                  BuiltinOp == Builtin::BIwmemmove ||
9229                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9230                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9231     bool Move = BuiltinOp == Builtin::BImemmove ||
9232                 BuiltinOp == Builtin::BIwmemmove ||
9233                 BuiltinOp == Builtin::BI__builtin_memmove ||
9234                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9235 
9236     // The result of mem* is the first argument.
9237     if (!Visit(E->getArg(0)))
9238       return false;
9239     LValue Dest = Result;
9240 
9241     LValue Src;
9242     if (!EvaluatePointer(E->getArg(1), Src, Info))
9243       return false;
9244 
9245     APSInt N;
9246     if (!EvaluateInteger(E->getArg(2), N, Info))
9247       return false;
9248     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9249 
9250     // If the size is zero, we treat this as always being a valid no-op.
9251     // (Even if one of the src and dest pointers is null.)
9252     if (!N)
9253       return true;
9254 
9255     // Otherwise, if either of the operands is null, we can't proceed. Don't
9256     // try to determine the type of the copied objects, because there aren't
9257     // any.
9258     if (!Src.Base || !Dest.Base) {
9259       APValue Val;
9260       (!Src.Base ? Src : Dest).moveInto(Val);
9261       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9262           << Move << WChar << !!Src.Base
9263           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9264       return false;
9265     }
9266     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9267       return false;
9268 
9269     // We require that Src and Dest are both pointers to arrays of
9270     // trivially-copyable type. (For the wide version, the designator will be
9271     // invalid if the designated object is not a wchar_t.)
9272     QualType T = Dest.Designator.getType(Info.Ctx);
9273     QualType SrcT = Src.Designator.getType(Info.Ctx);
9274     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9275       // FIXME: Consider using our bit_cast implementation to support this.
9276       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9277       return false;
9278     }
9279     if (T->isIncompleteType()) {
9280       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9281       return false;
9282     }
9283     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9284       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9285       return false;
9286     }
9287 
9288     // Figure out how many T's we're copying.
9289     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9290     if (!WChar) {
9291       uint64_t Remainder;
9292       llvm::APInt OrigN = N;
9293       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9294       if (Remainder) {
9295         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9296             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9297             << (unsigned)TSize;
9298         return false;
9299       }
9300     }
9301 
9302     // Check that the copying will remain within the arrays, just so that we
9303     // can give a more meaningful diagnostic. This implicitly also checks that
9304     // N fits into 64 bits.
9305     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9306     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9307     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9308       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9309           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9310           << toString(N, 10, /*Signed*/false);
9311       return false;
9312     }
9313     uint64_t NElems = N.getZExtValue();
9314     uint64_t NBytes = NElems * TSize;
9315 
9316     // Check for overlap.
9317     int Direction = 1;
9318     if (HasSameBase(Src, Dest)) {
9319       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9320       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9321       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9322         // Dest is inside the source region.
9323         if (!Move) {
9324           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9325           return false;
9326         }
9327         // For memmove and friends, copy backwards.
9328         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9329             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9330           return false;
9331         Direction = -1;
9332       } else if (!Move && SrcOffset >= DestOffset &&
9333                  SrcOffset - DestOffset < NBytes) {
9334         // Src is inside the destination region for memcpy: invalid.
9335         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9336         return false;
9337       }
9338     }
9339 
9340     while (true) {
9341       APValue Val;
9342       // FIXME: Set WantObjectRepresentation to true if we're copying a
9343       // char-like type?
9344       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9345           !handleAssignment(Info, E, Dest, T, Val))
9346         return false;
9347       // Do not iterate past the last element; if we're copying backwards, that
9348       // might take us off the start of the array.
9349       if (--NElems == 0)
9350         return true;
9351       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9352           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9353         return false;
9354     }
9355   }
9356 
9357   default:
9358     break;
9359   }
9360 
9361   return visitNonBuiltinCallExpr(E);
9362 }
9363 
9364 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9365                                      APValue &Result, const InitListExpr *ILE,
9366                                      QualType AllocType);
9367 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9368                                           APValue &Result,
9369                                           const CXXConstructExpr *CCE,
9370                                           QualType AllocType);
9371 
9372 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9373   if (!Info.getLangOpts().CPlusPlus20)
9374     Info.CCEDiag(E, diag::note_constexpr_new);
9375 
9376   // We cannot speculatively evaluate a delete expression.
9377   if (Info.SpeculativeEvaluationDepth)
9378     return false;
9379 
9380   FunctionDecl *OperatorNew = E->getOperatorNew();
9381 
9382   bool IsNothrow = false;
9383   bool IsPlacement = false;
9384   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9385       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9386     // FIXME Support array placement new.
9387     assert(E->getNumPlacementArgs() == 1);
9388     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9389       return false;
9390     if (Result.Designator.Invalid)
9391       return false;
9392     IsPlacement = true;
9393   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9394     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9395         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9396     return false;
9397   } else if (E->getNumPlacementArgs()) {
9398     // The only new-placement list we support is of the form (std::nothrow).
9399     //
9400     // FIXME: There is no restriction on this, but it's not clear that any
9401     // other form makes any sense. We get here for cases such as:
9402     //
9403     //   new (std::align_val_t{N}) X(int)
9404     //
9405     // (which should presumably be valid only if N is a multiple of
9406     // alignof(int), and in any case can't be deallocated unless N is
9407     // alignof(X) and X has new-extended alignment).
9408     if (E->getNumPlacementArgs() != 1 ||
9409         !E->getPlacementArg(0)->getType()->isNothrowT())
9410       return Error(E, diag::note_constexpr_new_placement);
9411 
9412     LValue Nothrow;
9413     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9414       return false;
9415     IsNothrow = true;
9416   }
9417 
9418   const Expr *Init = E->getInitializer();
9419   const InitListExpr *ResizedArrayILE = nullptr;
9420   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9421   bool ValueInit = false;
9422 
9423   QualType AllocType = E->getAllocatedType();
9424   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
9425     const Expr *Stripped = *ArraySize;
9426     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9427          Stripped = ICE->getSubExpr())
9428       if (ICE->getCastKind() != CK_NoOp &&
9429           ICE->getCastKind() != CK_IntegralCast)
9430         break;
9431 
9432     llvm::APSInt ArrayBound;
9433     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9434       return false;
9435 
9436     // C++ [expr.new]p9:
9437     //   The expression is erroneous if:
9438     //   -- [...] its value before converting to size_t [or] applying the
9439     //      second standard conversion sequence is less than zero
9440     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9441       if (IsNothrow)
9442         return ZeroInitialization(E);
9443 
9444       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9445           << ArrayBound << (*ArraySize)->getSourceRange();
9446       return false;
9447     }
9448 
9449     //   -- its value is such that the size of the allocated object would
9450     //      exceed the implementation-defined limit
9451     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9452                                                 ArrayBound) >
9453         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9454       if (IsNothrow)
9455         return ZeroInitialization(E);
9456 
9457       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9458         << ArrayBound << (*ArraySize)->getSourceRange();
9459       return false;
9460     }
9461 
9462     //   -- the new-initializer is a braced-init-list and the number of
9463     //      array elements for which initializers are provided [...]
9464     //      exceeds the number of elements to initialize
9465     if (!Init) {
9466       // No initialization is performed.
9467     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9468                isa<ImplicitValueInitExpr>(Init)) {
9469       ValueInit = true;
9470     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9471       ResizedArrayCCE = CCE;
9472     } else {
9473       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9474       assert(CAT && "unexpected type for array initializer");
9475 
9476       unsigned Bits =
9477           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9478       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9479       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9480       if (InitBound.ugt(AllocBound)) {
9481         if (IsNothrow)
9482           return ZeroInitialization(E);
9483 
9484         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9485             << toString(AllocBound, 10, /*Signed=*/false)
9486             << toString(InitBound, 10, /*Signed=*/false)
9487             << (*ArraySize)->getSourceRange();
9488         return false;
9489       }
9490 
9491       // If the sizes differ, we must have an initializer list, and we need
9492       // special handling for this case when we initialize.
9493       if (InitBound != AllocBound)
9494         ResizedArrayILE = cast<InitListExpr>(Init);
9495     }
9496 
9497     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9498                                               ArrayType::Normal, 0);
9499   } else {
9500     assert(!AllocType->isArrayType() &&
9501            "array allocation with non-array new");
9502   }
9503 
9504   APValue *Val;
9505   if (IsPlacement) {
9506     AccessKinds AK = AK_Construct;
9507     struct FindObjectHandler {
9508       EvalInfo &Info;
9509       const Expr *E;
9510       QualType AllocType;
9511       const AccessKinds AccessKind;
9512       APValue *Value;
9513 
9514       typedef bool result_type;
9515       bool failed() { return false; }
9516       bool found(APValue &Subobj, QualType SubobjType) {
9517         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9518         // old name of the object to be used to name the new object.
9519         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9520           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9521             SubobjType << AllocType;
9522           return false;
9523         }
9524         Value = &Subobj;
9525         return true;
9526       }
9527       bool found(APSInt &Value, QualType SubobjType) {
9528         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9529         return false;
9530       }
9531       bool found(APFloat &Value, QualType SubobjType) {
9532         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9533         return false;
9534       }
9535     } Handler = {Info, E, AllocType, AK, nullptr};
9536 
9537     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9538     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9539       return false;
9540 
9541     Val = Handler.Value;
9542 
9543     // [basic.life]p1:
9544     //   The lifetime of an object o of type T ends when [...] the storage
9545     //   which the object occupies is [...] reused by an object that is not
9546     //   nested within o (6.6.2).
9547     *Val = APValue();
9548   } else {
9549     // Perform the allocation and obtain a pointer to the resulting object.
9550     Val = Info.createHeapAlloc(E, AllocType, Result);
9551     if (!Val)
9552       return false;
9553   }
9554 
9555   if (ValueInit) {
9556     ImplicitValueInitExpr VIE(AllocType);
9557     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9558       return false;
9559   } else if (ResizedArrayILE) {
9560     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9561                                   AllocType))
9562       return false;
9563   } else if (ResizedArrayCCE) {
9564     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9565                                        AllocType))
9566       return false;
9567   } else if (Init) {
9568     if (!EvaluateInPlace(*Val, Info, Result, Init))
9569       return false;
9570   } else if (!getDefaultInitValue(AllocType, *Val)) {
9571     return false;
9572   }
9573 
9574   // Array new returns a pointer to the first element, not a pointer to the
9575   // array.
9576   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9577     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9578 
9579   return true;
9580 }
9581 //===----------------------------------------------------------------------===//
9582 // Member Pointer Evaluation
9583 //===----------------------------------------------------------------------===//
9584 
9585 namespace {
9586 class MemberPointerExprEvaluator
9587   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9588   MemberPtr &Result;
9589 
9590   bool Success(const ValueDecl *D) {
9591     Result = MemberPtr(D);
9592     return true;
9593   }
9594 public:
9595 
9596   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9597     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9598 
9599   bool Success(const APValue &V, const Expr *E) {
9600     Result.setFrom(V);
9601     return true;
9602   }
9603   bool ZeroInitialization(const Expr *E) {
9604     return Success((const ValueDecl*)nullptr);
9605   }
9606 
9607   bool VisitCastExpr(const CastExpr *E);
9608   bool VisitUnaryAddrOf(const UnaryOperator *E);
9609 };
9610 } // end anonymous namespace
9611 
9612 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9613                                   EvalInfo &Info) {
9614   assert(!E->isValueDependent());
9615   assert(E->isPRValue() && E->getType()->isMemberPointerType());
9616   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9617 }
9618 
9619 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9620   switch (E->getCastKind()) {
9621   default:
9622     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9623 
9624   case CK_NullToMemberPointer:
9625     VisitIgnoredValue(E->getSubExpr());
9626     return ZeroInitialization(E);
9627 
9628   case CK_BaseToDerivedMemberPointer: {
9629     if (!Visit(E->getSubExpr()))
9630       return false;
9631     if (E->path_empty())
9632       return true;
9633     // Base-to-derived member pointer casts store the path in derived-to-base
9634     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9635     // the wrong end of the derived->base arc, so stagger the path by one class.
9636     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9637     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9638          PathI != PathE; ++PathI) {
9639       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9640       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9641       if (!Result.castToDerived(Derived))
9642         return Error(E);
9643     }
9644     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9645     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9646       return Error(E);
9647     return true;
9648   }
9649 
9650   case CK_DerivedToBaseMemberPointer:
9651     if (!Visit(E->getSubExpr()))
9652       return false;
9653     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9654          PathE = E->path_end(); PathI != PathE; ++PathI) {
9655       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9656       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9657       if (!Result.castToBase(Base))
9658         return Error(E);
9659     }
9660     return true;
9661   }
9662 }
9663 
9664 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9665   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9666   // member can be formed.
9667   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9668 }
9669 
9670 //===----------------------------------------------------------------------===//
9671 // Record Evaluation
9672 //===----------------------------------------------------------------------===//
9673 
9674 namespace {
9675   class RecordExprEvaluator
9676   : public ExprEvaluatorBase<RecordExprEvaluator> {
9677     const LValue &This;
9678     APValue &Result;
9679   public:
9680 
9681     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9682       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9683 
9684     bool Success(const APValue &V, const Expr *E) {
9685       Result = V;
9686       return true;
9687     }
9688     bool ZeroInitialization(const Expr *E) {
9689       return ZeroInitialization(E, E->getType());
9690     }
9691     bool ZeroInitialization(const Expr *E, QualType T);
9692 
9693     bool VisitCallExpr(const CallExpr *E) {
9694       return handleCallExpr(E, Result, &This);
9695     }
9696     bool VisitCastExpr(const CastExpr *E);
9697     bool VisitInitListExpr(const InitListExpr *E);
9698     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9699       return VisitCXXConstructExpr(E, E->getType());
9700     }
9701     bool VisitLambdaExpr(const LambdaExpr *E);
9702     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9703     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9704     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9705     bool VisitBinCmp(const BinaryOperator *E);
9706   };
9707 }
9708 
9709 /// Perform zero-initialization on an object of non-union class type.
9710 /// C++11 [dcl.init]p5:
9711 ///  To zero-initialize an object or reference of type T means:
9712 ///    [...]
9713 ///    -- if T is a (possibly cv-qualified) non-union class type,
9714 ///       each non-static data member and each base-class subobject is
9715 ///       zero-initialized
9716 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9717                                           const RecordDecl *RD,
9718                                           const LValue &This, APValue &Result) {
9719   assert(!RD->isUnion() && "Expected non-union class type");
9720   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9721   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9722                    std::distance(RD->field_begin(), RD->field_end()));
9723 
9724   if (RD->isInvalidDecl()) return false;
9725   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9726 
9727   if (CD) {
9728     unsigned Index = 0;
9729     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9730            End = CD->bases_end(); I != End; ++I, ++Index) {
9731       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9732       LValue Subobject = This;
9733       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9734         return false;
9735       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9736                                          Result.getStructBase(Index)))
9737         return false;
9738     }
9739   }
9740 
9741   for (const auto *I : RD->fields()) {
9742     // -- if T is a reference type, no initialization is performed.
9743     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9744       continue;
9745 
9746     LValue Subobject = This;
9747     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9748       return false;
9749 
9750     ImplicitValueInitExpr VIE(I->getType());
9751     if (!EvaluateInPlace(
9752           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9753       return false;
9754   }
9755 
9756   return true;
9757 }
9758 
9759 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9760   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9761   if (RD->isInvalidDecl()) return false;
9762   if (RD->isUnion()) {
9763     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9764     // object's first non-static named data member is zero-initialized
9765     RecordDecl::field_iterator I = RD->field_begin();
9766     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9767       ++I;
9768     if (I == RD->field_end()) {
9769       Result = APValue((const FieldDecl*)nullptr);
9770       return true;
9771     }
9772 
9773     LValue Subobject = This;
9774     if (!HandleLValueMember(Info, E, Subobject, *I))
9775       return false;
9776     Result = APValue(*I);
9777     ImplicitValueInitExpr VIE(I->getType());
9778     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9779   }
9780 
9781   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9782     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9783     return false;
9784   }
9785 
9786   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9787 }
9788 
9789 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9790   switch (E->getCastKind()) {
9791   default:
9792     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9793 
9794   case CK_ConstructorConversion:
9795     return Visit(E->getSubExpr());
9796 
9797   case CK_DerivedToBase:
9798   case CK_UncheckedDerivedToBase: {
9799     APValue DerivedObject;
9800     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9801       return false;
9802     if (!DerivedObject.isStruct())
9803       return Error(E->getSubExpr());
9804 
9805     // Derived-to-base rvalue conversion: just slice off the derived part.
9806     APValue *Value = &DerivedObject;
9807     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9808     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9809          PathE = E->path_end(); PathI != PathE; ++PathI) {
9810       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9811       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9812       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9813       RD = Base;
9814     }
9815     Result = *Value;
9816     return true;
9817   }
9818   }
9819 }
9820 
9821 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9822   if (E->isTransparent())
9823     return Visit(E->getInit(0));
9824 
9825   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9826   if (RD->isInvalidDecl()) return false;
9827   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9828   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9829 
9830   EvalInfo::EvaluatingConstructorRAII EvalObj(
9831       Info,
9832       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9833       CXXRD && CXXRD->getNumBases());
9834 
9835   if (RD->isUnion()) {
9836     const FieldDecl *Field = E->getInitializedFieldInUnion();
9837     Result = APValue(Field);
9838     if (!Field)
9839       return true;
9840 
9841     // If the initializer list for a union does not contain any elements, the
9842     // first element of the union is value-initialized.
9843     // FIXME: The element should be initialized from an initializer list.
9844     //        Is this difference ever observable for initializer lists which
9845     //        we don't build?
9846     ImplicitValueInitExpr VIE(Field->getType());
9847     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9848 
9849     LValue Subobject = This;
9850     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9851       return false;
9852 
9853     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9854     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9855                                   isa<CXXDefaultInitExpr>(InitExpr));
9856 
9857     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
9858       if (Field->isBitField())
9859         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
9860                                      Field);
9861       return true;
9862     }
9863 
9864     return false;
9865   }
9866 
9867   if (!Result.hasValue())
9868     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9869                      std::distance(RD->field_begin(), RD->field_end()));
9870   unsigned ElementNo = 0;
9871   bool Success = true;
9872 
9873   // Initialize base classes.
9874   if (CXXRD && CXXRD->getNumBases()) {
9875     for (const auto &Base : CXXRD->bases()) {
9876       assert(ElementNo < E->getNumInits() && "missing init for base class");
9877       const Expr *Init = E->getInit(ElementNo);
9878 
9879       LValue Subobject = This;
9880       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9881         return false;
9882 
9883       APValue &FieldVal = Result.getStructBase(ElementNo);
9884       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9885         if (!Info.noteFailure())
9886           return false;
9887         Success = false;
9888       }
9889       ++ElementNo;
9890     }
9891 
9892     EvalObj.finishedConstructingBases();
9893   }
9894 
9895   // Initialize members.
9896   for (const auto *Field : RD->fields()) {
9897     // Anonymous bit-fields are not considered members of the class for
9898     // purposes of aggregate initialization.
9899     if (Field->isUnnamedBitfield())
9900       continue;
9901 
9902     LValue Subobject = This;
9903 
9904     bool HaveInit = ElementNo < E->getNumInits();
9905 
9906     // FIXME: Diagnostics here should point to the end of the initializer
9907     // list, not the start.
9908     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9909                             Subobject, Field, &Layout))
9910       return false;
9911 
9912     // Perform an implicit value-initialization for members beyond the end of
9913     // the initializer list.
9914     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9915     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9916 
9917     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9918     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9919                                   isa<CXXDefaultInitExpr>(Init));
9920 
9921     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9922     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9923         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9924                                                        FieldVal, Field))) {
9925       if (!Info.noteFailure())
9926         return false;
9927       Success = false;
9928     }
9929   }
9930 
9931   EvalObj.finishedConstructingFields();
9932 
9933   return Success;
9934 }
9935 
9936 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9937                                                 QualType T) {
9938   // Note that E's type is not necessarily the type of our class here; we might
9939   // be initializing an array element instead.
9940   const CXXConstructorDecl *FD = E->getConstructor();
9941   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9942 
9943   bool ZeroInit = E->requiresZeroInitialization();
9944   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9945     // If we've already performed zero-initialization, we're already done.
9946     if (Result.hasValue())
9947       return true;
9948 
9949     if (ZeroInit)
9950       return ZeroInitialization(E, T);
9951 
9952     return getDefaultInitValue(T, Result);
9953   }
9954 
9955   const FunctionDecl *Definition = nullptr;
9956   auto Body = FD->getBody(Definition);
9957 
9958   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9959     return false;
9960 
9961   // Avoid materializing a temporary for an elidable copy/move constructor.
9962   if (E->isElidable() && !ZeroInit) {
9963     // FIXME: This only handles the simplest case, where the source object
9964     //        is passed directly as the first argument to the constructor.
9965     //        This should also handle stepping though implicit casts and
9966     //        and conversion sequences which involve two steps, with a
9967     //        conversion operator followed by a converting constructor.
9968     const Expr *SrcObj = E->getArg(0);
9969     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
9970     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
9971     if (const MaterializeTemporaryExpr *ME =
9972             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
9973       return Visit(ME->getSubExpr());
9974   }
9975 
9976   if (ZeroInit && !ZeroInitialization(E, T))
9977     return false;
9978 
9979   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9980   return HandleConstructorCall(E, This, Args,
9981                                cast<CXXConstructorDecl>(Definition), Info,
9982                                Result);
9983 }
9984 
9985 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9986     const CXXInheritedCtorInitExpr *E) {
9987   if (!Info.CurrentCall) {
9988     assert(Info.checkingPotentialConstantExpression());
9989     return false;
9990   }
9991 
9992   const CXXConstructorDecl *FD = E->getConstructor();
9993   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9994     return false;
9995 
9996   const FunctionDecl *Definition = nullptr;
9997   auto Body = FD->getBody(Definition);
9998 
9999   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10000     return false;
10001 
10002   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10003                                cast<CXXConstructorDecl>(Definition), Info,
10004                                Result);
10005 }
10006 
10007 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10008     const CXXStdInitializerListExpr *E) {
10009   const ConstantArrayType *ArrayType =
10010       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10011 
10012   LValue Array;
10013   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10014     return false;
10015 
10016   // Get a pointer to the first element of the array.
10017   Array.addArray(Info, E, ArrayType);
10018 
10019   auto InvalidType = [&] {
10020     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10021       << E->getType();
10022     return false;
10023   };
10024 
10025   // FIXME: Perform the checks on the field types in SemaInit.
10026   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10027   RecordDecl::field_iterator Field = Record->field_begin();
10028   if (Field == Record->field_end())
10029     return InvalidType();
10030 
10031   // Start pointer.
10032   if (!Field->getType()->isPointerType() ||
10033       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10034                             ArrayType->getElementType()))
10035     return InvalidType();
10036 
10037   // FIXME: What if the initializer_list type has base classes, etc?
10038   Result = APValue(APValue::UninitStruct(), 0, 2);
10039   Array.moveInto(Result.getStructField(0));
10040 
10041   if (++Field == Record->field_end())
10042     return InvalidType();
10043 
10044   if (Field->getType()->isPointerType() &&
10045       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10046                            ArrayType->getElementType())) {
10047     // End pointer.
10048     if (!HandleLValueArrayAdjustment(Info, E, Array,
10049                                      ArrayType->getElementType(),
10050                                      ArrayType->getSize().getZExtValue()))
10051       return false;
10052     Array.moveInto(Result.getStructField(1));
10053   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10054     // Length.
10055     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10056   else
10057     return InvalidType();
10058 
10059   if (++Field != Record->field_end())
10060     return InvalidType();
10061 
10062   return true;
10063 }
10064 
10065 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10066   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10067   if (ClosureClass->isInvalidDecl())
10068     return false;
10069 
10070   const size_t NumFields =
10071       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10072 
10073   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10074                                             E->capture_init_end()) &&
10075          "The number of lambda capture initializers should equal the number of "
10076          "fields within the closure type");
10077 
10078   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10079   // Iterate through all the lambda's closure object's fields and initialize
10080   // them.
10081   auto *CaptureInitIt = E->capture_init_begin();
10082   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
10083   bool Success = true;
10084   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10085   for (const auto *Field : ClosureClass->fields()) {
10086     assert(CaptureInitIt != E->capture_init_end());
10087     // Get the initializer for this field
10088     Expr *const CurFieldInit = *CaptureInitIt++;
10089 
10090     // If there is no initializer, either this is a VLA or an error has
10091     // occurred.
10092     if (!CurFieldInit)
10093       return Error(E);
10094 
10095     LValue Subobject = This;
10096 
10097     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10098       return false;
10099 
10100     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10101     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10102       if (!Info.keepEvaluatingAfterFailure())
10103         return false;
10104       Success = false;
10105     }
10106     ++CaptureIt;
10107   }
10108   return Success;
10109 }
10110 
10111 static bool EvaluateRecord(const Expr *E, const LValue &This,
10112                            APValue &Result, EvalInfo &Info) {
10113   assert(!E->isValueDependent());
10114   assert(E->isPRValue() && E->getType()->isRecordType() &&
10115          "can't evaluate expression as a record rvalue");
10116   return RecordExprEvaluator(Info, This, Result).Visit(E);
10117 }
10118 
10119 //===----------------------------------------------------------------------===//
10120 // Temporary Evaluation
10121 //
10122 // Temporaries are represented in the AST as rvalues, but generally behave like
10123 // lvalues. The full-object of which the temporary is a subobject is implicitly
10124 // materialized so that a reference can bind to it.
10125 //===----------------------------------------------------------------------===//
10126 namespace {
10127 class TemporaryExprEvaluator
10128   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10129 public:
10130   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10131     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10132 
10133   /// Visit an expression which constructs the value of this temporary.
10134   bool VisitConstructExpr(const Expr *E) {
10135     APValue &Value = Info.CurrentCall->createTemporary(
10136         E, E->getType(), ScopeKind::FullExpression, Result);
10137     return EvaluateInPlace(Value, Info, Result, E);
10138   }
10139 
10140   bool VisitCastExpr(const CastExpr *E) {
10141     switch (E->getCastKind()) {
10142     default:
10143       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10144 
10145     case CK_ConstructorConversion:
10146       return VisitConstructExpr(E->getSubExpr());
10147     }
10148   }
10149   bool VisitInitListExpr(const InitListExpr *E) {
10150     return VisitConstructExpr(E);
10151   }
10152   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10153     return VisitConstructExpr(E);
10154   }
10155   bool VisitCallExpr(const CallExpr *E) {
10156     return VisitConstructExpr(E);
10157   }
10158   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10159     return VisitConstructExpr(E);
10160   }
10161   bool VisitLambdaExpr(const LambdaExpr *E) {
10162     return VisitConstructExpr(E);
10163   }
10164 };
10165 } // end anonymous namespace
10166 
10167 /// Evaluate an expression of record type as a temporary.
10168 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10169   assert(!E->isValueDependent());
10170   assert(E->isPRValue() && E->getType()->isRecordType());
10171   return TemporaryExprEvaluator(Info, Result).Visit(E);
10172 }
10173 
10174 //===----------------------------------------------------------------------===//
10175 // Vector Evaluation
10176 //===----------------------------------------------------------------------===//
10177 
10178 namespace {
10179   class VectorExprEvaluator
10180   : public ExprEvaluatorBase<VectorExprEvaluator> {
10181     APValue &Result;
10182   public:
10183 
10184     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10185       : ExprEvaluatorBaseTy(info), Result(Result) {}
10186 
10187     bool Success(ArrayRef<APValue> V, const Expr *E) {
10188       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10189       // FIXME: remove this APValue copy.
10190       Result = APValue(V.data(), V.size());
10191       return true;
10192     }
10193     bool Success(const APValue &V, const Expr *E) {
10194       assert(V.isVector());
10195       Result = V;
10196       return true;
10197     }
10198     bool ZeroInitialization(const Expr *E);
10199 
10200     bool VisitUnaryReal(const UnaryOperator *E)
10201       { return Visit(E->getSubExpr()); }
10202     bool VisitCastExpr(const CastExpr* E);
10203     bool VisitInitListExpr(const InitListExpr *E);
10204     bool VisitUnaryImag(const UnaryOperator *E);
10205     bool VisitBinaryOperator(const BinaryOperator *E);
10206     bool VisitUnaryOperator(const UnaryOperator *E);
10207     // FIXME: Missing: conditional operator (for GNU
10208     //                 conditional select), shufflevector, ExtVectorElementExpr
10209   };
10210 } // end anonymous namespace
10211 
10212 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10213   assert(E->isPRValue() && E->getType()->isVectorType() &&
10214          "not a vector prvalue");
10215   return VectorExprEvaluator(Info, Result).Visit(E);
10216 }
10217 
10218 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10219   const VectorType *VTy = E->getType()->castAs<VectorType>();
10220   unsigned NElts = VTy->getNumElements();
10221 
10222   const Expr *SE = E->getSubExpr();
10223   QualType SETy = SE->getType();
10224 
10225   switch (E->getCastKind()) {
10226   case CK_VectorSplat: {
10227     APValue Val = APValue();
10228     if (SETy->isIntegerType()) {
10229       APSInt IntResult;
10230       if (!EvaluateInteger(SE, IntResult, Info))
10231         return false;
10232       Val = APValue(std::move(IntResult));
10233     } else if (SETy->isRealFloatingType()) {
10234       APFloat FloatResult(0.0);
10235       if (!EvaluateFloat(SE, FloatResult, Info))
10236         return false;
10237       Val = APValue(std::move(FloatResult));
10238     } else {
10239       return Error(E);
10240     }
10241 
10242     // Splat and create vector APValue.
10243     SmallVector<APValue, 4> Elts(NElts, Val);
10244     return Success(Elts, E);
10245   }
10246   case CK_BitCast: {
10247     // Evaluate the operand into an APInt we can extract from.
10248     llvm::APInt SValInt;
10249     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10250       return false;
10251     // Extract the elements
10252     QualType EltTy = VTy->getElementType();
10253     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10254     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10255     SmallVector<APValue, 4> Elts;
10256     if (EltTy->isRealFloatingType()) {
10257       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10258       unsigned FloatEltSize = EltSize;
10259       if (&Sem == &APFloat::x87DoubleExtended())
10260         FloatEltSize = 80;
10261       for (unsigned i = 0; i < NElts; i++) {
10262         llvm::APInt Elt;
10263         if (BigEndian)
10264           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
10265         else
10266           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
10267         Elts.push_back(APValue(APFloat(Sem, Elt)));
10268       }
10269     } else if (EltTy->isIntegerType()) {
10270       for (unsigned i = 0; i < NElts; i++) {
10271         llvm::APInt Elt;
10272         if (BigEndian)
10273           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10274         else
10275           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10276         Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10277       }
10278     } else {
10279       return Error(E);
10280     }
10281     return Success(Elts, E);
10282   }
10283   default:
10284     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10285   }
10286 }
10287 
10288 bool
10289 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10290   const VectorType *VT = E->getType()->castAs<VectorType>();
10291   unsigned NumInits = E->getNumInits();
10292   unsigned NumElements = VT->getNumElements();
10293 
10294   QualType EltTy = VT->getElementType();
10295   SmallVector<APValue, 4> Elements;
10296 
10297   // The number of initializers can be less than the number of
10298   // vector elements. For OpenCL, this can be due to nested vector
10299   // initialization. For GCC compatibility, missing trailing elements
10300   // should be initialized with zeroes.
10301   unsigned CountInits = 0, CountElts = 0;
10302   while (CountElts < NumElements) {
10303     // Handle nested vector initialization.
10304     if (CountInits < NumInits
10305         && E->getInit(CountInits)->getType()->isVectorType()) {
10306       APValue v;
10307       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10308         return Error(E);
10309       unsigned vlen = v.getVectorLength();
10310       for (unsigned j = 0; j < vlen; j++)
10311         Elements.push_back(v.getVectorElt(j));
10312       CountElts += vlen;
10313     } else if (EltTy->isIntegerType()) {
10314       llvm::APSInt sInt(32);
10315       if (CountInits < NumInits) {
10316         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10317           return false;
10318       } else // trailing integer zero.
10319         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10320       Elements.push_back(APValue(sInt));
10321       CountElts++;
10322     } else {
10323       llvm::APFloat f(0.0);
10324       if (CountInits < NumInits) {
10325         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10326           return false;
10327       } else // trailing float zero.
10328         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10329       Elements.push_back(APValue(f));
10330       CountElts++;
10331     }
10332     CountInits++;
10333   }
10334   return Success(Elements, E);
10335 }
10336 
10337 bool
10338 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10339   const auto *VT = E->getType()->castAs<VectorType>();
10340   QualType EltTy = VT->getElementType();
10341   APValue ZeroElement;
10342   if (EltTy->isIntegerType())
10343     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10344   else
10345     ZeroElement =
10346         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10347 
10348   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10349   return Success(Elements, E);
10350 }
10351 
10352 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10353   VisitIgnoredValue(E->getSubExpr());
10354   return ZeroInitialization(E);
10355 }
10356 
10357 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10358   BinaryOperatorKind Op = E->getOpcode();
10359   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10360          "Operation not supported on vector types");
10361 
10362   if (Op == BO_Comma)
10363     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10364 
10365   Expr *LHS = E->getLHS();
10366   Expr *RHS = E->getRHS();
10367 
10368   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10369          "Must both be vector types");
10370   // Checking JUST the types are the same would be fine, except shifts don't
10371   // need to have their types be the same (since you always shift by an int).
10372   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10373              E->getType()->castAs<VectorType>()->getNumElements() &&
10374          RHS->getType()->castAs<VectorType>()->getNumElements() ==
10375              E->getType()->castAs<VectorType>()->getNumElements() &&
10376          "All operands must be the same size.");
10377 
10378   APValue LHSValue;
10379   APValue RHSValue;
10380   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10381   if (!LHSOK && !Info.noteFailure())
10382     return false;
10383   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10384     return false;
10385 
10386   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10387     return false;
10388 
10389   return Success(LHSValue, E);
10390 }
10391 
10392 static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10393                                                          QualType ResultTy,
10394                                                          UnaryOperatorKind Op,
10395                                                          APValue Elt) {
10396   switch (Op) {
10397   case UO_Plus:
10398     // Nothing to do here.
10399     return Elt;
10400   case UO_Minus:
10401     if (Elt.getKind() == APValue::Int) {
10402       Elt.getInt().negate();
10403     } else {
10404       assert(Elt.getKind() == APValue::Float &&
10405              "Vector can only be int or float type");
10406       Elt.getFloat().changeSign();
10407     }
10408     return Elt;
10409   case UO_Not:
10410     // This is only valid for integral types anyway, so we don't have to handle
10411     // float here.
10412     assert(Elt.getKind() == APValue::Int &&
10413            "Vector operator ~ can only be int");
10414     Elt.getInt().flipAllBits();
10415     return Elt;
10416   case UO_LNot: {
10417     if (Elt.getKind() == APValue::Int) {
10418       Elt.getInt() = !Elt.getInt();
10419       // operator ! on vectors returns -1 for 'truth', so negate it.
10420       Elt.getInt().negate();
10421       return Elt;
10422     }
10423     assert(Elt.getKind() == APValue::Float &&
10424            "Vector can only be int or float type");
10425     // Float types result in an int of the same size, but -1 for true, or 0 for
10426     // false.
10427     APSInt EltResult{Ctx.getIntWidth(ResultTy),
10428                      ResultTy->isUnsignedIntegerType()};
10429     if (Elt.getFloat().isZero())
10430       EltResult.setAllBits();
10431     else
10432       EltResult.clearAllBits();
10433 
10434     return APValue{EltResult};
10435   }
10436   default:
10437     // FIXME: Implement the rest of the unary operators.
10438     return llvm::None;
10439   }
10440 }
10441 
10442 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10443   Expr *SubExpr = E->getSubExpr();
10444   const auto *VD = SubExpr->getType()->castAs<VectorType>();
10445   // This result element type differs in the case of negating a floating point
10446   // vector, since the result type is the a vector of the equivilant sized
10447   // integer.
10448   const QualType ResultEltTy = VD->getElementType();
10449   UnaryOperatorKind Op = E->getOpcode();
10450 
10451   APValue SubExprValue;
10452   if (!Evaluate(SubExprValue, Info, SubExpr))
10453     return false;
10454 
10455   // FIXME: This vector evaluator someday needs to be changed to be LValue
10456   // aware/keep LValue information around, rather than dealing with just vector
10457   // types directly. Until then, we cannot handle cases where the operand to
10458   // these unary operators is an LValue. The only case I've been able to see
10459   // cause this is operator++ assigning to a member expression (only valid in
10460   // altivec compilations) in C mode, so this shouldn't limit us too much.
10461   if (SubExprValue.isLValue())
10462     return false;
10463 
10464   assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10465          "Vector length doesn't match type?");
10466 
10467   SmallVector<APValue, 4> ResultElements;
10468   for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10469     llvm::Optional<APValue> Elt = handleVectorUnaryOperator(
10470         Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10471     if (!Elt)
10472       return false;
10473     ResultElements.push_back(*Elt);
10474   }
10475   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10476 }
10477 
10478 //===----------------------------------------------------------------------===//
10479 // Array Evaluation
10480 //===----------------------------------------------------------------------===//
10481 
10482 namespace {
10483   class ArrayExprEvaluator
10484   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10485     const LValue &This;
10486     APValue &Result;
10487   public:
10488 
10489     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10490       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10491 
10492     bool Success(const APValue &V, const Expr *E) {
10493       assert(V.isArray() && "expected array");
10494       Result = V;
10495       return true;
10496     }
10497 
10498     bool ZeroInitialization(const Expr *E) {
10499       const ConstantArrayType *CAT =
10500           Info.Ctx.getAsConstantArrayType(E->getType());
10501       if (!CAT) {
10502         if (E->getType()->isIncompleteArrayType()) {
10503           // We can be asked to zero-initialize a flexible array member; this
10504           // is represented as an ImplicitValueInitExpr of incomplete array
10505           // type. In this case, the array has zero elements.
10506           Result = APValue(APValue::UninitArray(), 0, 0);
10507           return true;
10508         }
10509         // FIXME: We could handle VLAs here.
10510         return Error(E);
10511       }
10512 
10513       Result = APValue(APValue::UninitArray(), 0,
10514                        CAT->getSize().getZExtValue());
10515       if (!Result.hasArrayFiller())
10516         return true;
10517 
10518       // Zero-initialize all elements.
10519       LValue Subobject = This;
10520       Subobject.addArray(Info, E, CAT);
10521       ImplicitValueInitExpr VIE(CAT->getElementType());
10522       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10523     }
10524 
10525     bool VisitCallExpr(const CallExpr *E) {
10526       return handleCallExpr(E, Result, &This);
10527     }
10528     bool VisitInitListExpr(const InitListExpr *E,
10529                            QualType AllocType = QualType());
10530     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10531     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10532     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10533                                const LValue &Subobject,
10534                                APValue *Value, QualType Type);
10535     bool VisitStringLiteral(const StringLiteral *E,
10536                             QualType AllocType = QualType()) {
10537       expandStringLiteral(Info, E, Result, AllocType);
10538       return true;
10539     }
10540   };
10541 } // end anonymous namespace
10542 
10543 static bool EvaluateArray(const Expr *E, const LValue &This,
10544                           APValue &Result, EvalInfo &Info) {
10545   assert(!E->isValueDependent());
10546   assert(E->isPRValue() && E->getType()->isArrayType() &&
10547          "not an array prvalue");
10548   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10549 }
10550 
10551 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10552                                      APValue &Result, const InitListExpr *ILE,
10553                                      QualType AllocType) {
10554   assert(!ILE->isValueDependent());
10555   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10556          "not an array prvalue");
10557   return ArrayExprEvaluator(Info, This, Result)
10558       .VisitInitListExpr(ILE, AllocType);
10559 }
10560 
10561 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10562                                           APValue &Result,
10563                                           const CXXConstructExpr *CCE,
10564                                           QualType AllocType) {
10565   assert(!CCE->isValueDependent());
10566   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10567          "not an array prvalue");
10568   return ArrayExprEvaluator(Info, This, Result)
10569       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10570 }
10571 
10572 // Return true iff the given array filler may depend on the element index.
10573 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10574   // For now, just allow non-class value-initialization and initialization
10575   // lists comprised of them.
10576   if (isa<ImplicitValueInitExpr>(FillerExpr))
10577     return false;
10578   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10579     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10580       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10581         return true;
10582     }
10583     return false;
10584   }
10585   return true;
10586 }
10587 
10588 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10589                                            QualType AllocType) {
10590   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10591       AllocType.isNull() ? E->getType() : AllocType);
10592   if (!CAT)
10593     return Error(E);
10594 
10595   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10596   // an appropriately-typed string literal enclosed in braces.
10597   if (E->isStringLiteralInit()) {
10598     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10599     // FIXME: Support ObjCEncodeExpr here once we support it in
10600     // ArrayExprEvaluator generally.
10601     if (!SL)
10602       return Error(E);
10603     return VisitStringLiteral(SL, AllocType);
10604   }
10605   // Any other transparent list init will need proper handling of the
10606   // AllocType; we can't just recurse to the inner initializer.
10607   assert(!E->isTransparent() &&
10608          "transparent array list initialization is not string literal init?");
10609 
10610   bool Success = true;
10611 
10612   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10613          "zero-initialized array shouldn't have any initialized elts");
10614   APValue Filler;
10615   if (Result.isArray() && Result.hasArrayFiller())
10616     Filler = Result.getArrayFiller();
10617 
10618   unsigned NumEltsToInit = E->getNumInits();
10619   unsigned NumElts = CAT->getSize().getZExtValue();
10620   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10621 
10622   // If the initializer might depend on the array index, run it for each
10623   // array element.
10624   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10625     NumEltsToInit = NumElts;
10626 
10627   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10628                           << NumEltsToInit << ".\n");
10629 
10630   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10631 
10632   // If the array was previously zero-initialized, preserve the
10633   // zero-initialized values.
10634   if (Filler.hasValue()) {
10635     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10636       Result.getArrayInitializedElt(I) = Filler;
10637     if (Result.hasArrayFiller())
10638       Result.getArrayFiller() = Filler;
10639   }
10640 
10641   LValue Subobject = This;
10642   Subobject.addArray(Info, E, CAT);
10643   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10644     const Expr *Init =
10645         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10646     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10647                          Info, Subobject, Init) ||
10648         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10649                                      CAT->getElementType(), 1)) {
10650       if (!Info.noteFailure())
10651         return false;
10652       Success = false;
10653     }
10654   }
10655 
10656   if (!Result.hasArrayFiller())
10657     return Success;
10658 
10659   // If we get here, we have a trivial filler, which we can just evaluate
10660   // once and splat over the rest of the array elements.
10661   assert(FillerExpr && "no array filler for incomplete init list");
10662   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10663                          FillerExpr) && Success;
10664 }
10665 
10666 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10667   LValue CommonLV;
10668   if (E->getCommonExpr() &&
10669       !Evaluate(Info.CurrentCall->createTemporary(
10670                     E->getCommonExpr(),
10671                     getStorageType(Info.Ctx, E->getCommonExpr()),
10672                     ScopeKind::FullExpression, CommonLV),
10673                 Info, E->getCommonExpr()->getSourceExpr()))
10674     return false;
10675 
10676   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10677 
10678   uint64_t Elements = CAT->getSize().getZExtValue();
10679   Result = APValue(APValue::UninitArray(), Elements, Elements);
10680 
10681   LValue Subobject = This;
10682   Subobject.addArray(Info, E, CAT);
10683 
10684   bool Success = true;
10685   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10686     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10687                          Info, Subobject, E->getSubExpr()) ||
10688         !HandleLValueArrayAdjustment(Info, E, Subobject,
10689                                      CAT->getElementType(), 1)) {
10690       if (!Info.noteFailure())
10691         return false;
10692       Success = false;
10693     }
10694   }
10695 
10696   return Success;
10697 }
10698 
10699 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10700   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10701 }
10702 
10703 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10704                                                const LValue &Subobject,
10705                                                APValue *Value,
10706                                                QualType Type) {
10707   bool HadZeroInit = Value->hasValue();
10708 
10709   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10710     unsigned FinalSize = CAT->getSize().getZExtValue();
10711 
10712     // Preserve the array filler if we had prior zero-initialization.
10713     APValue Filler =
10714       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10715                                              : APValue();
10716 
10717     *Value = APValue(APValue::UninitArray(), 0, FinalSize);
10718     if (FinalSize == 0)
10719       return true;
10720 
10721     LValue ArrayElt = Subobject;
10722     ArrayElt.addArray(Info, E, CAT);
10723     // We do the whole initialization in two passes, first for just one element,
10724     // then for the whole array. It's possible we may find out we can't do const
10725     // init in the first pass, in which case we avoid allocating a potentially
10726     // large array. We don't do more passes because expanding array requires
10727     // copying the data, which is wasteful.
10728     for (const unsigned N : {1u, FinalSize}) {
10729       unsigned OldElts = Value->getArrayInitializedElts();
10730       if (OldElts == N)
10731         break;
10732 
10733       // Expand the array to appropriate size.
10734       APValue NewValue(APValue::UninitArray(), N, FinalSize);
10735       for (unsigned I = 0; I < OldElts; ++I)
10736         NewValue.getArrayInitializedElt(I).swap(
10737             Value->getArrayInitializedElt(I));
10738       Value->swap(NewValue);
10739 
10740       if (HadZeroInit)
10741         for (unsigned I = OldElts; I < N; ++I)
10742           Value->getArrayInitializedElt(I) = Filler;
10743 
10744       // Initialize the elements.
10745       for (unsigned I = OldElts; I < N; ++I) {
10746         if (!VisitCXXConstructExpr(E, ArrayElt,
10747                                    &Value->getArrayInitializedElt(I),
10748                                    CAT->getElementType()) ||
10749             !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10750                                          CAT->getElementType(), 1))
10751           return false;
10752         // When checking for const initilization any diagnostic is considered
10753         // an error.
10754         if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
10755             !Info.keepEvaluatingAfterFailure())
10756           return false;
10757       }
10758     }
10759 
10760     return true;
10761   }
10762 
10763   if (!Type->isRecordType())
10764     return Error(E);
10765 
10766   return RecordExprEvaluator(Info, Subobject, *Value)
10767              .VisitCXXConstructExpr(E, Type);
10768 }
10769 
10770 //===----------------------------------------------------------------------===//
10771 // Integer Evaluation
10772 //
10773 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10774 // types and back in constant folding. Integer values are thus represented
10775 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10776 //===----------------------------------------------------------------------===//
10777 
10778 namespace {
10779 class IntExprEvaluator
10780         : public ExprEvaluatorBase<IntExprEvaluator> {
10781   APValue &Result;
10782 public:
10783   IntExprEvaluator(EvalInfo &info, APValue &result)
10784       : ExprEvaluatorBaseTy(info), Result(result) {}
10785 
10786   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10787     assert(E->getType()->isIntegralOrEnumerationType() &&
10788            "Invalid evaluation result.");
10789     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10790            "Invalid evaluation result.");
10791     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10792            "Invalid evaluation result.");
10793     Result = APValue(SI);
10794     return true;
10795   }
10796   bool Success(const llvm::APSInt &SI, const Expr *E) {
10797     return Success(SI, E, Result);
10798   }
10799 
10800   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10801     assert(E->getType()->isIntegralOrEnumerationType() &&
10802            "Invalid evaluation result.");
10803     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10804            "Invalid evaluation result.");
10805     Result = APValue(APSInt(I));
10806     Result.getInt().setIsUnsigned(
10807                             E->getType()->isUnsignedIntegerOrEnumerationType());
10808     return true;
10809   }
10810   bool Success(const llvm::APInt &I, const Expr *E) {
10811     return Success(I, E, Result);
10812   }
10813 
10814   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10815     assert(E->getType()->isIntegralOrEnumerationType() &&
10816            "Invalid evaluation result.");
10817     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10818     return true;
10819   }
10820   bool Success(uint64_t Value, const Expr *E) {
10821     return Success(Value, E, Result);
10822   }
10823 
10824   bool Success(CharUnits Size, const Expr *E) {
10825     return Success(Size.getQuantity(), E);
10826   }
10827 
10828   bool Success(const APValue &V, const Expr *E) {
10829     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10830       Result = V;
10831       return true;
10832     }
10833     return Success(V.getInt(), E);
10834   }
10835 
10836   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10837 
10838   //===--------------------------------------------------------------------===//
10839   //                            Visitor Methods
10840   //===--------------------------------------------------------------------===//
10841 
10842   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10843     return Success(E->getValue(), E);
10844   }
10845   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10846     return Success(E->getValue(), E);
10847   }
10848 
10849   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10850   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10851     if (CheckReferencedDecl(E, E->getDecl()))
10852       return true;
10853 
10854     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10855   }
10856   bool VisitMemberExpr(const MemberExpr *E) {
10857     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10858       VisitIgnoredBaseExpression(E->getBase());
10859       return true;
10860     }
10861 
10862     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10863   }
10864 
10865   bool VisitCallExpr(const CallExpr *E);
10866   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10867   bool VisitBinaryOperator(const BinaryOperator *E);
10868   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10869   bool VisitUnaryOperator(const UnaryOperator *E);
10870 
10871   bool VisitCastExpr(const CastExpr* E);
10872   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10873 
10874   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10875     return Success(E->getValue(), E);
10876   }
10877 
10878   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10879     return Success(E->getValue(), E);
10880   }
10881 
10882   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10883     if (Info.ArrayInitIndex == uint64_t(-1)) {
10884       // We were asked to evaluate this subexpression independent of the
10885       // enclosing ArrayInitLoopExpr. We can't do that.
10886       Info.FFDiag(E);
10887       return false;
10888     }
10889     return Success(Info.ArrayInitIndex, E);
10890   }
10891 
10892   // Note, GNU defines __null as an integer, not a pointer.
10893   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10894     return ZeroInitialization(E);
10895   }
10896 
10897   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10898     return Success(E->getValue(), E);
10899   }
10900 
10901   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10902     return Success(E->getValue(), E);
10903   }
10904 
10905   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10906     return Success(E->getValue(), E);
10907   }
10908 
10909   bool VisitUnaryReal(const UnaryOperator *E);
10910   bool VisitUnaryImag(const UnaryOperator *E);
10911 
10912   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10913   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10914   bool VisitSourceLocExpr(const SourceLocExpr *E);
10915   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10916   bool VisitRequiresExpr(const RequiresExpr *E);
10917   // FIXME: Missing: array subscript of vector, member of vector
10918 };
10919 
10920 class FixedPointExprEvaluator
10921     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10922   APValue &Result;
10923 
10924  public:
10925   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10926       : ExprEvaluatorBaseTy(info), Result(result) {}
10927 
10928   bool Success(const llvm::APInt &I, const Expr *E) {
10929     return Success(
10930         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10931   }
10932 
10933   bool Success(uint64_t Value, const Expr *E) {
10934     return Success(
10935         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10936   }
10937 
10938   bool Success(const APValue &V, const Expr *E) {
10939     return Success(V.getFixedPoint(), E);
10940   }
10941 
10942   bool Success(const APFixedPoint &V, const Expr *E) {
10943     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10944     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10945            "Invalid evaluation result.");
10946     Result = APValue(V);
10947     return true;
10948   }
10949 
10950   //===--------------------------------------------------------------------===//
10951   //                            Visitor Methods
10952   //===--------------------------------------------------------------------===//
10953 
10954   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10955     return Success(E->getValue(), E);
10956   }
10957 
10958   bool VisitCastExpr(const CastExpr *E);
10959   bool VisitUnaryOperator(const UnaryOperator *E);
10960   bool VisitBinaryOperator(const BinaryOperator *E);
10961 };
10962 } // end anonymous namespace
10963 
10964 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10965 /// produce either the integer value or a pointer.
10966 ///
10967 /// GCC has a heinous extension which folds casts between pointer types and
10968 /// pointer-sized integral types. We support this by allowing the evaluation of
10969 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10970 /// Some simple arithmetic on such values is supported (they are treated much
10971 /// like char*).
10972 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10973                                     EvalInfo &Info) {
10974   assert(!E->isValueDependent());
10975   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
10976   return IntExprEvaluator(Info, Result).Visit(E);
10977 }
10978 
10979 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10980   assert(!E->isValueDependent());
10981   APValue Val;
10982   if (!EvaluateIntegerOrLValue(E, Val, Info))
10983     return false;
10984   if (!Val.isInt()) {
10985     // FIXME: It would be better to produce the diagnostic for casting
10986     //        a pointer to an integer.
10987     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10988     return false;
10989   }
10990   Result = Val.getInt();
10991   return true;
10992 }
10993 
10994 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10995   APValue Evaluated = E->EvaluateInContext(
10996       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10997   return Success(Evaluated, E);
10998 }
10999 
11000 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11001                                EvalInfo &Info) {
11002   assert(!E->isValueDependent());
11003   if (E->getType()->isFixedPointType()) {
11004     APValue Val;
11005     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11006       return false;
11007     if (!Val.isFixedPoint())
11008       return false;
11009 
11010     Result = Val.getFixedPoint();
11011     return true;
11012   }
11013   return false;
11014 }
11015 
11016 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11017                                         EvalInfo &Info) {
11018   assert(!E->isValueDependent());
11019   if (E->getType()->isIntegerType()) {
11020     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11021     APSInt Val;
11022     if (!EvaluateInteger(E, Val, Info))
11023       return false;
11024     Result = APFixedPoint(Val, FXSema);
11025     return true;
11026   } else if (E->getType()->isFixedPointType()) {
11027     return EvaluateFixedPoint(E, Result, Info);
11028   }
11029   return false;
11030 }
11031 
11032 /// Check whether the given declaration can be directly converted to an integral
11033 /// rvalue. If not, no diagnostic is produced; there are other things we can
11034 /// try.
11035 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11036   // Enums are integer constant exprs.
11037   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11038     // Check for signedness/width mismatches between E type and ECD value.
11039     bool SameSign = (ECD->getInitVal().isSigned()
11040                      == E->getType()->isSignedIntegerOrEnumerationType());
11041     bool SameWidth = (ECD->getInitVal().getBitWidth()
11042                       == Info.Ctx.getIntWidth(E->getType()));
11043     if (SameSign && SameWidth)
11044       return Success(ECD->getInitVal(), E);
11045     else {
11046       // Get rid of mismatch (otherwise Success assertions will fail)
11047       // by computing a new value matching the type of E.
11048       llvm::APSInt Val = ECD->getInitVal();
11049       if (!SameSign)
11050         Val.setIsSigned(!ECD->getInitVal().isSigned());
11051       if (!SameWidth)
11052         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11053       return Success(Val, E);
11054     }
11055   }
11056   return false;
11057 }
11058 
11059 /// Values returned by __builtin_classify_type, chosen to match the values
11060 /// produced by GCC's builtin.
11061 enum class GCCTypeClass {
11062   None = -1,
11063   Void = 0,
11064   Integer = 1,
11065   // GCC reserves 2 for character types, but instead classifies them as
11066   // integers.
11067   Enum = 3,
11068   Bool = 4,
11069   Pointer = 5,
11070   // GCC reserves 6 for references, but appears to never use it (because
11071   // expressions never have reference type, presumably).
11072   PointerToDataMember = 7,
11073   RealFloat = 8,
11074   Complex = 9,
11075   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
11076   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
11077   // GCC claims to reserve 11 for pointers to member functions, but *actually*
11078   // uses 12 for that purpose, same as for a class or struct. Maybe it
11079   // internally implements a pointer to member as a struct?  Who knows.
11080   PointerToMemberFunction = 12, // Not a bug, see above.
11081   ClassOrStruct = 12,
11082   Union = 13,
11083   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
11084   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
11085   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
11086   // literals.
11087 };
11088 
11089 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11090 /// as GCC.
11091 static GCCTypeClass
11092 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
11093   assert(!T->isDependentType() && "unexpected dependent type");
11094 
11095   QualType CanTy = T.getCanonicalType();
11096   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
11097 
11098   switch (CanTy->getTypeClass()) {
11099 #define TYPE(ID, BASE)
11100 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11101 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11102 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11103 #include "clang/AST/TypeNodes.inc"
11104   case Type::Auto:
11105   case Type::DeducedTemplateSpecialization:
11106       llvm_unreachable("unexpected non-canonical or dependent type");
11107 
11108   case Type::Builtin:
11109     switch (BT->getKind()) {
11110 #define BUILTIN_TYPE(ID, SINGLETON_ID)
11111 #define SIGNED_TYPE(ID, SINGLETON_ID) \
11112     case BuiltinType::ID: return GCCTypeClass::Integer;
11113 #define FLOATING_TYPE(ID, SINGLETON_ID) \
11114     case BuiltinType::ID: return GCCTypeClass::RealFloat;
11115 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11116     case BuiltinType::ID: break;
11117 #include "clang/AST/BuiltinTypes.def"
11118     case BuiltinType::Void:
11119       return GCCTypeClass::Void;
11120 
11121     case BuiltinType::Bool:
11122       return GCCTypeClass::Bool;
11123 
11124     case BuiltinType::Char_U:
11125     case BuiltinType::UChar:
11126     case BuiltinType::WChar_U:
11127     case BuiltinType::Char8:
11128     case BuiltinType::Char16:
11129     case BuiltinType::Char32:
11130     case BuiltinType::UShort:
11131     case BuiltinType::UInt:
11132     case BuiltinType::ULong:
11133     case BuiltinType::ULongLong:
11134     case BuiltinType::UInt128:
11135       return GCCTypeClass::Integer;
11136 
11137     case BuiltinType::UShortAccum:
11138     case BuiltinType::UAccum:
11139     case BuiltinType::ULongAccum:
11140     case BuiltinType::UShortFract:
11141     case BuiltinType::UFract:
11142     case BuiltinType::ULongFract:
11143     case BuiltinType::SatUShortAccum:
11144     case BuiltinType::SatUAccum:
11145     case BuiltinType::SatULongAccum:
11146     case BuiltinType::SatUShortFract:
11147     case BuiltinType::SatUFract:
11148     case BuiltinType::SatULongFract:
11149       return GCCTypeClass::None;
11150 
11151     case BuiltinType::NullPtr:
11152 
11153     case BuiltinType::ObjCId:
11154     case BuiltinType::ObjCClass:
11155     case BuiltinType::ObjCSel:
11156 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11157     case BuiltinType::Id:
11158 #include "clang/Basic/OpenCLImageTypes.def"
11159 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11160     case BuiltinType::Id:
11161 #include "clang/Basic/OpenCLExtensionTypes.def"
11162     case BuiltinType::OCLSampler:
11163     case BuiltinType::OCLEvent:
11164     case BuiltinType::OCLClkEvent:
11165     case BuiltinType::OCLQueue:
11166     case BuiltinType::OCLReserveID:
11167 #define SVE_TYPE(Name, Id, SingletonId) \
11168     case BuiltinType::Id:
11169 #include "clang/Basic/AArch64SVEACLETypes.def"
11170 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11171     case BuiltinType::Id:
11172 #include "clang/Basic/PPCTypes.def"
11173 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11174 #include "clang/Basic/RISCVVTypes.def"
11175       return GCCTypeClass::None;
11176 
11177     case BuiltinType::Dependent:
11178       llvm_unreachable("unexpected dependent type");
11179     };
11180     llvm_unreachable("unexpected placeholder type");
11181 
11182   case Type::Enum:
11183     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11184 
11185   case Type::Pointer:
11186   case Type::ConstantArray:
11187   case Type::VariableArray:
11188   case Type::IncompleteArray:
11189   case Type::FunctionNoProto:
11190   case Type::FunctionProto:
11191     return GCCTypeClass::Pointer;
11192 
11193   case Type::MemberPointer:
11194     return CanTy->isMemberDataPointerType()
11195                ? GCCTypeClass::PointerToDataMember
11196                : GCCTypeClass::PointerToMemberFunction;
11197 
11198   case Type::Complex:
11199     return GCCTypeClass::Complex;
11200 
11201   case Type::Record:
11202     return CanTy->isUnionType() ? GCCTypeClass::Union
11203                                 : GCCTypeClass::ClassOrStruct;
11204 
11205   case Type::Atomic:
11206     // GCC classifies _Atomic T the same as T.
11207     return EvaluateBuiltinClassifyType(
11208         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11209 
11210   case Type::BlockPointer:
11211   case Type::Vector:
11212   case Type::ExtVector:
11213   case Type::ConstantMatrix:
11214   case Type::ObjCObject:
11215   case Type::ObjCInterface:
11216   case Type::ObjCObjectPointer:
11217   case Type::Pipe:
11218   case Type::BitInt:
11219     // GCC classifies vectors as None. We follow its lead and classify all
11220     // other types that don't fit into the regular classification the same way.
11221     return GCCTypeClass::None;
11222 
11223   case Type::LValueReference:
11224   case Type::RValueReference:
11225     llvm_unreachable("invalid type for expression");
11226   }
11227 
11228   llvm_unreachable("unexpected type class");
11229 }
11230 
11231 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11232 /// as GCC.
11233 static GCCTypeClass
11234 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11235   // If no argument was supplied, default to None. This isn't
11236   // ideal, however it is what gcc does.
11237   if (E->getNumArgs() == 0)
11238     return GCCTypeClass::None;
11239 
11240   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11241   // being an ICE, but still folds it to a constant using the type of the first
11242   // argument.
11243   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11244 }
11245 
11246 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11247 /// __builtin_constant_p when applied to the given pointer.
11248 ///
11249 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11250 /// or it points to the first character of a string literal.
11251 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11252   APValue::LValueBase Base = LV.getLValueBase();
11253   if (Base.isNull()) {
11254     // A null base is acceptable.
11255     return true;
11256   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11257     if (!isa<StringLiteral>(E))
11258       return false;
11259     return LV.getLValueOffset().isZero();
11260   } else if (Base.is<TypeInfoLValue>()) {
11261     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11262     // evaluate to true.
11263     return true;
11264   } else {
11265     // Any other base is not constant enough for GCC.
11266     return false;
11267   }
11268 }
11269 
11270 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11271 /// GCC as we can manage.
11272 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11273   // This evaluation is not permitted to have side-effects, so evaluate it in
11274   // a speculative evaluation context.
11275   SpeculativeEvaluationRAII SpeculativeEval(Info);
11276 
11277   // Constant-folding is always enabled for the operand of __builtin_constant_p
11278   // (even when the enclosing evaluation context otherwise requires a strict
11279   // language-specific constant expression).
11280   FoldConstant Fold(Info, true);
11281 
11282   QualType ArgType = Arg->getType();
11283 
11284   // __builtin_constant_p always has one operand. The rules which gcc follows
11285   // are not precisely documented, but are as follows:
11286   //
11287   //  - If the operand is of integral, floating, complex or enumeration type,
11288   //    and can be folded to a known value of that type, it returns 1.
11289   //  - If the operand can be folded to a pointer to the first character
11290   //    of a string literal (or such a pointer cast to an integral type)
11291   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11292   //
11293   // Otherwise, it returns 0.
11294   //
11295   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11296   // its support for this did not work prior to GCC 9 and is not yet well
11297   // understood.
11298   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11299       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11300       ArgType->isNullPtrType()) {
11301     APValue V;
11302     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11303       Fold.keepDiagnostics();
11304       return false;
11305     }
11306 
11307     // For a pointer (possibly cast to integer), there are special rules.
11308     if (V.getKind() == APValue::LValue)
11309       return EvaluateBuiltinConstantPForLValue(V);
11310 
11311     // Otherwise, any constant value is good enough.
11312     return V.hasValue();
11313   }
11314 
11315   // Anything else isn't considered to be sufficiently constant.
11316   return false;
11317 }
11318 
11319 /// Retrieves the "underlying object type" of the given expression,
11320 /// as used by __builtin_object_size.
11321 static QualType getObjectType(APValue::LValueBase B) {
11322   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11323     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11324       return VD->getType();
11325   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11326     if (isa<CompoundLiteralExpr>(E))
11327       return E->getType();
11328   } else if (B.is<TypeInfoLValue>()) {
11329     return B.getTypeInfoType();
11330   } else if (B.is<DynamicAllocLValue>()) {
11331     return B.getDynamicAllocType();
11332   }
11333 
11334   return QualType();
11335 }
11336 
11337 /// A more selective version of E->IgnoreParenCasts for
11338 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11339 /// to change the type of E.
11340 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11341 ///
11342 /// Always returns an RValue with a pointer representation.
11343 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11344   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11345 
11346   auto *NoParens = E->IgnoreParens();
11347   auto *Cast = dyn_cast<CastExpr>(NoParens);
11348   if (Cast == nullptr)
11349     return NoParens;
11350 
11351   // We only conservatively allow a few kinds of casts, because this code is
11352   // inherently a simple solution that seeks to support the common case.
11353   auto CastKind = Cast->getCastKind();
11354   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11355       CastKind != CK_AddressSpaceConversion)
11356     return NoParens;
11357 
11358   auto *SubExpr = Cast->getSubExpr();
11359   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11360     return NoParens;
11361   return ignorePointerCastsAndParens(SubExpr);
11362 }
11363 
11364 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11365 /// record layout. e.g.
11366 ///   struct { struct { int a, b; } fst, snd; } obj;
11367 ///   obj.fst   // no
11368 ///   obj.snd   // yes
11369 ///   obj.fst.a // no
11370 ///   obj.fst.b // no
11371 ///   obj.snd.a // no
11372 ///   obj.snd.b // yes
11373 ///
11374 /// Please note: this function is specialized for how __builtin_object_size
11375 /// views "objects".
11376 ///
11377 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11378 /// correct result, it will always return true.
11379 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11380   assert(!LVal.Designator.Invalid);
11381 
11382   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11383     const RecordDecl *Parent = FD->getParent();
11384     Invalid = Parent->isInvalidDecl();
11385     if (Invalid || Parent->isUnion())
11386       return true;
11387     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11388     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11389   };
11390 
11391   auto &Base = LVal.getLValueBase();
11392   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11393     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11394       bool Invalid;
11395       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11396         return Invalid;
11397     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11398       for (auto *FD : IFD->chain()) {
11399         bool Invalid;
11400         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11401           return Invalid;
11402       }
11403     }
11404   }
11405 
11406   unsigned I = 0;
11407   QualType BaseType = getType(Base);
11408   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11409     // If we don't know the array bound, conservatively assume we're looking at
11410     // the final array element.
11411     ++I;
11412     if (BaseType->isIncompleteArrayType())
11413       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11414     else
11415       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11416   }
11417 
11418   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11419     const auto &Entry = LVal.Designator.Entries[I];
11420     if (BaseType->isArrayType()) {
11421       // Because __builtin_object_size treats arrays as objects, we can ignore
11422       // the index iff this is the last array in the Designator.
11423       if (I + 1 == E)
11424         return true;
11425       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11426       uint64_t Index = Entry.getAsArrayIndex();
11427       if (Index + 1 != CAT->getSize())
11428         return false;
11429       BaseType = CAT->getElementType();
11430     } else if (BaseType->isAnyComplexType()) {
11431       const auto *CT = BaseType->castAs<ComplexType>();
11432       uint64_t Index = Entry.getAsArrayIndex();
11433       if (Index != 1)
11434         return false;
11435       BaseType = CT->getElementType();
11436     } else if (auto *FD = getAsField(Entry)) {
11437       bool Invalid;
11438       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11439         return Invalid;
11440       BaseType = FD->getType();
11441     } else {
11442       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11443       return false;
11444     }
11445   }
11446   return true;
11447 }
11448 
11449 /// Tests to see if the LValue has a user-specified designator (that isn't
11450 /// necessarily valid). Note that this always returns 'true' if the LValue has
11451 /// an unsized array as its first designator entry, because there's currently no
11452 /// way to tell if the user typed *foo or foo[0].
11453 static bool refersToCompleteObject(const LValue &LVal) {
11454   if (LVal.Designator.Invalid)
11455     return false;
11456 
11457   if (!LVal.Designator.Entries.empty())
11458     return LVal.Designator.isMostDerivedAnUnsizedArray();
11459 
11460   if (!LVal.InvalidBase)
11461     return true;
11462 
11463   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11464   // the LValueBase.
11465   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11466   return !E || !isa<MemberExpr>(E);
11467 }
11468 
11469 /// Attempts to detect a user writing into a piece of memory that's impossible
11470 /// to figure out the size of by just using types.
11471 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11472   const SubobjectDesignator &Designator = LVal.Designator;
11473   // Notes:
11474   // - Users can only write off of the end when we have an invalid base. Invalid
11475   //   bases imply we don't know where the memory came from.
11476   // - We used to be a bit more aggressive here; we'd only be conservative if
11477   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11478   //   broke some common standard library extensions (PR30346), but was
11479   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11480   //   with some sort of list. OTOH, it seems that GCC is always
11481   //   conservative with the last element in structs (if it's an array), so our
11482   //   current behavior is more compatible than an explicit list approach would
11483   //   be.
11484   return LVal.InvalidBase &&
11485          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11486          Designator.MostDerivedIsArrayElement &&
11487          isDesignatorAtObjectEnd(Ctx, LVal);
11488 }
11489 
11490 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11491 /// Fails if the conversion would cause loss of precision.
11492 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11493                                             CharUnits &Result) {
11494   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11495   if (Int.ugt(CharUnitsMax))
11496     return false;
11497   Result = CharUnits::fromQuantity(Int.getZExtValue());
11498   return true;
11499 }
11500 
11501 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11502 /// determine how many bytes exist from the beginning of the object to either
11503 /// the end of the current subobject, or the end of the object itself, depending
11504 /// on what the LValue looks like + the value of Type.
11505 ///
11506 /// If this returns false, the value of Result is undefined.
11507 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11508                                unsigned Type, const LValue &LVal,
11509                                CharUnits &EndOffset) {
11510   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11511 
11512   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11513     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11514       return false;
11515     return HandleSizeof(Info, ExprLoc, Ty, Result);
11516   };
11517 
11518   // We want to evaluate the size of the entire object. This is a valid fallback
11519   // for when Type=1 and the designator is invalid, because we're asked for an
11520   // upper-bound.
11521   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11522     // Type=3 wants a lower bound, so we can't fall back to this.
11523     if (Type == 3 && !DetermineForCompleteObject)
11524       return false;
11525 
11526     llvm::APInt APEndOffset;
11527     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11528         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11529       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11530 
11531     if (LVal.InvalidBase)
11532       return false;
11533 
11534     QualType BaseTy = getObjectType(LVal.getLValueBase());
11535     return CheckedHandleSizeof(BaseTy, EndOffset);
11536   }
11537 
11538   // We want to evaluate the size of a subobject.
11539   const SubobjectDesignator &Designator = LVal.Designator;
11540 
11541   // The following is a moderately common idiom in C:
11542   //
11543   // struct Foo { int a; char c[1]; };
11544   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11545   // strcpy(&F->c[0], Bar);
11546   //
11547   // In order to not break too much legacy code, we need to support it.
11548   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11549     // If we can resolve this to an alloc_size call, we can hand that back,
11550     // because we know for certain how many bytes there are to write to.
11551     llvm::APInt APEndOffset;
11552     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11553         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11554       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11555 
11556     // If we cannot determine the size of the initial allocation, then we can't
11557     // given an accurate upper-bound. However, we are still able to give
11558     // conservative lower-bounds for Type=3.
11559     if (Type == 1)
11560       return false;
11561   }
11562 
11563   CharUnits BytesPerElem;
11564   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11565     return false;
11566 
11567   // According to the GCC documentation, we want the size of the subobject
11568   // denoted by the pointer. But that's not quite right -- what we actually
11569   // want is the size of the immediately-enclosing array, if there is one.
11570   int64_t ElemsRemaining;
11571   if (Designator.MostDerivedIsArrayElement &&
11572       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11573     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11574     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11575     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11576   } else {
11577     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11578   }
11579 
11580   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11581   return true;
11582 }
11583 
11584 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11585 /// returns true and stores the result in @p Size.
11586 ///
11587 /// If @p WasError is non-null, this will report whether the failure to evaluate
11588 /// is to be treated as an Error in IntExprEvaluator.
11589 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11590                                          EvalInfo &Info, uint64_t &Size) {
11591   // Determine the denoted object.
11592   LValue LVal;
11593   {
11594     // The operand of __builtin_object_size is never evaluated for side-effects.
11595     // If there are any, but we can determine the pointed-to object anyway, then
11596     // ignore the side-effects.
11597     SpeculativeEvaluationRAII SpeculativeEval(Info);
11598     IgnoreSideEffectsRAII Fold(Info);
11599 
11600     if (E->isGLValue()) {
11601       // It's possible for us to be given GLValues if we're called via
11602       // Expr::tryEvaluateObjectSize.
11603       APValue RVal;
11604       if (!EvaluateAsRValue(Info, E, RVal))
11605         return false;
11606       LVal.setFrom(Info.Ctx, RVal);
11607     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11608                                 /*InvalidBaseOK=*/true))
11609       return false;
11610   }
11611 
11612   // If we point to before the start of the object, there are no accessible
11613   // bytes.
11614   if (LVal.getLValueOffset().isNegative()) {
11615     Size = 0;
11616     return true;
11617   }
11618 
11619   CharUnits EndOffset;
11620   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11621     return false;
11622 
11623   // If we've fallen outside of the end offset, just pretend there's nothing to
11624   // write to/read from.
11625   if (EndOffset <= LVal.getLValueOffset())
11626     Size = 0;
11627   else
11628     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11629   return true;
11630 }
11631 
11632 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11633   if (unsigned BuiltinOp = E->getBuiltinCallee())
11634     return VisitBuiltinCallExpr(E, BuiltinOp);
11635 
11636   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11637 }
11638 
11639 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11640                                      APValue &Val, APSInt &Alignment) {
11641   QualType SrcTy = E->getArg(0)->getType();
11642   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11643     return false;
11644   // Even though we are evaluating integer expressions we could get a pointer
11645   // argument for the __builtin_is_aligned() case.
11646   if (SrcTy->isPointerType()) {
11647     LValue Ptr;
11648     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11649       return false;
11650     Ptr.moveInto(Val);
11651   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11652     Info.FFDiag(E->getArg(0));
11653     return false;
11654   } else {
11655     APSInt SrcInt;
11656     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11657       return false;
11658     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11659            "Bit widths must be the same");
11660     Val = APValue(SrcInt);
11661   }
11662   assert(Val.hasValue());
11663   return true;
11664 }
11665 
11666 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11667                                             unsigned BuiltinOp) {
11668   switch (BuiltinOp) {
11669   default:
11670     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11671 
11672   case Builtin::BI__builtin_dynamic_object_size:
11673   case Builtin::BI__builtin_object_size: {
11674     // The type was checked when we built the expression.
11675     unsigned Type =
11676         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11677     assert(Type <= 3 && "unexpected type");
11678 
11679     uint64_t Size;
11680     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11681       return Success(Size, E);
11682 
11683     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11684       return Success((Type & 2) ? 0 : -1, E);
11685 
11686     // Expression had no side effects, but we couldn't statically determine the
11687     // size of the referenced object.
11688     switch (Info.EvalMode) {
11689     case EvalInfo::EM_ConstantExpression:
11690     case EvalInfo::EM_ConstantFold:
11691     case EvalInfo::EM_IgnoreSideEffects:
11692       // Leave it to IR generation.
11693       return Error(E);
11694     case EvalInfo::EM_ConstantExpressionUnevaluated:
11695       // Reduce it to a constant now.
11696       return Success((Type & 2) ? 0 : -1, E);
11697     }
11698 
11699     llvm_unreachable("unexpected EvalMode");
11700   }
11701 
11702   case Builtin::BI__builtin_os_log_format_buffer_size: {
11703     analyze_os_log::OSLogBufferLayout Layout;
11704     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11705     return Success(Layout.size().getQuantity(), E);
11706   }
11707 
11708   case Builtin::BI__builtin_is_aligned: {
11709     APValue Src;
11710     APSInt Alignment;
11711     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11712       return false;
11713     if (Src.isLValue()) {
11714       // If we evaluated a pointer, check the minimum known alignment.
11715       LValue Ptr;
11716       Ptr.setFrom(Info.Ctx, Src);
11717       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11718       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11719       // We can return true if the known alignment at the computed offset is
11720       // greater than the requested alignment.
11721       assert(PtrAlign.isPowerOfTwo());
11722       assert(Alignment.isPowerOf2());
11723       if (PtrAlign.getQuantity() >= Alignment)
11724         return Success(1, E);
11725       // If the alignment is not known to be sufficient, some cases could still
11726       // be aligned at run time. However, if the requested alignment is less or
11727       // equal to the base alignment and the offset is not aligned, we know that
11728       // the run-time value can never be aligned.
11729       if (BaseAlignment.getQuantity() >= Alignment &&
11730           PtrAlign.getQuantity() < Alignment)
11731         return Success(0, E);
11732       // Otherwise we can't infer whether the value is sufficiently aligned.
11733       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11734       //  in cases where we can't fully evaluate the pointer.
11735       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11736           << Alignment;
11737       return false;
11738     }
11739     assert(Src.isInt());
11740     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11741   }
11742   case Builtin::BI__builtin_align_up: {
11743     APValue Src;
11744     APSInt Alignment;
11745     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11746       return false;
11747     if (!Src.isInt())
11748       return Error(E);
11749     APSInt AlignedVal =
11750         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11751                Src.getInt().isUnsigned());
11752     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11753     return Success(AlignedVal, E);
11754   }
11755   case Builtin::BI__builtin_align_down: {
11756     APValue Src;
11757     APSInt Alignment;
11758     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11759       return false;
11760     if (!Src.isInt())
11761       return Error(E);
11762     APSInt AlignedVal =
11763         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11764     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11765     return Success(AlignedVal, E);
11766   }
11767 
11768   case Builtin::BI__builtin_bitreverse8:
11769   case Builtin::BI__builtin_bitreverse16:
11770   case Builtin::BI__builtin_bitreverse32:
11771   case Builtin::BI__builtin_bitreverse64: {
11772     APSInt Val;
11773     if (!EvaluateInteger(E->getArg(0), Val, Info))
11774       return false;
11775 
11776     return Success(Val.reverseBits(), E);
11777   }
11778 
11779   case Builtin::BI__builtin_bswap16:
11780   case Builtin::BI__builtin_bswap32:
11781   case Builtin::BI__builtin_bswap64: {
11782     APSInt Val;
11783     if (!EvaluateInteger(E->getArg(0), Val, Info))
11784       return false;
11785 
11786     return Success(Val.byteSwap(), E);
11787   }
11788 
11789   case Builtin::BI__builtin_classify_type:
11790     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11791 
11792   case Builtin::BI__builtin_clrsb:
11793   case Builtin::BI__builtin_clrsbl:
11794   case Builtin::BI__builtin_clrsbll: {
11795     APSInt Val;
11796     if (!EvaluateInteger(E->getArg(0), Val, Info))
11797       return false;
11798 
11799     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11800   }
11801 
11802   case Builtin::BI__builtin_clz:
11803   case Builtin::BI__builtin_clzl:
11804   case Builtin::BI__builtin_clzll:
11805   case Builtin::BI__builtin_clzs: {
11806     APSInt Val;
11807     if (!EvaluateInteger(E->getArg(0), Val, Info))
11808       return false;
11809     if (!Val)
11810       return Error(E);
11811 
11812     return Success(Val.countLeadingZeros(), E);
11813   }
11814 
11815   case Builtin::BI__builtin_constant_p: {
11816     const Expr *Arg = E->getArg(0);
11817     if (EvaluateBuiltinConstantP(Info, Arg))
11818       return Success(true, E);
11819     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11820       // Outside a constant context, eagerly evaluate to false in the presence
11821       // of side-effects in order to avoid -Wunsequenced false-positives in
11822       // a branch on __builtin_constant_p(expr).
11823       return Success(false, E);
11824     }
11825     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11826     return false;
11827   }
11828 
11829   case Builtin::BI__builtin_is_constant_evaluated: {
11830     const auto *Callee = Info.CurrentCall->getCallee();
11831     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11832         (Info.CallStackDepth == 1 ||
11833          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11834           Callee->getIdentifier() &&
11835           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11836       // FIXME: Find a better way to avoid duplicated diagnostics.
11837       if (Info.EvalStatus.Diag)
11838         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11839                                                : Info.CurrentCall->CallLoc,
11840                     diag::warn_is_constant_evaluated_always_true_constexpr)
11841             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11842                                          : "std::is_constant_evaluated");
11843     }
11844 
11845     return Success(Info.InConstantContext, E);
11846   }
11847 
11848   case Builtin::BI__builtin_ctz:
11849   case Builtin::BI__builtin_ctzl:
11850   case Builtin::BI__builtin_ctzll:
11851   case Builtin::BI__builtin_ctzs: {
11852     APSInt Val;
11853     if (!EvaluateInteger(E->getArg(0), Val, Info))
11854       return false;
11855     if (!Val)
11856       return Error(E);
11857 
11858     return Success(Val.countTrailingZeros(), E);
11859   }
11860 
11861   case Builtin::BI__builtin_eh_return_data_regno: {
11862     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11863     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11864     return Success(Operand, E);
11865   }
11866 
11867   case Builtin::BI__builtin_expect:
11868   case Builtin::BI__builtin_expect_with_probability:
11869     return Visit(E->getArg(0));
11870 
11871   case Builtin::BI__builtin_ffs:
11872   case Builtin::BI__builtin_ffsl:
11873   case Builtin::BI__builtin_ffsll: {
11874     APSInt Val;
11875     if (!EvaluateInteger(E->getArg(0), Val, Info))
11876       return false;
11877 
11878     unsigned N = Val.countTrailingZeros();
11879     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11880   }
11881 
11882   case Builtin::BI__builtin_fpclassify: {
11883     APFloat Val(0.0);
11884     if (!EvaluateFloat(E->getArg(5), Val, Info))
11885       return false;
11886     unsigned Arg;
11887     switch (Val.getCategory()) {
11888     case APFloat::fcNaN: Arg = 0; break;
11889     case APFloat::fcInfinity: Arg = 1; break;
11890     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11891     case APFloat::fcZero: Arg = 4; break;
11892     }
11893     return Visit(E->getArg(Arg));
11894   }
11895 
11896   case Builtin::BI__builtin_isinf_sign: {
11897     APFloat Val(0.0);
11898     return EvaluateFloat(E->getArg(0), Val, Info) &&
11899            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11900   }
11901 
11902   case Builtin::BI__builtin_isinf: {
11903     APFloat Val(0.0);
11904     return EvaluateFloat(E->getArg(0), Val, Info) &&
11905            Success(Val.isInfinity() ? 1 : 0, E);
11906   }
11907 
11908   case Builtin::BI__builtin_isfinite: {
11909     APFloat Val(0.0);
11910     return EvaluateFloat(E->getArg(0), Val, Info) &&
11911            Success(Val.isFinite() ? 1 : 0, E);
11912   }
11913 
11914   case Builtin::BI__builtin_isnan: {
11915     APFloat Val(0.0);
11916     return EvaluateFloat(E->getArg(0), Val, Info) &&
11917            Success(Val.isNaN() ? 1 : 0, E);
11918   }
11919 
11920   case Builtin::BI__builtin_isnormal: {
11921     APFloat Val(0.0);
11922     return EvaluateFloat(E->getArg(0), Val, Info) &&
11923            Success(Val.isNormal() ? 1 : 0, E);
11924   }
11925 
11926   case Builtin::BI__builtin_parity:
11927   case Builtin::BI__builtin_parityl:
11928   case Builtin::BI__builtin_parityll: {
11929     APSInt Val;
11930     if (!EvaluateInteger(E->getArg(0), Val, Info))
11931       return false;
11932 
11933     return Success(Val.countPopulation() % 2, E);
11934   }
11935 
11936   case Builtin::BI__builtin_popcount:
11937   case Builtin::BI__builtin_popcountl:
11938   case Builtin::BI__builtin_popcountll: {
11939     APSInt Val;
11940     if (!EvaluateInteger(E->getArg(0), Val, Info))
11941       return false;
11942 
11943     return Success(Val.countPopulation(), E);
11944   }
11945 
11946   case Builtin::BI__builtin_rotateleft8:
11947   case Builtin::BI__builtin_rotateleft16:
11948   case Builtin::BI__builtin_rotateleft32:
11949   case Builtin::BI__builtin_rotateleft64:
11950   case Builtin::BI_rotl8: // Microsoft variants of rotate right
11951   case Builtin::BI_rotl16:
11952   case Builtin::BI_rotl:
11953   case Builtin::BI_lrotl:
11954   case Builtin::BI_rotl64: {
11955     APSInt Val, Amt;
11956     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11957         !EvaluateInteger(E->getArg(1), Amt, Info))
11958       return false;
11959 
11960     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
11961   }
11962 
11963   case Builtin::BI__builtin_rotateright8:
11964   case Builtin::BI__builtin_rotateright16:
11965   case Builtin::BI__builtin_rotateright32:
11966   case Builtin::BI__builtin_rotateright64:
11967   case Builtin::BI_rotr8: // Microsoft variants of rotate right
11968   case Builtin::BI_rotr16:
11969   case Builtin::BI_rotr:
11970   case Builtin::BI_lrotr:
11971   case Builtin::BI_rotr64: {
11972     APSInt Val, Amt;
11973     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11974         !EvaluateInteger(E->getArg(1), Amt, Info))
11975       return false;
11976 
11977     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
11978   }
11979 
11980   case Builtin::BIstrlen:
11981   case Builtin::BIwcslen:
11982     // A call to strlen is not a constant expression.
11983     if (Info.getLangOpts().CPlusPlus11)
11984       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11985         << /*isConstexpr*/0 << /*isConstructor*/0
11986         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11987     else
11988       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11989     LLVM_FALLTHROUGH;
11990   case Builtin::BI__builtin_strlen:
11991   case Builtin::BI__builtin_wcslen: {
11992     // As an extension, we support __builtin_strlen() as a constant expression,
11993     // and support folding strlen() to a constant.
11994     uint64_t StrLen;
11995     if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
11996       return Success(StrLen, E);
11997     return false;
11998   }
11999 
12000   case Builtin::BIstrcmp:
12001   case Builtin::BIwcscmp:
12002   case Builtin::BIstrncmp:
12003   case Builtin::BIwcsncmp:
12004   case Builtin::BImemcmp:
12005   case Builtin::BIbcmp:
12006   case Builtin::BIwmemcmp:
12007     // A call to strlen is not a constant expression.
12008     if (Info.getLangOpts().CPlusPlus11)
12009       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12010         << /*isConstexpr*/0 << /*isConstructor*/0
12011         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
12012     else
12013       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12014     LLVM_FALLTHROUGH;
12015   case Builtin::BI__builtin_strcmp:
12016   case Builtin::BI__builtin_wcscmp:
12017   case Builtin::BI__builtin_strncmp:
12018   case Builtin::BI__builtin_wcsncmp:
12019   case Builtin::BI__builtin_memcmp:
12020   case Builtin::BI__builtin_bcmp:
12021   case Builtin::BI__builtin_wmemcmp: {
12022     LValue String1, String2;
12023     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12024         !EvaluatePointer(E->getArg(1), String2, Info))
12025       return false;
12026 
12027     uint64_t MaxLength = uint64_t(-1);
12028     if (BuiltinOp != Builtin::BIstrcmp &&
12029         BuiltinOp != Builtin::BIwcscmp &&
12030         BuiltinOp != Builtin::BI__builtin_strcmp &&
12031         BuiltinOp != Builtin::BI__builtin_wcscmp) {
12032       APSInt N;
12033       if (!EvaluateInteger(E->getArg(2), N, Info))
12034         return false;
12035       MaxLength = N.getExtValue();
12036     }
12037 
12038     // Empty substrings compare equal by definition.
12039     if (MaxLength == 0u)
12040       return Success(0, E);
12041 
12042     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12043         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12044         String1.Designator.Invalid || String2.Designator.Invalid)
12045       return false;
12046 
12047     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12048     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12049 
12050     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12051                      BuiltinOp == Builtin::BIbcmp ||
12052                      BuiltinOp == Builtin::BI__builtin_memcmp ||
12053                      BuiltinOp == Builtin::BI__builtin_bcmp;
12054 
12055     assert(IsRawByte ||
12056            (Info.Ctx.hasSameUnqualifiedType(
12057                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12058             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12059 
12060     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12061     // 'char8_t', but no other types.
12062     if (IsRawByte &&
12063         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12064       // FIXME: Consider using our bit_cast implementation to support this.
12065       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12066           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
12067           << CharTy1 << CharTy2;
12068       return false;
12069     }
12070 
12071     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12072       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12073              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12074              Char1.isInt() && Char2.isInt();
12075     };
12076     const auto &AdvanceElems = [&] {
12077       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12078              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12079     };
12080 
12081     bool StopAtNull =
12082         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12083          BuiltinOp != Builtin::BIwmemcmp &&
12084          BuiltinOp != Builtin::BI__builtin_memcmp &&
12085          BuiltinOp != Builtin::BI__builtin_bcmp &&
12086          BuiltinOp != Builtin::BI__builtin_wmemcmp);
12087     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12088                   BuiltinOp == Builtin::BIwcsncmp ||
12089                   BuiltinOp == Builtin::BIwmemcmp ||
12090                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
12091                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12092                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
12093 
12094     for (; MaxLength; --MaxLength) {
12095       APValue Char1, Char2;
12096       if (!ReadCurElems(Char1, Char2))
12097         return false;
12098       if (Char1.getInt().ne(Char2.getInt())) {
12099         if (IsWide) // wmemcmp compares with wchar_t signedness.
12100           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12101         // memcmp always compares unsigned chars.
12102         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12103       }
12104       if (StopAtNull && !Char1.getInt())
12105         return Success(0, E);
12106       assert(!(StopAtNull && !Char2.getInt()));
12107       if (!AdvanceElems())
12108         return false;
12109     }
12110     // We hit the strncmp / memcmp limit.
12111     return Success(0, E);
12112   }
12113 
12114   case Builtin::BI__atomic_always_lock_free:
12115   case Builtin::BI__atomic_is_lock_free:
12116   case Builtin::BI__c11_atomic_is_lock_free: {
12117     APSInt SizeVal;
12118     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12119       return false;
12120 
12121     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12122     // of two less than or equal to the maximum inline atomic width, we know it
12123     // is lock-free.  If the size isn't a power of two, or greater than the
12124     // maximum alignment where we promote atomics, we know it is not lock-free
12125     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
12126     // the answer can only be determined at runtime; for example, 16-byte
12127     // atomics have lock-free implementations on some, but not all,
12128     // x86-64 processors.
12129 
12130     // Check power-of-two.
12131     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12132     if (Size.isPowerOfTwo()) {
12133       // Check against inlining width.
12134       unsigned InlineWidthBits =
12135           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12136       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12137         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12138             Size == CharUnits::One() ||
12139             E->getArg(1)->isNullPointerConstant(Info.Ctx,
12140                                                 Expr::NPC_NeverValueDependent))
12141           // OK, we will inline appropriately-aligned operations of this size,
12142           // and _Atomic(T) is appropriately-aligned.
12143           return Success(1, E);
12144 
12145         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12146           castAs<PointerType>()->getPointeeType();
12147         if (!PointeeType->isIncompleteType() &&
12148             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12149           // OK, we will inline operations on this object.
12150           return Success(1, E);
12151         }
12152       }
12153     }
12154 
12155     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12156         Success(0, E) : Error(E);
12157   }
12158   case Builtin::BI__builtin_add_overflow:
12159   case Builtin::BI__builtin_sub_overflow:
12160   case Builtin::BI__builtin_mul_overflow:
12161   case Builtin::BI__builtin_sadd_overflow:
12162   case Builtin::BI__builtin_uadd_overflow:
12163   case Builtin::BI__builtin_uaddl_overflow:
12164   case Builtin::BI__builtin_uaddll_overflow:
12165   case Builtin::BI__builtin_usub_overflow:
12166   case Builtin::BI__builtin_usubl_overflow:
12167   case Builtin::BI__builtin_usubll_overflow:
12168   case Builtin::BI__builtin_umul_overflow:
12169   case Builtin::BI__builtin_umull_overflow:
12170   case Builtin::BI__builtin_umulll_overflow:
12171   case Builtin::BI__builtin_saddl_overflow:
12172   case Builtin::BI__builtin_saddll_overflow:
12173   case Builtin::BI__builtin_ssub_overflow:
12174   case Builtin::BI__builtin_ssubl_overflow:
12175   case Builtin::BI__builtin_ssubll_overflow:
12176   case Builtin::BI__builtin_smul_overflow:
12177   case Builtin::BI__builtin_smull_overflow:
12178   case Builtin::BI__builtin_smulll_overflow: {
12179     LValue ResultLValue;
12180     APSInt LHS, RHS;
12181 
12182     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12183     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12184         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12185         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12186       return false;
12187 
12188     APSInt Result;
12189     bool DidOverflow = false;
12190 
12191     // If the types don't have to match, enlarge all 3 to the largest of them.
12192     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12193         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12194         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12195       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12196                       ResultType->isSignedIntegerOrEnumerationType();
12197       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12198                       ResultType->isSignedIntegerOrEnumerationType();
12199       uint64_t LHSSize = LHS.getBitWidth();
12200       uint64_t RHSSize = RHS.getBitWidth();
12201       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12202       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12203 
12204       // Add an additional bit if the signedness isn't uniformly agreed to. We
12205       // could do this ONLY if there is a signed and an unsigned that both have
12206       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12207       // caught in the shrink-to-result later anyway.
12208       if (IsSigned && !AllSigned)
12209         ++MaxBits;
12210 
12211       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12212       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12213       Result = APSInt(MaxBits, !IsSigned);
12214     }
12215 
12216     // Find largest int.
12217     switch (BuiltinOp) {
12218     default:
12219       llvm_unreachable("Invalid value for BuiltinOp");
12220     case Builtin::BI__builtin_add_overflow:
12221     case Builtin::BI__builtin_sadd_overflow:
12222     case Builtin::BI__builtin_saddl_overflow:
12223     case Builtin::BI__builtin_saddll_overflow:
12224     case Builtin::BI__builtin_uadd_overflow:
12225     case Builtin::BI__builtin_uaddl_overflow:
12226     case Builtin::BI__builtin_uaddll_overflow:
12227       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12228                               : LHS.uadd_ov(RHS, DidOverflow);
12229       break;
12230     case Builtin::BI__builtin_sub_overflow:
12231     case Builtin::BI__builtin_ssub_overflow:
12232     case Builtin::BI__builtin_ssubl_overflow:
12233     case Builtin::BI__builtin_ssubll_overflow:
12234     case Builtin::BI__builtin_usub_overflow:
12235     case Builtin::BI__builtin_usubl_overflow:
12236     case Builtin::BI__builtin_usubll_overflow:
12237       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12238                               : LHS.usub_ov(RHS, DidOverflow);
12239       break;
12240     case Builtin::BI__builtin_mul_overflow:
12241     case Builtin::BI__builtin_smul_overflow:
12242     case Builtin::BI__builtin_smull_overflow:
12243     case Builtin::BI__builtin_smulll_overflow:
12244     case Builtin::BI__builtin_umul_overflow:
12245     case Builtin::BI__builtin_umull_overflow:
12246     case Builtin::BI__builtin_umulll_overflow:
12247       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12248                               : LHS.umul_ov(RHS, DidOverflow);
12249       break;
12250     }
12251 
12252     // In the case where multiple sizes are allowed, truncate and see if
12253     // the values are the same.
12254     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12255         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12256         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12257       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12258       // since it will give us the behavior of a TruncOrSelf in the case where
12259       // its parameter <= its size.  We previously set Result to be at least the
12260       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12261       // will work exactly like TruncOrSelf.
12262       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12263       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12264 
12265       if (!APSInt::isSameValue(Temp, Result))
12266         DidOverflow = true;
12267       Result = Temp;
12268     }
12269 
12270     APValue APV{Result};
12271     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12272       return false;
12273     return Success(DidOverflow, E);
12274   }
12275   }
12276 }
12277 
12278 /// Determine whether this is a pointer past the end of the complete
12279 /// object referred to by the lvalue.
12280 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12281                                             const LValue &LV) {
12282   // A null pointer can be viewed as being "past the end" but we don't
12283   // choose to look at it that way here.
12284   if (!LV.getLValueBase())
12285     return false;
12286 
12287   // If the designator is valid and refers to a subobject, we're not pointing
12288   // past the end.
12289   if (!LV.getLValueDesignator().Invalid &&
12290       !LV.getLValueDesignator().isOnePastTheEnd())
12291     return false;
12292 
12293   // A pointer to an incomplete type might be past-the-end if the type's size is
12294   // zero.  We cannot tell because the type is incomplete.
12295   QualType Ty = getType(LV.getLValueBase());
12296   if (Ty->isIncompleteType())
12297     return true;
12298 
12299   // We're a past-the-end pointer if we point to the byte after the object,
12300   // no matter what our type or path is.
12301   auto Size = Ctx.getTypeSizeInChars(Ty);
12302   return LV.getLValueOffset() == Size;
12303 }
12304 
12305 namespace {
12306 
12307 /// Data recursive integer evaluator of certain binary operators.
12308 ///
12309 /// We use a data recursive algorithm for binary operators so that we are able
12310 /// to handle extreme cases of chained binary operators without causing stack
12311 /// overflow.
12312 class DataRecursiveIntBinOpEvaluator {
12313   struct EvalResult {
12314     APValue Val;
12315     bool Failed;
12316 
12317     EvalResult() : Failed(false) { }
12318 
12319     void swap(EvalResult &RHS) {
12320       Val.swap(RHS.Val);
12321       Failed = RHS.Failed;
12322       RHS.Failed = false;
12323     }
12324   };
12325 
12326   struct Job {
12327     const Expr *E;
12328     EvalResult LHSResult; // meaningful only for binary operator expression.
12329     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12330 
12331     Job() = default;
12332     Job(Job &&) = default;
12333 
12334     void startSpeculativeEval(EvalInfo &Info) {
12335       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12336     }
12337 
12338   private:
12339     SpeculativeEvaluationRAII SpecEvalRAII;
12340   };
12341 
12342   SmallVector<Job, 16> Queue;
12343 
12344   IntExprEvaluator &IntEval;
12345   EvalInfo &Info;
12346   APValue &FinalResult;
12347 
12348 public:
12349   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12350     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12351 
12352   /// True if \param E is a binary operator that we are going to handle
12353   /// data recursively.
12354   /// We handle binary operators that are comma, logical, or that have operands
12355   /// with integral or enumeration type.
12356   static bool shouldEnqueue(const BinaryOperator *E) {
12357     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12358            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12359             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12360             E->getRHS()->getType()->isIntegralOrEnumerationType());
12361   }
12362 
12363   bool Traverse(const BinaryOperator *E) {
12364     enqueue(E);
12365     EvalResult PrevResult;
12366     while (!Queue.empty())
12367       process(PrevResult);
12368 
12369     if (PrevResult.Failed) return false;
12370 
12371     FinalResult.swap(PrevResult.Val);
12372     return true;
12373   }
12374 
12375 private:
12376   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12377     return IntEval.Success(Value, E, Result);
12378   }
12379   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12380     return IntEval.Success(Value, E, Result);
12381   }
12382   bool Error(const Expr *E) {
12383     return IntEval.Error(E);
12384   }
12385   bool Error(const Expr *E, diag::kind D) {
12386     return IntEval.Error(E, D);
12387   }
12388 
12389   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12390     return Info.CCEDiag(E, D);
12391   }
12392 
12393   // Returns true if visiting the RHS is necessary, false otherwise.
12394   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12395                          bool &SuppressRHSDiags);
12396 
12397   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12398                   const BinaryOperator *E, APValue &Result);
12399 
12400   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12401     Result.Failed = !Evaluate(Result.Val, Info, E);
12402     if (Result.Failed)
12403       Result.Val = APValue();
12404   }
12405 
12406   void process(EvalResult &Result);
12407 
12408   void enqueue(const Expr *E) {
12409     E = E->IgnoreParens();
12410     Queue.resize(Queue.size()+1);
12411     Queue.back().E = E;
12412     Queue.back().Kind = Job::AnyExprKind;
12413   }
12414 };
12415 
12416 }
12417 
12418 bool DataRecursiveIntBinOpEvaluator::
12419        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12420                          bool &SuppressRHSDiags) {
12421   if (E->getOpcode() == BO_Comma) {
12422     // Ignore LHS but note if we could not evaluate it.
12423     if (LHSResult.Failed)
12424       return Info.noteSideEffect();
12425     return true;
12426   }
12427 
12428   if (E->isLogicalOp()) {
12429     bool LHSAsBool;
12430     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12431       // We were able to evaluate the LHS, see if we can get away with not
12432       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12433       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12434         Success(LHSAsBool, E, LHSResult.Val);
12435         return false; // Ignore RHS
12436       }
12437     } else {
12438       LHSResult.Failed = true;
12439 
12440       // Since we weren't able to evaluate the left hand side, it
12441       // might have had side effects.
12442       if (!Info.noteSideEffect())
12443         return false;
12444 
12445       // We can't evaluate the LHS; however, sometimes the result
12446       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12447       // Don't ignore RHS and suppress diagnostics from this arm.
12448       SuppressRHSDiags = true;
12449     }
12450 
12451     return true;
12452   }
12453 
12454   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12455          E->getRHS()->getType()->isIntegralOrEnumerationType());
12456 
12457   if (LHSResult.Failed && !Info.noteFailure())
12458     return false; // Ignore RHS;
12459 
12460   return true;
12461 }
12462 
12463 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12464                                     bool IsSub) {
12465   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12466   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12467   // offsets.
12468   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12469   CharUnits &Offset = LVal.getLValueOffset();
12470   uint64_t Offset64 = Offset.getQuantity();
12471   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12472   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12473                                          : Offset64 + Index64);
12474 }
12475 
12476 bool DataRecursiveIntBinOpEvaluator::
12477        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12478                   const BinaryOperator *E, APValue &Result) {
12479   if (E->getOpcode() == BO_Comma) {
12480     if (RHSResult.Failed)
12481       return false;
12482     Result = RHSResult.Val;
12483     return true;
12484   }
12485 
12486   if (E->isLogicalOp()) {
12487     bool lhsResult, rhsResult;
12488     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12489     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12490 
12491     if (LHSIsOK) {
12492       if (RHSIsOK) {
12493         if (E->getOpcode() == BO_LOr)
12494           return Success(lhsResult || rhsResult, E, Result);
12495         else
12496           return Success(lhsResult && rhsResult, E, Result);
12497       }
12498     } else {
12499       if (RHSIsOK) {
12500         // We can't evaluate the LHS; however, sometimes the result
12501         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12502         if (rhsResult == (E->getOpcode() == BO_LOr))
12503           return Success(rhsResult, E, Result);
12504       }
12505     }
12506 
12507     return false;
12508   }
12509 
12510   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12511          E->getRHS()->getType()->isIntegralOrEnumerationType());
12512 
12513   if (LHSResult.Failed || RHSResult.Failed)
12514     return false;
12515 
12516   const APValue &LHSVal = LHSResult.Val;
12517   const APValue &RHSVal = RHSResult.Val;
12518 
12519   // Handle cases like (unsigned long)&a + 4.
12520   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12521     Result = LHSVal;
12522     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12523     return true;
12524   }
12525 
12526   // Handle cases like 4 + (unsigned long)&a
12527   if (E->getOpcode() == BO_Add &&
12528       RHSVal.isLValue() && LHSVal.isInt()) {
12529     Result = RHSVal;
12530     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12531     return true;
12532   }
12533 
12534   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12535     // Handle (intptr_t)&&A - (intptr_t)&&B.
12536     if (!LHSVal.getLValueOffset().isZero() ||
12537         !RHSVal.getLValueOffset().isZero())
12538       return false;
12539     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12540     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12541     if (!LHSExpr || !RHSExpr)
12542       return false;
12543     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12544     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12545     if (!LHSAddrExpr || !RHSAddrExpr)
12546       return false;
12547     // Make sure both labels come from the same function.
12548     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12549         RHSAddrExpr->getLabel()->getDeclContext())
12550       return false;
12551     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12552     return true;
12553   }
12554 
12555   // All the remaining cases expect both operands to be an integer
12556   if (!LHSVal.isInt() || !RHSVal.isInt())
12557     return Error(E);
12558 
12559   // Set up the width and signedness manually, in case it can't be deduced
12560   // from the operation we're performing.
12561   // FIXME: Don't do this in the cases where we can deduce it.
12562   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12563                E->getType()->isUnsignedIntegerOrEnumerationType());
12564   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12565                          RHSVal.getInt(), Value))
12566     return false;
12567   return Success(Value, E, Result);
12568 }
12569 
12570 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12571   Job &job = Queue.back();
12572 
12573   switch (job.Kind) {
12574     case Job::AnyExprKind: {
12575       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12576         if (shouldEnqueue(Bop)) {
12577           job.Kind = Job::BinOpKind;
12578           enqueue(Bop->getLHS());
12579           return;
12580         }
12581       }
12582 
12583       EvaluateExpr(job.E, Result);
12584       Queue.pop_back();
12585       return;
12586     }
12587 
12588     case Job::BinOpKind: {
12589       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12590       bool SuppressRHSDiags = false;
12591       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12592         Queue.pop_back();
12593         return;
12594       }
12595       if (SuppressRHSDiags)
12596         job.startSpeculativeEval(Info);
12597       job.LHSResult.swap(Result);
12598       job.Kind = Job::BinOpVisitedLHSKind;
12599       enqueue(Bop->getRHS());
12600       return;
12601     }
12602 
12603     case Job::BinOpVisitedLHSKind: {
12604       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12605       EvalResult RHS;
12606       RHS.swap(Result);
12607       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12608       Queue.pop_back();
12609       return;
12610     }
12611   }
12612 
12613   llvm_unreachable("Invalid Job::Kind!");
12614 }
12615 
12616 namespace {
12617 enum class CmpResult {
12618   Unequal,
12619   Less,
12620   Equal,
12621   Greater,
12622   Unordered,
12623 };
12624 }
12625 
12626 template <class SuccessCB, class AfterCB>
12627 static bool
12628 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12629                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12630   assert(!E->isValueDependent());
12631   assert(E->isComparisonOp() && "expected comparison operator");
12632   assert((E->getOpcode() == BO_Cmp ||
12633           E->getType()->isIntegralOrEnumerationType()) &&
12634          "unsupported binary expression evaluation");
12635   auto Error = [&](const Expr *E) {
12636     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12637     return false;
12638   };
12639 
12640   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12641   bool IsEquality = E->isEqualityOp();
12642 
12643   QualType LHSTy = E->getLHS()->getType();
12644   QualType RHSTy = E->getRHS()->getType();
12645 
12646   if (LHSTy->isIntegralOrEnumerationType() &&
12647       RHSTy->isIntegralOrEnumerationType()) {
12648     APSInt LHS, RHS;
12649     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12650     if (!LHSOK && !Info.noteFailure())
12651       return false;
12652     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12653       return false;
12654     if (LHS < RHS)
12655       return Success(CmpResult::Less, E);
12656     if (LHS > RHS)
12657       return Success(CmpResult::Greater, E);
12658     return Success(CmpResult::Equal, E);
12659   }
12660 
12661   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12662     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12663     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12664 
12665     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12666     if (!LHSOK && !Info.noteFailure())
12667       return false;
12668     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12669       return false;
12670     if (LHSFX < RHSFX)
12671       return Success(CmpResult::Less, E);
12672     if (LHSFX > RHSFX)
12673       return Success(CmpResult::Greater, E);
12674     return Success(CmpResult::Equal, E);
12675   }
12676 
12677   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12678     ComplexValue LHS, RHS;
12679     bool LHSOK;
12680     if (E->isAssignmentOp()) {
12681       LValue LV;
12682       EvaluateLValue(E->getLHS(), LV, Info);
12683       LHSOK = false;
12684     } else if (LHSTy->isRealFloatingType()) {
12685       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12686       if (LHSOK) {
12687         LHS.makeComplexFloat();
12688         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12689       }
12690     } else {
12691       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12692     }
12693     if (!LHSOK && !Info.noteFailure())
12694       return false;
12695 
12696     if (E->getRHS()->getType()->isRealFloatingType()) {
12697       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12698         return false;
12699       RHS.makeComplexFloat();
12700       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12701     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12702       return false;
12703 
12704     if (LHS.isComplexFloat()) {
12705       APFloat::cmpResult CR_r =
12706         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12707       APFloat::cmpResult CR_i =
12708         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12709       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12710       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12711     } else {
12712       assert(IsEquality && "invalid complex comparison");
12713       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12714                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12715       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12716     }
12717   }
12718 
12719   if (LHSTy->isRealFloatingType() &&
12720       RHSTy->isRealFloatingType()) {
12721     APFloat RHS(0.0), LHS(0.0);
12722 
12723     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12724     if (!LHSOK && !Info.noteFailure())
12725       return false;
12726 
12727     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12728       return false;
12729 
12730     assert(E->isComparisonOp() && "Invalid binary operator!");
12731     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12732     if (!Info.InConstantContext &&
12733         APFloatCmpResult == APFloat::cmpUnordered &&
12734         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12735       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12736       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12737       return false;
12738     }
12739     auto GetCmpRes = [&]() {
12740       switch (APFloatCmpResult) {
12741       case APFloat::cmpEqual:
12742         return CmpResult::Equal;
12743       case APFloat::cmpLessThan:
12744         return CmpResult::Less;
12745       case APFloat::cmpGreaterThan:
12746         return CmpResult::Greater;
12747       case APFloat::cmpUnordered:
12748         return CmpResult::Unordered;
12749       }
12750       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12751     };
12752     return Success(GetCmpRes(), E);
12753   }
12754 
12755   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12756     LValue LHSValue, RHSValue;
12757 
12758     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12759     if (!LHSOK && !Info.noteFailure())
12760       return false;
12761 
12762     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12763       return false;
12764 
12765     // Reject differing bases from the normal codepath; we special-case
12766     // comparisons to null.
12767     if (!HasSameBase(LHSValue, RHSValue)) {
12768       // Inequalities and subtractions between unrelated pointers have
12769       // unspecified or undefined behavior.
12770       if (!IsEquality) {
12771         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12772         return false;
12773       }
12774       // A constant address may compare equal to the address of a symbol.
12775       // The one exception is that address of an object cannot compare equal
12776       // to a null pointer constant.
12777       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12778           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12779         return Error(E);
12780       // It's implementation-defined whether distinct literals will have
12781       // distinct addresses. In clang, the result of such a comparison is
12782       // unspecified, so it is not a constant expression. However, we do know
12783       // that the address of a literal will be non-null.
12784       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12785           LHSValue.Base && RHSValue.Base)
12786         return Error(E);
12787       // We can't tell whether weak symbols will end up pointing to the same
12788       // object.
12789       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12790         return Error(E);
12791       // We can't compare the address of the start of one object with the
12792       // past-the-end address of another object, per C++ DR1652.
12793       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12794            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12795           (RHSValue.Base && RHSValue.Offset.isZero() &&
12796            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12797         return Error(E);
12798       // We can't tell whether an object is at the same address as another
12799       // zero sized object.
12800       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12801           (LHSValue.Base && isZeroSized(RHSValue)))
12802         return Error(E);
12803       return Success(CmpResult::Unequal, E);
12804     }
12805 
12806     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12807     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12808 
12809     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12810     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12811 
12812     // C++11 [expr.rel]p3:
12813     //   Pointers to void (after pointer conversions) can be compared, with a
12814     //   result defined as follows: If both pointers represent the same
12815     //   address or are both the null pointer value, the result is true if the
12816     //   operator is <= or >= and false otherwise; otherwise the result is
12817     //   unspecified.
12818     // We interpret this as applying to pointers to *cv* void.
12819     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12820       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12821 
12822     // C++11 [expr.rel]p2:
12823     // - If two pointers point to non-static data members of the same object,
12824     //   or to subobjects or array elements fo such members, recursively, the
12825     //   pointer to the later declared member compares greater provided the
12826     //   two members have the same access control and provided their class is
12827     //   not a union.
12828     //   [...]
12829     // - Otherwise pointer comparisons are unspecified.
12830     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12831       bool WasArrayIndex;
12832       unsigned Mismatch = FindDesignatorMismatch(
12833           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12834       // At the point where the designators diverge, the comparison has a
12835       // specified value if:
12836       //  - we are comparing array indices
12837       //  - we are comparing fields of a union, or fields with the same access
12838       // Otherwise, the result is unspecified and thus the comparison is not a
12839       // constant expression.
12840       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12841           Mismatch < RHSDesignator.Entries.size()) {
12842         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12843         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12844         if (!LF && !RF)
12845           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12846         else if (!LF)
12847           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12848               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12849               << RF->getParent() << RF;
12850         else if (!RF)
12851           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12852               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12853               << LF->getParent() << LF;
12854         else if (!LF->getParent()->isUnion() &&
12855                  LF->getAccess() != RF->getAccess())
12856           Info.CCEDiag(E,
12857                        diag::note_constexpr_pointer_comparison_differing_access)
12858               << LF << LF->getAccess() << RF << RF->getAccess()
12859               << LF->getParent();
12860       }
12861     }
12862 
12863     // The comparison here must be unsigned, and performed with the same
12864     // width as the pointer.
12865     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12866     uint64_t CompareLHS = LHSOffset.getQuantity();
12867     uint64_t CompareRHS = RHSOffset.getQuantity();
12868     assert(PtrSize <= 64 && "Unexpected pointer width");
12869     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12870     CompareLHS &= Mask;
12871     CompareRHS &= Mask;
12872 
12873     // If there is a base and this is a relational operator, we can only
12874     // compare pointers within the object in question; otherwise, the result
12875     // depends on where the object is located in memory.
12876     if (!LHSValue.Base.isNull() && IsRelational) {
12877       QualType BaseTy = getType(LHSValue.Base);
12878       if (BaseTy->isIncompleteType())
12879         return Error(E);
12880       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12881       uint64_t OffsetLimit = Size.getQuantity();
12882       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12883         return Error(E);
12884     }
12885 
12886     if (CompareLHS < CompareRHS)
12887       return Success(CmpResult::Less, E);
12888     if (CompareLHS > CompareRHS)
12889       return Success(CmpResult::Greater, E);
12890     return Success(CmpResult::Equal, E);
12891   }
12892 
12893   if (LHSTy->isMemberPointerType()) {
12894     assert(IsEquality && "unexpected member pointer operation");
12895     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12896 
12897     MemberPtr LHSValue, RHSValue;
12898 
12899     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12900     if (!LHSOK && !Info.noteFailure())
12901       return false;
12902 
12903     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12904       return false;
12905 
12906     // C++11 [expr.eq]p2:
12907     //   If both operands are null, they compare equal. Otherwise if only one is
12908     //   null, they compare unequal.
12909     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12910       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12911       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12912     }
12913 
12914     //   Otherwise if either is a pointer to a virtual member function, the
12915     //   result is unspecified.
12916     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12917       if (MD->isVirtual())
12918         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12919     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12920       if (MD->isVirtual())
12921         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12922 
12923     //   Otherwise they compare equal if and only if they would refer to the
12924     //   same member of the same most derived object or the same subobject if
12925     //   they were dereferenced with a hypothetical object of the associated
12926     //   class type.
12927     bool Equal = LHSValue == RHSValue;
12928     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12929   }
12930 
12931   if (LHSTy->isNullPtrType()) {
12932     assert(E->isComparisonOp() && "unexpected nullptr operation");
12933     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12934     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12935     // are compared, the result is true of the operator is <=, >= or ==, and
12936     // false otherwise.
12937     return Success(CmpResult::Equal, E);
12938   }
12939 
12940   return DoAfter();
12941 }
12942 
12943 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12944   if (!CheckLiteralType(Info, E))
12945     return false;
12946 
12947   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12948     ComparisonCategoryResult CCR;
12949     switch (CR) {
12950     case CmpResult::Unequal:
12951       llvm_unreachable("should never produce Unequal for three-way comparison");
12952     case CmpResult::Less:
12953       CCR = ComparisonCategoryResult::Less;
12954       break;
12955     case CmpResult::Equal:
12956       CCR = ComparisonCategoryResult::Equal;
12957       break;
12958     case CmpResult::Greater:
12959       CCR = ComparisonCategoryResult::Greater;
12960       break;
12961     case CmpResult::Unordered:
12962       CCR = ComparisonCategoryResult::Unordered;
12963       break;
12964     }
12965     // Evaluation succeeded. Lookup the information for the comparison category
12966     // type and fetch the VarDecl for the result.
12967     const ComparisonCategoryInfo &CmpInfo =
12968         Info.Ctx.CompCategories.getInfoForType(E->getType());
12969     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12970     // Check and evaluate the result as a constant expression.
12971     LValue LV;
12972     LV.set(VD);
12973     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12974       return false;
12975     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
12976                                    ConstantExprKind::Normal);
12977   };
12978   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12979     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12980   });
12981 }
12982 
12983 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12984   // We don't support assignment in C. C++ assignments don't get here because
12985   // assignment is an lvalue in C++.
12986   if (E->isAssignmentOp()) {
12987     Error(E);
12988     if (!Info.noteFailure())
12989       return false;
12990   }
12991 
12992   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12993     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12994 
12995   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12996           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12997          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12998 
12999   if (E->isComparisonOp()) {
13000     // Evaluate builtin binary comparisons by evaluating them as three-way
13001     // comparisons and then translating the result.
13002     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13003       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
13004              "should only produce Unequal for equality comparisons");
13005       bool IsEqual   = CR == CmpResult::Equal,
13006            IsLess    = CR == CmpResult::Less,
13007            IsGreater = CR == CmpResult::Greater;
13008       auto Op = E->getOpcode();
13009       switch (Op) {
13010       default:
13011         llvm_unreachable("unsupported binary operator");
13012       case BO_EQ:
13013       case BO_NE:
13014         return Success(IsEqual == (Op == BO_EQ), E);
13015       case BO_LT:
13016         return Success(IsLess, E);
13017       case BO_GT:
13018         return Success(IsGreater, E);
13019       case BO_LE:
13020         return Success(IsEqual || IsLess, E);
13021       case BO_GE:
13022         return Success(IsEqual || IsGreater, E);
13023       }
13024     };
13025     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13026       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13027     });
13028   }
13029 
13030   QualType LHSTy = E->getLHS()->getType();
13031   QualType RHSTy = E->getRHS()->getType();
13032 
13033   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13034       E->getOpcode() == BO_Sub) {
13035     LValue LHSValue, RHSValue;
13036 
13037     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13038     if (!LHSOK && !Info.noteFailure())
13039       return false;
13040 
13041     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13042       return false;
13043 
13044     // Reject differing bases from the normal codepath; we special-case
13045     // comparisons to null.
13046     if (!HasSameBase(LHSValue, RHSValue)) {
13047       // Handle &&A - &&B.
13048       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13049         return Error(E);
13050       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13051       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13052       if (!LHSExpr || !RHSExpr)
13053         return Error(E);
13054       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13055       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13056       if (!LHSAddrExpr || !RHSAddrExpr)
13057         return Error(E);
13058       // Make sure both labels come from the same function.
13059       if (LHSAddrExpr->getLabel()->getDeclContext() !=
13060           RHSAddrExpr->getLabel()->getDeclContext())
13061         return Error(E);
13062       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13063     }
13064     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13065     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13066 
13067     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13068     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13069 
13070     // C++11 [expr.add]p6:
13071     //   Unless both pointers point to elements of the same array object, or
13072     //   one past the last element of the array object, the behavior is
13073     //   undefined.
13074     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13075         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13076                                 RHSDesignator))
13077       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13078 
13079     QualType Type = E->getLHS()->getType();
13080     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13081 
13082     CharUnits ElementSize;
13083     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13084       return false;
13085 
13086     // As an extension, a type may have zero size (empty struct or union in
13087     // C, array of zero length). Pointer subtraction in such cases has
13088     // undefined behavior, so is not constant.
13089     if (ElementSize.isZero()) {
13090       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13091           << ElementType;
13092       return false;
13093     }
13094 
13095     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13096     // and produce incorrect results when it overflows. Such behavior
13097     // appears to be non-conforming, but is common, so perhaps we should
13098     // assume the standard intended for such cases to be undefined behavior
13099     // and check for them.
13100 
13101     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13102     // overflow in the final conversion to ptrdiff_t.
13103     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13104     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13105     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13106                     false);
13107     APSInt TrueResult = (LHS - RHS) / ElemSize;
13108     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13109 
13110     if (Result.extend(65) != TrueResult &&
13111         !HandleOverflow(Info, E, TrueResult, E->getType()))
13112       return false;
13113     return Success(Result, E);
13114   }
13115 
13116   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13117 }
13118 
13119 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13120 /// a result as the expression's type.
13121 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13122                                     const UnaryExprOrTypeTraitExpr *E) {
13123   switch(E->getKind()) {
13124   case UETT_PreferredAlignOf:
13125   case UETT_AlignOf: {
13126     if (E->isArgumentType())
13127       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13128                      E);
13129     else
13130       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13131                      E);
13132   }
13133 
13134   case UETT_VecStep: {
13135     QualType Ty = E->getTypeOfArgument();
13136 
13137     if (Ty->isVectorType()) {
13138       unsigned n = Ty->castAs<VectorType>()->getNumElements();
13139 
13140       // The vec_step built-in functions that take a 3-component
13141       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13142       if (n == 3)
13143         n = 4;
13144 
13145       return Success(n, E);
13146     } else
13147       return Success(1, E);
13148   }
13149 
13150   case UETT_SizeOf: {
13151     QualType SrcTy = E->getTypeOfArgument();
13152     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13153     //   the result is the size of the referenced type."
13154     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13155       SrcTy = Ref->getPointeeType();
13156 
13157     CharUnits Sizeof;
13158     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13159       return false;
13160     return Success(Sizeof, E);
13161   }
13162   case UETT_OpenMPRequiredSimdAlign:
13163     assert(E->isArgumentType());
13164     return Success(
13165         Info.Ctx.toCharUnitsFromBits(
13166                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13167             .getQuantity(),
13168         E);
13169   }
13170 
13171   llvm_unreachable("unknown expr/type trait");
13172 }
13173 
13174 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13175   CharUnits Result;
13176   unsigned n = OOE->getNumComponents();
13177   if (n == 0)
13178     return Error(OOE);
13179   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13180   for (unsigned i = 0; i != n; ++i) {
13181     OffsetOfNode ON = OOE->getComponent(i);
13182     switch (ON.getKind()) {
13183     case OffsetOfNode::Array: {
13184       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13185       APSInt IdxResult;
13186       if (!EvaluateInteger(Idx, IdxResult, Info))
13187         return false;
13188       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13189       if (!AT)
13190         return Error(OOE);
13191       CurrentType = AT->getElementType();
13192       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13193       Result += IdxResult.getSExtValue() * ElementSize;
13194       break;
13195     }
13196 
13197     case OffsetOfNode::Field: {
13198       FieldDecl *MemberDecl = ON.getField();
13199       const RecordType *RT = CurrentType->getAs<RecordType>();
13200       if (!RT)
13201         return Error(OOE);
13202       RecordDecl *RD = RT->getDecl();
13203       if (RD->isInvalidDecl()) return false;
13204       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13205       unsigned i = MemberDecl->getFieldIndex();
13206       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13207       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13208       CurrentType = MemberDecl->getType().getNonReferenceType();
13209       break;
13210     }
13211 
13212     case OffsetOfNode::Identifier:
13213       llvm_unreachable("dependent __builtin_offsetof");
13214 
13215     case OffsetOfNode::Base: {
13216       CXXBaseSpecifier *BaseSpec = ON.getBase();
13217       if (BaseSpec->isVirtual())
13218         return Error(OOE);
13219 
13220       // Find the layout of the class whose base we are looking into.
13221       const RecordType *RT = CurrentType->getAs<RecordType>();
13222       if (!RT)
13223         return Error(OOE);
13224       RecordDecl *RD = RT->getDecl();
13225       if (RD->isInvalidDecl()) return false;
13226       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13227 
13228       // Find the base class itself.
13229       CurrentType = BaseSpec->getType();
13230       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13231       if (!BaseRT)
13232         return Error(OOE);
13233 
13234       // Add the offset to the base.
13235       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13236       break;
13237     }
13238     }
13239   }
13240   return Success(Result, OOE);
13241 }
13242 
13243 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13244   switch (E->getOpcode()) {
13245   default:
13246     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13247     // See C99 6.6p3.
13248     return Error(E);
13249   case UO_Extension:
13250     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13251     // If so, we could clear the diagnostic ID.
13252     return Visit(E->getSubExpr());
13253   case UO_Plus:
13254     // The result is just the value.
13255     return Visit(E->getSubExpr());
13256   case UO_Minus: {
13257     if (!Visit(E->getSubExpr()))
13258       return false;
13259     if (!Result.isInt()) return Error(E);
13260     const APSInt &Value = Result.getInt();
13261     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13262         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13263                         E->getType()))
13264       return false;
13265     return Success(-Value, E);
13266   }
13267   case UO_Not: {
13268     if (!Visit(E->getSubExpr()))
13269       return false;
13270     if (!Result.isInt()) return Error(E);
13271     return Success(~Result.getInt(), E);
13272   }
13273   case UO_LNot: {
13274     bool bres;
13275     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13276       return false;
13277     return Success(!bres, E);
13278   }
13279   }
13280 }
13281 
13282 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13283 /// result type is integer.
13284 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13285   const Expr *SubExpr = E->getSubExpr();
13286   QualType DestType = E->getType();
13287   QualType SrcType = SubExpr->getType();
13288 
13289   switch (E->getCastKind()) {
13290   case CK_BaseToDerived:
13291   case CK_DerivedToBase:
13292   case CK_UncheckedDerivedToBase:
13293   case CK_Dynamic:
13294   case CK_ToUnion:
13295   case CK_ArrayToPointerDecay:
13296   case CK_FunctionToPointerDecay:
13297   case CK_NullToPointer:
13298   case CK_NullToMemberPointer:
13299   case CK_BaseToDerivedMemberPointer:
13300   case CK_DerivedToBaseMemberPointer:
13301   case CK_ReinterpretMemberPointer:
13302   case CK_ConstructorConversion:
13303   case CK_IntegralToPointer:
13304   case CK_ToVoid:
13305   case CK_VectorSplat:
13306   case CK_IntegralToFloating:
13307   case CK_FloatingCast:
13308   case CK_CPointerToObjCPointerCast:
13309   case CK_BlockPointerToObjCPointerCast:
13310   case CK_AnyPointerToBlockPointerCast:
13311   case CK_ObjCObjectLValueCast:
13312   case CK_FloatingRealToComplex:
13313   case CK_FloatingComplexToReal:
13314   case CK_FloatingComplexCast:
13315   case CK_FloatingComplexToIntegralComplex:
13316   case CK_IntegralRealToComplex:
13317   case CK_IntegralComplexCast:
13318   case CK_IntegralComplexToFloatingComplex:
13319   case CK_BuiltinFnToFnPtr:
13320   case CK_ZeroToOCLOpaqueType:
13321   case CK_NonAtomicToAtomic:
13322   case CK_AddressSpaceConversion:
13323   case CK_IntToOCLSampler:
13324   case CK_FloatingToFixedPoint:
13325   case CK_FixedPointToFloating:
13326   case CK_FixedPointCast:
13327   case CK_IntegralToFixedPoint:
13328   case CK_MatrixCast:
13329     llvm_unreachable("invalid cast kind for integral value");
13330 
13331   case CK_BitCast:
13332   case CK_Dependent:
13333   case CK_LValueBitCast:
13334   case CK_ARCProduceObject:
13335   case CK_ARCConsumeObject:
13336   case CK_ARCReclaimReturnedObject:
13337   case CK_ARCExtendBlockObject:
13338   case CK_CopyAndAutoreleaseBlockObject:
13339     return Error(E);
13340 
13341   case CK_UserDefinedConversion:
13342   case CK_LValueToRValue:
13343   case CK_AtomicToNonAtomic:
13344   case CK_NoOp:
13345   case CK_LValueToRValueBitCast:
13346     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13347 
13348   case CK_MemberPointerToBoolean:
13349   case CK_PointerToBoolean:
13350   case CK_IntegralToBoolean:
13351   case CK_FloatingToBoolean:
13352   case CK_BooleanToSignedIntegral:
13353   case CK_FloatingComplexToBoolean:
13354   case CK_IntegralComplexToBoolean: {
13355     bool BoolResult;
13356     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13357       return false;
13358     uint64_t IntResult = BoolResult;
13359     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13360       IntResult = (uint64_t)-1;
13361     return Success(IntResult, E);
13362   }
13363 
13364   case CK_FixedPointToIntegral: {
13365     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13366     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13367       return false;
13368     bool Overflowed;
13369     llvm::APSInt Result = Src.convertToInt(
13370         Info.Ctx.getIntWidth(DestType),
13371         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13372     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13373       return false;
13374     return Success(Result, E);
13375   }
13376 
13377   case CK_FixedPointToBoolean: {
13378     // Unsigned padding does not affect this.
13379     APValue Val;
13380     if (!Evaluate(Val, Info, SubExpr))
13381       return false;
13382     return Success(Val.getFixedPoint().getBoolValue(), E);
13383   }
13384 
13385   case CK_IntegralCast: {
13386     if (!Visit(SubExpr))
13387       return false;
13388 
13389     if (!Result.isInt()) {
13390       // Allow casts of address-of-label differences if they are no-ops
13391       // or narrowing.  (The narrowing case isn't actually guaranteed to
13392       // be constant-evaluatable except in some narrow cases which are hard
13393       // to detect here.  We let it through on the assumption the user knows
13394       // what they are doing.)
13395       if (Result.isAddrLabelDiff())
13396         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13397       // Only allow casts of lvalues if they are lossless.
13398       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13399     }
13400 
13401     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13402                                       Result.getInt()), E);
13403   }
13404 
13405   case CK_PointerToIntegral: {
13406     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13407 
13408     LValue LV;
13409     if (!EvaluatePointer(SubExpr, LV, Info))
13410       return false;
13411 
13412     if (LV.getLValueBase()) {
13413       // Only allow based lvalue casts if they are lossless.
13414       // FIXME: Allow a larger integer size than the pointer size, and allow
13415       // narrowing back down to pointer width in subsequent integral casts.
13416       // FIXME: Check integer type's active bits, not its type size.
13417       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13418         return Error(E);
13419 
13420       LV.Designator.setInvalid();
13421       LV.moveInto(Result);
13422       return true;
13423     }
13424 
13425     APSInt AsInt;
13426     APValue V;
13427     LV.moveInto(V);
13428     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13429       llvm_unreachable("Can't cast this!");
13430 
13431     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13432   }
13433 
13434   case CK_IntegralComplexToReal: {
13435     ComplexValue C;
13436     if (!EvaluateComplex(SubExpr, C, Info))
13437       return false;
13438     return Success(C.getComplexIntReal(), E);
13439   }
13440 
13441   case CK_FloatingToIntegral: {
13442     APFloat F(0.0);
13443     if (!EvaluateFloat(SubExpr, F, Info))
13444       return false;
13445 
13446     APSInt Value;
13447     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13448       return false;
13449     return Success(Value, E);
13450   }
13451   }
13452 
13453   llvm_unreachable("unknown cast resulting in integral value");
13454 }
13455 
13456 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13457   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13458     ComplexValue LV;
13459     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13460       return false;
13461     if (!LV.isComplexInt())
13462       return Error(E);
13463     return Success(LV.getComplexIntReal(), E);
13464   }
13465 
13466   return Visit(E->getSubExpr());
13467 }
13468 
13469 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13470   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13471     ComplexValue LV;
13472     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13473       return false;
13474     if (!LV.isComplexInt())
13475       return Error(E);
13476     return Success(LV.getComplexIntImag(), E);
13477   }
13478 
13479   VisitIgnoredValue(E->getSubExpr());
13480   return Success(0, E);
13481 }
13482 
13483 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13484   return Success(E->getPackLength(), E);
13485 }
13486 
13487 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13488   return Success(E->getValue(), E);
13489 }
13490 
13491 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13492        const ConceptSpecializationExpr *E) {
13493   return Success(E->isSatisfied(), E);
13494 }
13495 
13496 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13497   return Success(E->isSatisfied(), E);
13498 }
13499 
13500 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13501   switch (E->getOpcode()) {
13502     default:
13503       // Invalid unary operators
13504       return Error(E);
13505     case UO_Plus:
13506       // The result is just the value.
13507       return Visit(E->getSubExpr());
13508     case UO_Minus: {
13509       if (!Visit(E->getSubExpr())) return false;
13510       if (!Result.isFixedPoint())
13511         return Error(E);
13512       bool Overflowed;
13513       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13514       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13515         return false;
13516       return Success(Negated, E);
13517     }
13518     case UO_LNot: {
13519       bool bres;
13520       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13521         return false;
13522       return Success(!bres, E);
13523     }
13524   }
13525 }
13526 
13527 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13528   const Expr *SubExpr = E->getSubExpr();
13529   QualType DestType = E->getType();
13530   assert(DestType->isFixedPointType() &&
13531          "Expected destination type to be a fixed point type");
13532   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13533 
13534   switch (E->getCastKind()) {
13535   case CK_FixedPointCast: {
13536     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13537     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13538       return false;
13539     bool Overflowed;
13540     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13541     if (Overflowed) {
13542       if (Info.checkingForUndefinedBehavior())
13543         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13544                                          diag::warn_fixedpoint_constant_overflow)
13545           << Result.toString() << E->getType();
13546       if (!HandleOverflow(Info, E, Result, E->getType()))
13547         return false;
13548     }
13549     return Success(Result, E);
13550   }
13551   case CK_IntegralToFixedPoint: {
13552     APSInt Src;
13553     if (!EvaluateInteger(SubExpr, Src, Info))
13554       return false;
13555 
13556     bool Overflowed;
13557     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13558         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13559 
13560     if (Overflowed) {
13561       if (Info.checkingForUndefinedBehavior())
13562         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13563                                          diag::warn_fixedpoint_constant_overflow)
13564           << IntResult.toString() << E->getType();
13565       if (!HandleOverflow(Info, E, IntResult, E->getType()))
13566         return false;
13567     }
13568 
13569     return Success(IntResult, E);
13570   }
13571   case CK_FloatingToFixedPoint: {
13572     APFloat Src(0.0);
13573     if (!EvaluateFloat(SubExpr, Src, Info))
13574       return false;
13575 
13576     bool Overflowed;
13577     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13578         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13579 
13580     if (Overflowed) {
13581       if (Info.checkingForUndefinedBehavior())
13582         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13583                                          diag::warn_fixedpoint_constant_overflow)
13584           << Result.toString() << E->getType();
13585       if (!HandleOverflow(Info, E, Result, E->getType()))
13586         return false;
13587     }
13588 
13589     return Success(Result, E);
13590   }
13591   case CK_NoOp:
13592   case CK_LValueToRValue:
13593     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13594   default:
13595     return Error(E);
13596   }
13597 }
13598 
13599 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13600   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13601     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13602 
13603   const Expr *LHS = E->getLHS();
13604   const Expr *RHS = E->getRHS();
13605   FixedPointSemantics ResultFXSema =
13606       Info.Ctx.getFixedPointSemantics(E->getType());
13607 
13608   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13609   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13610     return false;
13611   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13612   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13613     return false;
13614 
13615   bool OpOverflow = false, ConversionOverflow = false;
13616   APFixedPoint Result(LHSFX.getSemantics());
13617   switch (E->getOpcode()) {
13618   case BO_Add: {
13619     Result = LHSFX.add(RHSFX, &OpOverflow)
13620                   .convert(ResultFXSema, &ConversionOverflow);
13621     break;
13622   }
13623   case BO_Sub: {
13624     Result = LHSFX.sub(RHSFX, &OpOverflow)
13625                   .convert(ResultFXSema, &ConversionOverflow);
13626     break;
13627   }
13628   case BO_Mul: {
13629     Result = LHSFX.mul(RHSFX, &OpOverflow)
13630                   .convert(ResultFXSema, &ConversionOverflow);
13631     break;
13632   }
13633   case BO_Div: {
13634     if (RHSFX.getValue() == 0) {
13635       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13636       return false;
13637     }
13638     Result = LHSFX.div(RHSFX, &OpOverflow)
13639                   .convert(ResultFXSema, &ConversionOverflow);
13640     break;
13641   }
13642   case BO_Shl:
13643   case BO_Shr: {
13644     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13645     llvm::APSInt RHSVal = RHSFX.getValue();
13646 
13647     unsigned ShiftBW =
13648         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13649     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13650     // Embedded-C 4.1.6.2.2:
13651     //   The right operand must be nonnegative and less than the total number
13652     //   of (nonpadding) bits of the fixed-point operand ...
13653     if (RHSVal.isNegative())
13654       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13655     else if (Amt != RHSVal)
13656       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13657           << RHSVal << E->getType() << ShiftBW;
13658 
13659     if (E->getOpcode() == BO_Shl)
13660       Result = LHSFX.shl(Amt, &OpOverflow);
13661     else
13662       Result = LHSFX.shr(Amt, &OpOverflow);
13663     break;
13664   }
13665   default:
13666     return false;
13667   }
13668   if (OpOverflow || ConversionOverflow) {
13669     if (Info.checkingForUndefinedBehavior())
13670       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13671                                        diag::warn_fixedpoint_constant_overflow)
13672         << Result.toString() << E->getType();
13673     if (!HandleOverflow(Info, E, Result, E->getType()))
13674       return false;
13675   }
13676   return Success(Result, E);
13677 }
13678 
13679 //===----------------------------------------------------------------------===//
13680 // Float Evaluation
13681 //===----------------------------------------------------------------------===//
13682 
13683 namespace {
13684 class FloatExprEvaluator
13685   : public ExprEvaluatorBase<FloatExprEvaluator> {
13686   APFloat &Result;
13687 public:
13688   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13689     : ExprEvaluatorBaseTy(info), Result(result) {}
13690 
13691   bool Success(const APValue &V, const Expr *e) {
13692     Result = V.getFloat();
13693     return true;
13694   }
13695 
13696   bool ZeroInitialization(const Expr *E) {
13697     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13698     return true;
13699   }
13700 
13701   bool VisitCallExpr(const CallExpr *E);
13702 
13703   bool VisitUnaryOperator(const UnaryOperator *E);
13704   bool VisitBinaryOperator(const BinaryOperator *E);
13705   bool VisitFloatingLiteral(const FloatingLiteral *E);
13706   bool VisitCastExpr(const CastExpr *E);
13707 
13708   bool VisitUnaryReal(const UnaryOperator *E);
13709   bool VisitUnaryImag(const UnaryOperator *E);
13710 
13711   // FIXME: Missing: array subscript of vector, member of vector
13712 };
13713 } // end anonymous namespace
13714 
13715 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13716   assert(!E->isValueDependent());
13717   assert(E->isPRValue() && E->getType()->isRealFloatingType());
13718   return FloatExprEvaluator(Info, Result).Visit(E);
13719 }
13720 
13721 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13722                                   QualType ResultTy,
13723                                   const Expr *Arg,
13724                                   bool SNaN,
13725                                   llvm::APFloat &Result) {
13726   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13727   if (!S) return false;
13728 
13729   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13730 
13731   llvm::APInt fill;
13732 
13733   // Treat empty strings as if they were zero.
13734   if (S->getString().empty())
13735     fill = llvm::APInt(32, 0);
13736   else if (S->getString().getAsInteger(0, fill))
13737     return false;
13738 
13739   if (Context.getTargetInfo().isNan2008()) {
13740     if (SNaN)
13741       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13742     else
13743       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13744   } else {
13745     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13746     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13747     // a different encoding to what became a standard in 2008, and for pre-
13748     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13749     // sNaN. This is now known as "legacy NaN" encoding.
13750     if (SNaN)
13751       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13752     else
13753       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13754   }
13755 
13756   return true;
13757 }
13758 
13759 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13760   switch (E->getBuiltinCallee()) {
13761   default:
13762     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13763 
13764   case Builtin::BI__builtin_huge_val:
13765   case Builtin::BI__builtin_huge_valf:
13766   case Builtin::BI__builtin_huge_vall:
13767   case Builtin::BI__builtin_huge_valf128:
13768   case Builtin::BI__builtin_inf:
13769   case Builtin::BI__builtin_inff:
13770   case Builtin::BI__builtin_infl:
13771   case Builtin::BI__builtin_inff128: {
13772     const llvm::fltSemantics &Sem =
13773       Info.Ctx.getFloatTypeSemantics(E->getType());
13774     Result = llvm::APFloat::getInf(Sem);
13775     return true;
13776   }
13777 
13778   case Builtin::BI__builtin_nans:
13779   case Builtin::BI__builtin_nansf:
13780   case Builtin::BI__builtin_nansl:
13781   case Builtin::BI__builtin_nansf128:
13782     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13783                                true, Result))
13784       return Error(E);
13785     return true;
13786 
13787   case Builtin::BI__builtin_nan:
13788   case Builtin::BI__builtin_nanf:
13789   case Builtin::BI__builtin_nanl:
13790   case Builtin::BI__builtin_nanf128:
13791     // If this is __builtin_nan() turn this into a nan, otherwise we
13792     // can't constant fold it.
13793     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13794                                false, Result))
13795       return Error(E);
13796     return true;
13797 
13798   case Builtin::BI__builtin_fabs:
13799   case Builtin::BI__builtin_fabsf:
13800   case Builtin::BI__builtin_fabsl:
13801   case Builtin::BI__builtin_fabsf128:
13802     // The C standard says "fabs raises no floating-point exceptions,
13803     // even if x is a signaling NaN. The returned value is independent of
13804     // the current rounding direction mode."  Therefore constant folding can
13805     // proceed without regard to the floating point settings.
13806     // Reference, WG14 N2478 F.10.4.3
13807     if (!EvaluateFloat(E->getArg(0), Result, Info))
13808       return false;
13809 
13810     if (Result.isNegative())
13811       Result.changeSign();
13812     return true;
13813 
13814   case Builtin::BI__arithmetic_fence:
13815     return EvaluateFloat(E->getArg(0), Result, Info);
13816 
13817   // FIXME: Builtin::BI__builtin_powi
13818   // FIXME: Builtin::BI__builtin_powif
13819   // FIXME: Builtin::BI__builtin_powil
13820 
13821   case Builtin::BI__builtin_copysign:
13822   case Builtin::BI__builtin_copysignf:
13823   case Builtin::BI__builtin_copysignl:
13824   case Builtin::BI__builtin_copysignf128: {
13825     APFloat RHS(0.);
13826     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13827         !EvaluateFloat(E->getArg(1), RHS, Info))
13828       return false;
13829     Result.copySign(RHS);
13830     return true;
13831   }
13832   }
13833 }
13834 
13835 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13836   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13837     ComplexValue CV;
13838     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13839       return false;
13840     Result = CV.FloatReal;
13841     return true;
13842   }
13843 
13844   return Visit(E->getSubExpr());
13845 }
13846 
13847 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13848   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13849     ComplexValue CV;
13850     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13851       return false;
13852     Result = CV.FloatImag;
13853     return true;
13854   }
13855 
13856   VisitIgnoredValue(E->getSubExpr());
13857   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13858   Result = llvm::APFloat::getZero(Sem);
13859   return true;
13860 }
13861 
13862 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13863   switch (E->getOpcode()) {
13864   default: return Error(E);
13865   case UO_Plus:
13866     return EvaluateFloat(E->getSubExpr(), Result, Info);
13867   case UO_Minus:
13868     // In C standard, WG14 N2478 F.3 p4
13869     // "the unary - raises no floating point exceptions,
13870     // even if the operand is signalling."
13871     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13872       return false;
13873     Result.changeSign();
13874     return true;
13875   }
13876 }
13877 
13878 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13879   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13880     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13881 
13882   APFloat RHS(0.0);
13883   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13884   if (!LHSOK && !Info.noteFailure())
13885     return false;
13886   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13887          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13888 }
13889 
13890 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13891   Result = E->getValue();
13892   return true;
13893 }
13894 
13895 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13896   const Expr* SubExpr = E->getSubExpr();
13897 
13898   switch (E->getCastKind()) {
13899   default:
13900     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13901 
13902   case CK_IntegralToFloating: {
13903     APSInt IntResult;
13904     const FPOptions FPO = E->getFPFeaturesInEffect(
13905                                   Info.Ctx.getLangOpts());
13906     return EvaluateInteger(SubExpr, IntResult, Info) &&
13907            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
13908                                 IntResult, E->getType(), Result);
13909   }
13910 
13911   case CK_FixedPointToFloating: {
13912     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13913     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
13914       return false;
13915     Result =
13916         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
13917     return true;
13918   }
13919 
13920   case CK_FloatingCast: {
13921     if (!Visit(SubExpr))
13922       return false;
13923     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13924                                   Result);
13925   }
13926 
13927   case CK_FloatingComplexToReal: {
13928     ComplexValue V;
13929     if (!EvaluateComplex(SubExpr, V, Info))
13930       return false;
13931     Result = V.getComplexFloatReal();
13932     return true;
13933   }
13934   }
13935 }
13936 
13937 //===----------------------------------------------------------------------===//
13938 // Complex Evaluation (for float and integer)
13939 //===----------------------------------------------------------------------===//
13940 
13941 namespace {
13942 class ComplexExprEvaluator
13943   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13944   ComplexValue &Result;
13945 
13946 public:
13947   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13948     : ExprEvaluatorBaseTy(info), Result(Result) {}
13949 
13950   bool Success(const APValue &V, const Expr *e) {
13951     Result.setFrom(V);
13952     return true;
13953   }
13954 
13955   bool ZeroInitialization(const Expr *E);
13956 
13957   //===--------------------------------------------------------------------===//
13958   //                            Visitor Methods
13959   //===--------------------------------------------------------------------===//
13960 
13961   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13962   bool VisitCastExpr(const CastExpr *E);
13963   bool VisitBinaryOperator(const BinaryOperator *E);
13964   bool VisitUnaryOperator(const UnaryOperator *E);
13965   bool VisitInitListExpr(const InitListExpr *E);
13966   bool VisitCallExpr(const CallExpr *E);
13967 };
13968 } // end anonymous namespace
13969 
13970 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13971                             EvalInfo &Info) {
13972   assert(!E->isValueDependent());
13973   assert(E->isPRValue() && E->getType()->isAnyComplexType());
13974   return ComplexExprEvaluator(Info, Result).Visit(E);
13975 }
13976 
13977 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13978   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13979   if (ElemTy->isRealFloatingType()) {
13980     Result.makeComplexFloat();
13981     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13982     Result.FloatReal = Zero;
13983     Result.FloatImag = Zero;
13984   } else {
13985     Result.makeComplexInt();
13986     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13987     Result.IntReal = Zero;
13988     Result.IntImag = Zero;
13989   }
13990   return true;
13991 }
13992 
13993 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13994   const Expr* SubExpr = E->getSubExpr();
13995 
13996   if (SubExpr->getType()->isRealFloatingType()) {
13997     Result.makeComplexFloat();
13998     APFloat &Imag = Result.FloatImag;
13999     if (!EvaluateFloat(SubExpr, Imag, Info))
14000       return false;
14001 
14002     Result.FloatReal = APFloat(Imag.getSemantics());
14003     return true;
14004   } else {
14005     assert(SubExpr->getType()->isIntegerType() &&
14006            "Unexpected imaginary literal.");
14007 
14008     Result.makeComplexInt();
14009     APSInt &Imag = Result.IntImag;
14010     if (!EvaluateInteger(SubExpr, Imag, Info))
14011       return false;
14012 
14013     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
14014     return true;
14015   }
14016 }
14017 
14018 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14019 
14020   switch (E->getCastKind()) {
14021   case CK_BitCast:
14022   case CK_BaseToDerived:
14023   case CK_DerivedToBase:
14024   case CK_UncheckedDerivedToBase:
14025   case CK_Dynamic:
14026   case CK_ToUnion:
14027   case CK_ArrayToPointerDecay:
14028   case CK_FunctionToPointerDecay:
14029   case CK_NullToPointer:
14030   case CK_NullToMemberPointer:
14031   case CK_BaseToDerivedMemberPointer:
14032   case CK_DerivedToBaseMemberPointer:
14033   case CK_MemberPointerToBoolean:
14034   case CK_ReinterpretMemberPointer:
14035   case CK_ConstructorConversion:
14036   case CK_IntegralToPointer:
14037   case CK_PointerToIntegral:
14038   case CK_PointerToBoolean:
14039   case CK_ToVoid:
14040   case CK_VectorSplat:
14041   case CK_IntegralCast:
14042   case CK_BooleanToSignedIntegral:
14043   case CK_IntegralToBoolean:
14044   case CK_IntegralToFloating:
14045   case CK_FloatingToIntegral:
14046   case CK_FloatingToBoolean:
14047   case CK_FloatingCast:
14048   case CK_CPointerToObjCPointerCast:
14049   case CK_BlockPointerToObjCPointerCast:
14050   case CK_AnyPointerToBlockPointerCast:
14051   case CK_ObjCObjectLValueCast:
14052   case CK_FloatingComplexToReal:
14053   case CK_FloatingComplexToBoolean:
14054   case CK_IntegralComplexToReal:
14055   case CK_IntegralComplexToBoolean:
14056   case CK_ARCProduceObject:
14057   case CK_ARCConsumeObject:
14058   case CK_ARCReclaimReturnedObject:
14059   case CK_ARCExtendBlockObject:
14060   case CK_CopyAndAutoreleaseBlockObject:
14061   case CK_BuiltinFnToFnPtr:
14062   case CK_ZeroToOCLOpaqueType:
14063   case CK_NonAtomicToAtomic:
14064   case CK_AddressSpaceConversion:
14065   case CK_IntToOCLSampler:
14066   case CK_FloatingToFixedPoint:
14067   case CK_FixedPointToFloating:
14068   case CK_FixedPointCast:
14069   case CK_FixedPointToBoolean:
14070   case CK_FixedPointToIntegral:
14071   case CK_IntegralToFixedPoint:
14072   case CK_MatrixCast:
14073     llvm_unreachable("invalid cast kind for complex value");
14074 
14075   case CK_LValueToRValue:
14076   case CK_AtomicToNonAtomic:
14077   case CK_NoOp:
14078   case CK_LValueToRValueBitCast:
14079     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14080 
14081   case CK_Dependent:
14082   case CK_LValueBitCast:
14083   case CK_UserDefinedConversion:
14084     return Error(E);
14085 
14086   case CK_FloatingRealToComplex: {
14087     APFloat &Real = Result.FloatReal;
14088     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14089       return false;
14090 
14091     Result.makeComplexFloat();
14092     Result.FloatImag = APFloat(Real.getSemantics());
14093     return true;
14094   }
14095 
14096   case CK_FloatingComplexCast: {
14097     if (!Visit(E->getSubExpr()))
14098       return false;
14099 
14100     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14101     QualType From
14102       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14103 
14104     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14105            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14106   }
14107 
14108   case CK_FloatingComplexToIntegralComplex: {
14109     if (!Visit(E->getSubExpr()))
14110       return false;
14111 
14112     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14113     QualType From
14114       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14115     Result.makeComplexInt();
14116     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14117                                 To, Result.IntReal) &&
14118            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14119                                 To, Result.IntImag);
14120   }
14121 
14122   case CK_IntegralRealToComplex: {
14123     APSInt &Real = Result.IntReal;
14124     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14125       return false;
14126 
14127     Result.makeComplexInt();
14128     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14129     return true;
14130   }
14131 
14132   case CK_IntegralComplexCast: {
14133     if (!Visit(E->getSubExpr()))
14134       return false;
14135 
14136     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14137     QualType From
14138       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14139 
14140     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14141     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14142     return true;
14143   }
14144 
14145   case CK_IntegralComplexToFloatingComplex: {
14146     if (!Visit(E->getSubExpr()))
14147       return false;
14148 
14149     const FPOptions FPO = E->getFPFeaturesInEffect(
14150                                   Info.Ctx.getLangOpts());
14151     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14152     QualType From
14153       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14154     Result.makeComplexFloat();
14155     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14156                                 To, Result.FloatReal) &&
14157            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14158                                 To, Result.FloatImag);
14159   }
14160   }
14161 
14162   llvm_unreachable("unknown cast resulting in complex value");
14163 }
14164 
14165 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14166   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14167     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14168 
14169   // Track whether the LHS or RHS is real at the type system level. When this is
14170   // the case we can simplify our evaluation strategy.
14171   bool LHSReal = false, RHSReal = false;
14172 
14173   bool LHSOK;
14174   if (E->getLHS()->getType()->isRealFloatingType()) {
14175     LHSReal = true;
14176     APFloat &Real = Result.FloatReal;
14177     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14178     if (LHSOK) {
14179       Result.makeComplexFloat();
14180       Result.FloatImag = APFloat(Real.getSemantics());
14181     }
14182   } else {
14183     LHSOK = Visit(E->getLHS());
14184   }
14185   if (!LHSOK && !Info.noteFailure())
14186     return false;
14187 
14188   ComplexValue RHS;
14189   if (E->getRHS()->getType()->isRealFloatingType()) {
14190     RHSReal = true;
14191     APFloat &Real = RHS.FloatReal;
14192     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14193       return false;
14194     RHS.makeComplexFloat();
14195     RHS.FloatImag = APFloat(Real.getSemantics());
14196   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14197     return false;
14198 
14199   assert(!(LHSReal && RHSReal) &&
14200          "Cannot have both operands of a complex operation be real.");
14201   switch (E->getOpcode()) {
14202   default: return Error(E);
14203   case BO_Add:
14204     if (Result.isComplexFloat()) {
14205       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14206                                        APFloat::rmNearestTiesToEven);
14207       if (LHSReal)
14208         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14209       else if (!RHSReal)
14210         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14211                                          APFloat::rmNearestTiesToEven);
14212     } else {
14213       Result.getComplexIntReal() += RHS.getComplexIntReal();
14214       Result.getComplexIntImag() += RHS.getComplexIntImag();
14215     }
14216     break;
14217   case BO_Sub:
14218     if (Result.isComplexFloat()) {
14219       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14220                                             APFloat::rmNearestTiesToEven);
14221       if (LHSReal) {
14222         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14223         Result.getComplexFloatImag().changeSign();
14224       } else if (!RHSReal) {
14225         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14226                                               APFloat::rmNearestTiesToEven);
14227       }
14228     } else {
14229       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14230       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14231     }
14232     break;
14233   case BO_Mul:
14234     if (Result.isComplexFloat()) {
14235       // This is an implementation of complex multiplication according to the
14236       // constraints laid out in C11 Annex G. The implementation uses the
14237       // following naming scheme:
14238       //   (a + ib) * (c + id)
14239       ComplexValue LHS = Result;
14240       APFloat &A = LHS.getComplexFloatReal();
14241       APFloat &B = LHS.getComplexFloatImag();
14242       APFloat &C = RHS.getComplexFloatReal();
14243       APFloat &D = RHS.getComplexFloatImag();
14244       APFloat &ResR = Result.getComplexFloatReal();
14245       APFloat &ResI = Result.getComplexFloatImag();
14246       if (LHSReal) {
14247         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14248         ResR = A * C;
14249         ResI = A * D;
14250       } else if (RHSReal) {
14251         ResR = C * A;
14252         ResI = C * B;
14253       } else {
14254         // In the fully general case, we need to handle NaNs and infinities
14255         // robustly.
14256         APFloat AC = A * C;
14257         APFloat BD = B * D;
14258         APFloat AD = A * D;
14259         APFloat BC = B * C;
14260         ResR = AC - BD;
14261         ResI = AD + BC;
14262         if (ResR.isNaN() && ResI.isNaN()) {
14263           bool Recalc = false;
14264           if (A.isInfinity() || B.isInfinity()) {
14265             A = APFloat::copySign(
14266                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14267             B = APFloat::copySign(
14268                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14269             if (C.isNaN())
14270               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14271             if (D.isNaN())
14272               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14273             Recalc = true;
14274           }
14275           if (C.isInfinity() || D.isInfinity()) {
14276             C = APFloat::copySign(
14277                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14278             D = APFloat::copySign(
14279                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14280             if (A.isNaN())
14281               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14282             if (B.isNaN())
14283               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14284             Recalc = true;
14285           }
14286           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14287                           AD.isInfinity() || BC.isInfinity())) {
14288             if (A.isNaN())
14289               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14290             if (B.isNaN())
14291               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14292             if (C.isNaN())
14293               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14294             if (D.isNaN())
14295               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14296             Recalc = true;
14297           }
14298           if (Recalc) {
14299             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14300             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14301           }
14302         }
14303       }
14304     } else {
14305       ComplexValue LHS = Result;
14306       Result.getComplexIntReal() =
14307         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14308          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14309       Result.getComplexIntImag() =
14310         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14311          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14312     }
14313     break;
14314   case BO_Div:
14315     if (Result.isComplexFloat()) {
14316       // This is an implementation of complex division according to the
14317       // constraints laid out in C11 Annex G. The implementation uses the
14318       // following naming scheme:
14319       //   (a + ib) / (c + id)
14320       ComplexValue LHS = Result;
14321       APFloat &A = LHS.getComplexFloatReal();
14322       APFloat &B = LHS.getComplexFloatImag();
14323       APFloat &C = RHS.getComplexFloatReal();
14324       APFloat &D = RHS.getComplexFloatImag();
14325       APFloat &ResR = Result.getComplexFloatReal();
14326       APFloat &ResI = Result.getComplexFloatImag();
14327       if (RHSReal) {
14328         ResR = A / C;
14329         ResI = B / C;
14330       } else {
14331         if (LHSReal) {
14332           // No real optimizations we can do here, stub out with zero.
14333           B = APFloat::getZero(A.getSemantics());
14334         }
14335         int DenomLogB = 0;
14336         APFloat MaxCD = maxnum(abs(C), abs(D));
14337         if (MaxCD.isFinite()) {
14338           DenomLogB = ilogb(MaxCD);
14339           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14340           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14341         }
14342         APFloat Denom = C * C + D * D;
14343         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14344                       APFloat::rmNearestTiesToEven);
14345         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14346                       APFloat::rmNearestTiesToEven);
14347         if (ResR.isNaN() && ResI.isNaN()) {
14348           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14349             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14350             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14351           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14352                      D.isFinite()) {
14353             A = APFloat::copySign(
14354                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14355             B = APFloat::copySign(
14356                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14357             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14358             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14359           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14360             C = APFloat::copySign(
14361                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14362             D = APFloat::copySign(
14363                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14364             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14365             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14366           }
14367         }
14368       }
14369     } else {
14370       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14371         return Error(E, diag::note_expr_divide_by_zero);
14372 
14373       ComplexValue LHS = Result;
14374       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14375         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14376       Result.getComplexIntReal() =
14377         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14378          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14379       Result.getComplexIntImag() =
14380         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14381          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14382     }
14383     break;
14384   }
14385 
14386   return true;
14387 }
14388 
14389 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14390   // Get the operand value into 'Result'.
14391   if (!Visit(E->getSubExpr()))
14392     return false;
14393 
14394   switch (E->getOpcode()) {
14395   default:
14396     return Error(E);
14397   case UO_Extension:
14398     return true;
14399   case UO_Plus:
14400     // The result is always just the subexpr.
14401     return true;
14402   case UO_Minus:
14403     if (Result.isComplexFloat()) {
14404       Result.getComplexFloatReal().changeSign();
14405       Result.getComplexFloatImag().changeSign();
14406     }
14407     else {
14408       Result.getComplexIntReal() = -Result.getComplexIntReal();
14409       Result.getComplexIntImag() = -Result.getComplexIntImag();
14410     }
14411     return true;
14412   case UO_Not:
14413     if (Result.isComplexFloat())
14414       Result.getComplexFloatImag().changeSign();
14415     else
14416       Result.getComplexIntImag() = -Result.getComplexIntImag();
14417     return true;
14418   }
14419 }
14420 
14421 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14422   if (E->getNumInits() == 2) {
14423     if (E->getType()->isComplexType()) {
14424       Result.makeComplexFloat();
14425       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14426         return false;
14427       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14428         return false;
14429     } else {
14430       Result.makeComplexInt();
14431       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14432         return false;
14433       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14434         return false;
14435     }
14436     return true;
14437   }
14438   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14439 }
14440 
14441 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14442   switch (E->getBuiltinCallee()) {
14443   case Builtin::BI__builtin_complex:
14444     Result.makeComplexFloat();
14445     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14446       return false;
14447     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14448       return false;
14449     return true;
14450 
14451   default:
14452     break;
14453   }
14454 
14455   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14456 }
14457 
14458 //===----------------------------------------------------------------------===//
14459 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14460 // implicit conversion.
14461 //===----------------------------------------------------------------------===//
14462 
14463 namespace {
14464 class AtomicExprEvaluator :
14465     public ExprEvaluatorBase<AtomicExprEvaluator> {
14466   const LValue *This;
14467   APValue &Result;
14468 public:
14469   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14470       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14471 
14472   bool Success(const APValue &V, const Expr *E) {
14473     Result = V;
14474     return true;
14475   }
14476 
14477   bool ZeroInitialization(const Expr *E) {
14478     ImplicitValueInitExpr VIE(
14479         E->getType()->castAs<AtomicType>()->getValueType());
14480     // For atomic-qualified class (and array) types in C++, initialize the
14481     // _Atomic-wrapped subobject directly, in-place.
14482     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14483                 : Evaluate(Result, Info, &VIE);
14484   }
14485 
14486   bool VisitCastExpr(const CastExpr *E) {
14487     switch (E->getCastKind()) {
14488     default:
14489       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14490     case CK_NonAtomicToAtomic:
14491       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14492                   : Evaluate(Result, Info, E->getSubExpr());
14493     }
14494   }
14495 };
14496 } // end anonymous namespace
14497 
14498 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14499                            EvalInfo &Info) {
14500   assert(!E->isValueDependent());
14501   assert(E->isPRValue() && E->getType()->isAtomicType());
14502   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14503 }
14504 
14505 //===----------------------------------------------------------------------===//
14506 // Void expression evaluation, primarily for a cast to void on the LHS of a
14507 // comma operator
14508 //===----------------------------------------------------------------------===//
14509 
14510 namespace {
14511 class VoidExprEvaluator
14512   : public ExprEvaluatorBase<VoidExprEvaluator> {
14513 public:
14514   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14515 
14516   bool Success(const APValue &V, const Expr *e) { return true; }
14517 
14518   bool ZeroInitialization(const Expr *E) { return true; }
14519 
14520   bool VisitCastExpr(const CastExpr *E) {
14521     switch (E->getCastKind()) {
14522     default:
14523       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14524     case CK_ToVoid:
14525       VisitIgnoredValue(E->getSubExpr());
14526       return true;
14527     }
14528   }
14529 
14530   bool VisitCallExpr(const CallExpr *E) {
14531     switch (E->getBuiltinCallee()) {
14532     case Builtin::BI__assume:
14533     case Builtin::BI__builtin_assume:
14534       // The argument is not evaluated!
14535       return true;
14536 
14537     case Builtin::BI__builtin_operator_delete:
14538       return HandleOperatorDeleteCall(Info, E);
14539 
14540     default:
14541       break;
14542     }
14543 
14544     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14545   }
14546 
14547   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14548 };
14549 } // end anonymous namespace
14550 
14551 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14552   // We cannot speculatively evaluate a delete expression.
14553   if (Info.SpeculativeEvaluationDepth)
14554     return false;
14555 
14556   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14557   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14558     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14559         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14560     return false;
14561   }
14562 
14563   const Expr *Arg = E->getArgument();
14564 
14565   LValue Pointer;
14566   if (!EvaluatePointer(Arg, Pointer, Info))
14567     return false;
14568   if (Pointer.Designator.Invalid)
14569     return false;
14570 
14571   // Deleting a null pointer has no effect.
14572   if (Pointer.isNullPointer()) {
14573     // This is the only case where we need to produce an extension warning:
14574     // the only other way we can succeed is if we find a dynamic allocation,
14575     // and we will have warned when we allocated it in that case.
14576     if (!Info.getLangOpts().CPlusPlus20)
14577       Info.CCEDiag(E, diag::note_constexpr_new);
14578     return true;
14579   }
14580 
14581   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14582       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14583   if (!Alloc)
14584     return false;
14585   QualType AllocType = Pointer.Base.getDynamicAllocType();
14586 
14587   // For the non-array case, the designator must be empty if the static type
14588   // does not have a virtual destructor.
14589   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14590       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14591     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14592         << Arg->getType()->getPointeeType() << AllocType;
14593     return false;
14594   }
14595 
14596   // For a class type with a virtual destructor, the selected operator delete
14597   // is the one looked up when building the destructor.
14598   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14599     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14600     if (VirtualDelete &&
14601         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14602       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14603           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14604       return false;
14605     }
14606   }
14607 
14608   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14609                          (*Alloc)->Value, AllocType))
14610     return false;
14611 
14612   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14613     // The element was already erased. This means the destructor call also
14614     // deleted the object.
14615     // FIXME: This probably results in undefined behavior before we get this
14616     // far, and should be diagnosed elsewhere first.
14617     Info.FFDiag(E, diag::note_constexpr_double_delete);
14618     return false;
14619   }
14620 
14621   return true;
14622 }
14623 
14624 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14625   assert(!E->isValueDependent());
14626   assert(E->isPRValue() && E->getType()->isVoidType());
14627   return VoidExprEvaluator(Info).Visit(E);
14628 }
14629 
14630 //===----------------------------------------------------------------------===//
14631 // Top level Expr::EvaluateAsRValue method.
14632 //===----------------------------------------------------------------------===//
14633 
14634 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14635   assert(!E->isValueDependent());
14636   // In C, function designators are not lvalues, but we evaluate them as if they
14637   // are.
14638   QualType T = E->getType();
14639   if (E->isGLValue() || T->isFunctionType()) {
14640     LValue LV;
14641     if (!EvaluateLValue(E, LV, Info))
14642       return false;
14643     LV.moveInto(Result);
14644   } else if (T->isVectorType()) {
14645     if (!EvaluateVector(E, Result, Info))
14646       return false;
14647   } else if (T->isIntegralOrEnumerationType()) {
14648     if (!IntExprEvaluator(Info, Result).Visit(E))
14649       return false;
14650   } else if (T->hasPointerRepresentation()) {
14651     LValue LV;
14652     if (!EvaluatePointer(E, LV, Info))
14653       return false;
14654     LV.moveInto(Result);
14655   } else if (T->isRealFloatingType()) {
14656     llvm::APFloat F(0.0);
14657     if (!EvaluateFloat(E, F, Info))
14658       return false;
14659     Result = APValue(F);
14660   } else if (T->isAnyComplexType()) {
14661     ComplexValue C;
14662     if (!EvaluateComplex(E, C, Info))
14663       return false;
14664     C.moveInto(Result);
14665   } else if (T->isFixedPointType()) {
14666     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14667   } else if (T->isMemberPointerType()) {
14668     MemberPtr P;
14669     if (!EvaluateMemberPointer(E, P, Info))
14670       return false;
14671     P.moveInto(Result);
14672     return true;
14673   } else if (T->isArrayType()) {
14674     LValue LV;
14675     APValue &Value =
14676         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14677     if (!EvaluateArray(E, LV, Value, Info))
14678       return false;
14679     Result = Value;
14680   } else if (T->isRecordType()) {
14681     LValue LV;
14682     APValue &Value =
14683         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14684     if (!EvaluateRecord(E, LV, Value, Info))
14685       return false;
14686     Result = Value;
14687   } else if (T->isVoidType()) {
14688     if (!Info.getLangOpts().CPlusPlus11)
14689       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14690         << E->getType();
14691     if (!EvaluateVoid(E, Info))
14692       return false;
14693   } else if (T->isAtomicType()) {
14694     QualType Unqual = T.getAtomicUnqualifiedType();
14695     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14696       LValue LV;
14697       APValue &Value = Info.CurrentCall->createTemporary(
14698           E, Unqual, ScopeKind::FullExpression, LV);
14699       if (!EvaluateAtomic(E, &LV, Value, Info))
14700         return false;
14701     } else {
14702       if (!EvaluateAtomic(E, nullptr, Result, Info))
14703         return false;
14704     }
14705   } else if (Info.getLangOpts().CPlusPlus11) {
14706     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14707     return false;
14708   } else {
14709     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14710     return false;
14711   }
14712 
14713   return true;
14714 }
14715 
14716 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14717 /// cases, the in-place evaluation is essential, since later initializers for
14718 /// an object can indirectly refer to subobjects which were initialized earlier.
14719 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14720                             const Expr *E, bool AllowNonLiteralTypes) {
14721   assert(!E->isValueDependent());
14722 
14723   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14724     return false;
14725 
14726   if (E->isPRValue()) {
14727     // Evaluate arrays and record types in-place, so that later initializers can
14728     // refer to earlier-initialized members of the object.
14729     QualType T = E->getType();
14730     if (T->isArrayType())
14731       return EvaluateArray(E, This, Result, Info);
14732     else if (T->isRecordType())
14733       return EvaluateRecord(E, This, Result, Info);
14734     else if (T->isAtomicType()) {
14735       QualType Unqual = T.getAtomicUnqualifiedType();
14736       if (Unqual->isArrayType() || Unqual->isRecordType())
14737         return EvaluateAtomic(E, &This, Result, Info);
14738     }
14739   }
14740 
14741   // For any other type, in-place evaluation is unimportant.
14742   return Evaluate(Result, Info, E);
14743 }
14744 
14745 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14746 /// lvalue-to-rvalue cast if it is an lvalue.
14747 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14748   assert(!E->isValueDependent());
14749   if (Info.EnableNewConstInterp) {
14750     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14751       return false;
14752   } else {
14753     if (E->getType().isNull())
14754       return false;
14755 
14756     if (!CheckLiteralType(Info, E))
14757       return false;
14758 
14759     if (!::Evaluate(Result, Info, E))
14760       return false;
14761 
14762     if (E->isGLValue()) {
14763       LValue LV;
14764       LV.setFrom(Info.Ctx, Result);
14765       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14766         return false;
14767     }
14768   }
14769 
14770   // Check this core constant expression is a constant expression.
14771   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14772                                  ConstantExprKind::Normal) &&
14773          CheckMemoryLeaks(Info);
14774 }
14775 
14776 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14777                                  const ASTContext &Ctx, bool &IsConst) {
14778   // Fast-path evaluations of integer literals, since we sometimes see files
14779   // containing vast quantities of these.
14780   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14781     Result.Val = APValue(APSInt(L->getValue(),
14782                                 L->getType()->isUnsignedIntegerType()));
14783     IsConst = true;
14784     return true;
14785   }
14786 
14787   // This case should be rare, but we need to check it before we check on
14788   // the type below.
14789   if (Exp->getType().isNull()) {
14790     IsConst = false;
14791     return true;
14792   }
14793 
14794   // FIXME: Evaluating values of large array and record types can cause
14795   // performance problems. Only do so in C++11 for now.
14796   if (Exp->isPRValue() &&
14797       (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
14798       !Ctx.getLangOpts().CPlusPlus11) {
14799     IsConst = false;
14800     return true;
14801   }
14802   return false;
14803 }
14804 
14805 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14806                                       Expr::SideEffectsKind SEK) {
14807   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14808          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14809 }
14810 
14811 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14812                              const ASTContext &Ctx, EvalInfo &Info) {
14813   assert(!E->isValueDependent());
14814   bool IsConst;
14815   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14816     return IsConst;
14817 
14818   return EvaluateAsRValue(Info, E, Result.Val);
14819 }
14820 
14821 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14822                           const ASTContext &Ctx,
14823                           Expr::SideEffectsKind AllowSideEffects,
14824                           EvalInfo &Info) {
14825   assert(!E->isValueDependent());
14826   if (!E->getType()->isIntegralOrEnumerationType())
14827     return false;
14828 
14829   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14830       !ExprResult.Val.isInt() ||
14831       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14832     return false;
14833 
14834   return true;
14835 }
14836 
14837 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14838                                  const ASTContext &Ctx,
14839                                  Expr::SideEffectsKind AllowSideEffects,
14840                                  EvalInfo &Info) {
14841   assert(!E->isValueDependent());
14842   if (!E->getType()->isFixedPointType())
14843     return false;
14844 
14845   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14846     return false;
14847 
14848   if (!ExprResult.Val.isFixedPoint() ||
14849       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14850     return false;
14851 
14852   return true;
14853 }
14854 
14855 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14856 /// any crazy technique (that has nothing to do with language standards) that
14857 /// we want to.  If this function returns true, it returns the folded constant
14858 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14859 /// will be applied to the result.
14860 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14861                             bool InConstantContext) const {
14862   assert(!isValueDependent() &&
14863          "Expression evaluator can't be called on a dependent expression.");
14864   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14865   Info.InConstantContext = InConstantContext;
14866   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14867 }
14868 
14869 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14870                                       bool InConstantContext) const {
14871   assert(!isValueDependent() &&
14872          "Expression evaluator can't be called on a dependent expression.");
14873   EvalResult Scratch;
14874   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14875          HandleConversionToBool(Scratch.Val, Result);
14876 }
14877 
14878 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14879                          SideEffectsKind AllowSideEffects,
14880                          bool InConstantContext) const {
14881   assert(!isValueDependent() &&
14882          "Expression evaluator can't be called on a dependent expression.");
14883   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14884   Info.InConstantContext = InConstantContext;
14885   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14886 }
14887 
14888 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14889                                 SideEffectsKind AllowSideEffects,
14890                                 bool InConstantContext) const {
14891   assert(!isValueDependent() &&
14892          "Expression evaluator can't be called on a dependent expression.");
14893   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14894   Info.InConstantContext = InConstantContext;
14895   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14896 }
14897 
14898 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14899                            SideEffectsKind AllowSideEffects,
14900                            bool InConstantContext) const {
14901   assert(!isValueDependent() &&
14902          "Expression evaluator can't be called on a dependent expression.");
14903 
14904   if (!getType()->isRealFloatingType())
14905     return false;
14906 
14907   EvalResult ExprResult;
14908   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14909       !ExprResult.Val.isFloat() ||
14910       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14911     return false;
14912 
14913   Result = ExprResult.Val.getFloat();
14914   return true;
14915 }
14916 
14917 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14918                             bool InConstantContext) const {
14919   assert(!isValueDependent() &&
14920          "Expression evaluator can't be called on a dependent expression.");
14921 
14922   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14923   Info.InConstantContext = InConstantContext;
14924   LValue LV;
14925   CheckedTemporaries CheckedTemps;
14926   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14927       Result.HasSideEffects ||
14928       !CheckLValueConstantExpression(Info, getExprLoc(),
14929                                      Ctx.getLValueReferenceType(getType()), LV,
14930                                      ConstantExprKind::Normal, CheckedTemps))
14931     return false;
14932 
14933   LV.moveInto(Result.Val);
14934   return true;
14935 }
14936 
14937 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
14938                                 APValue DestroyedValue, QualType Type,
14939                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
14940                                 bool IsConstantDestruction) {
14941   EvalInfo Info(Ctx, EStatus,
14942                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
14943                                       : EvalInfo::EM_ConstantFold);
14944   Info.setEvaluatingDecl(Base, DestroyedValue,
14945                          EvalInfo::EvaluatingDeclKind::Dtor);
14946   Info.InConstantContext = IsConstantDestruction;
14947 
14948   LValue LVal;
14949   LVal.set(Base);
14950 
14951   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
14952       EStatus.HasSideEffects)
14953     return false;
14954 
14955   if (!Info.discardCleanups())
14956     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14957 
14958   return true;
14959 }
14960 
14961 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
14962                                   ConstantExprKind Kind) const {
14963   assert(!isValueDependent() &&
14964          "Expression evaluator can't be called on a dependent expression.");
14965 
14966   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14967   EvalInfo Info(Ctx, Result, EM);
14968   Info.InConstantContext = true;
14969 
14970   // The type of the object we're initializing is 'const T' for a class NTTP.
14971   QualType T = getType();
14972   if (Kind == ConstantExprKind::ClassTemplateArgument)
14973     T.addConst();
14974 
14975   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
14976   // represent the result of the evaluation. CheckConstantExpression ensures
14977   // this doesn't escape.
14978   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
14979   APValue::LValueBase Base(&BaseMTE);
14980 
14981   Info.setEvaluatingDecl(Base, Result.Val);
14982   LValue LVal;
14983   LVal.set(Base);
14984 
14985   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
14986     return false;
14987 
14988   if (!Info.discardCleanups())
14989     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14990 
14991   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14992                                Result.Val, Kind))
14993     return false;
14994   if (!CheckMemoryLeaks(Info))
14995     return false;
14996 
14997   // If this is a class template argument, it's required to have constant
14998   // destruction too.
14999   if (Kind == ConstantExprKind::ClassTemplateArgument &&
15000       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
15001                             true) ||
15002        Result.HasSideEffects)) {
15003     // FIXME: Prefix a note to indicate that the problem is lack of constant
15004     // destruction.
15005     return false;
15006   }
15007 
15008   return true;
15009 }
15010 
15011 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
15012                                  const VarDecl *VD,
15013                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
15014                                  bool IsConstantInitialization) const {
15015   assert(!isValueDependent() &&
15016          "Expression evaluator can't be called on a dependent expression.");
15017 
15018   // FIXME: Evaluating initializers for large array and record types can cause
15019   // performance problems. Only do so in C++11 for now.
15020   if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
15021       !Ctx.getLangOpts().CPlusPlus11)
15022     return false;
15023 
15024   Expr::EvalStatus EStatus;
15025   EStatus.Diag = &Notes;
15026 
15027   EvalInfo Info(Ctx, EStatus,
15028                 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
15029                     ? EvalInfo::EM_ConstantExpression
15030                     : EvalInfo::EM_ConstantFold);
15031   Info.setEvaluatingDecl(VD, Value);
15032   Info.InConstantContext = IsConstantInitialization;
15033 
15034   SourceLocation DeclLoc = VD->getLocation();
15035   QualType DeclTy = VD->getType();
15036 
15037   if (Info.EnableNewConstInterp) {
15038     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
15039     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
15040       return false;
15041   } else {
15042     LValue LVal;
15043     LVal.set(VD);
15044 
15045     if (!EvaluateInPlace(Value, Info, LVal, this,
15046                          /*AllowNonLiteralTypes=*/true) ||
15047         EStatus.HasSideEffects)
15048       return false;
15049 
15050     // At this point, any lifetime-extended temporaries are completely
15051     // initialized.
15052     Info.performLifetimeExtension();
15053 
15054     if (!Info.discardCleanups())
15055       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15056   }
15057   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15058                                  ConstantExprKind::Normal) &&
15059          CheckMemoryLeaks(Info);
15060 }
15061 
15062 bool VarDecl::evaluateDestruction(
15063     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15064   Expr::EvalStatus EStatus;
15065   EStatus.Diag = &Notes;
15066 
15067   // Only treat the destruction as constant destruction if we formally have
15068   // constant initialization (or are usable in a constant expression).
15069   bool IsConstantDestruction = hasConstantInitialization();
15070 
15071   // Make a copy of the value for the destructor to mutate, if we know it.
15072   // Otherwise, treat the value as default-initialized; if the destructor works
15073   // anyway, then the destruction is constant (and must be essentially empty).
15074   APValue DestroyedValue;
15075   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15076     DestroyedValue = *getEvaluatedValue();
15077   else if (!getDefaultInitValue(getType(), DestroyedValue))
15078     return false;
15079 
15080   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15081                            getType(), getLocation(), EStatus,
15082                            IsConstantDestruction) ||
15083       EStatus.HasSideEffects)
15084     return false;
15085 
15086   ensureEvaluatedStmt()->HasConstantDestruction = true;
15087   return true;
15088 }
15089 
15090 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15091 /// constant folded, but discard the result.
15092 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15093   assert(!isValueDependent() &&
15094          "Expression evaluator can't be called on a dependent expression.");
15095 
15096   EvalResult Result;
15097   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15098          !hasUnacceptableSideEffect(Result, SEK);
15099 }
15100 
15101 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15102                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15103   assert(!isValueDependent() &&
15104          "Expression evaluator can't be called on a dependent expression.");
15105 
15106   EvalResult EVResult;
15107   EVResult.Diag = Diag;
15108   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15109   Info.InConstantContext = true;
15110 
15111   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15112   (void)Result;
15113   assert(Result && "Could not evaluate expression");
15114   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15115 
15116   return EVResult.Val.getInt();
15117 }
15118 
15119 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15120     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15121   assert(!isValueDependent() &&
15122          "Expression evaluator can't be called on a dependent expression.");
15123 
15124   EvalResult EVResult;
15125   EVResult.Diag = Diag;
15126   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15127   Info.InConstantContext = true;
15128   Info.CheckingForUndefinedBehavior = true;
15129 
15130   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15131   (void)Result;
15132   assert(Result && "Could not evaluate expression");
15133   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15134 
15135   return EVResult.Val.getInt();
15136 }
15137 
15138 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15139   assert(!isValueDependent() &&
15140          "Expression evaluator can't be called on a dependent expression.");
15141 
15142   bool IsConst;
15143   EvalResult EVResult;
15144   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15145     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15146     Info.CheckingForUndefinedBehavior = true;
15147     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15148   }
15149 }
15150 
15151 bool Expr::EvalResult::isGlobalLValue() const {
15152   assert(Val.isLValue());
15153   return IsGlobalLValue(Val.getLValueBase());
15154 }
15155 
15156 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15157 /// an integer constant expression.
15158 
15159 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15160 /// comma, etc
15161 
15162 // CheckICE - This function does the fundamental ICE checking: the returned
15163 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15164 // and a (possibly null) SourceLocation indicating the location of the problem.
15165 //
15166 // Note that to reduce code duplication, this helper does no evaluation
15167 // itself; the caller checks whether the expression is evaluatable, and
15168 // in the rare cases where CheckICE actually cares about the evaluated
15169 // value, it calls into Evaluate.
15170 
15171 namespace {
15172 
15173 enum ICEKind {
15174   /// This expression is an ICE.
15175   IK_ICE,
15176   /// This expression is not an ICE, but if it isn't evaluated, it's
15177   /// a legal subexpression for an ICE. This return value is used to handle
15178   /// the comma operator in C99 mode, and non-constant subexpressions.
15179   IK_ICEIfUnevaluated,
15180   /// This expression is not an ICE, and is not a legal subexpression for one.
15181   IK_NotICE
15182 };
15183 
15184 struct ICEDiag {
15185   ICEKind Kind;
15186   SourceLocation Loc;
15187 
15188   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15189 };
15190 
15191 }
15192 
15193 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15194 
15195 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15196 
15197 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15198   Expr::EvalResult EVResult;
15199   Expr::EvalStatus Status;
15200   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15201 
15202   Info.InConstantContext = true;
15203   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15204       !EVResult.Val.isInt())
15205     return ICEDiag(IK_NotICE, E->getBeginLoc());
15206 
15207   return NoDiag();
15208 }
15209 
15210 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15211   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15212   if (!E->getType()->isIntegralOrEnumerationType())
15213     return ICEDiag(IK_NotICE, E->getBeginLoc());
15214 
15215   switch (E->getStmtClass()) {
15216 #define ABSTRACT_STMT(Node)
15217 #define STMT(Node, Base) case Expr::Node##Class:
15218 #define EXPR(Node, Base)
15219 #include "clang/AST/StmtNodes.inc"
15220   case Expr::PredefinedExprClass:
15221   case Expr::FloatingLiteralClass:
15222   case Expr::ImaginaryLiteralClass:
15223   case Expr::StringLiteralClass:
15224   case Expr::ArraySubscriptExprClass:
15225   case Expr::MatrixSubscriptExprClass:
15226   case Expr::OMPArraySectionExprClass:
15227   case Expr::OMPArrayShapingExprClass:
15228   case Expr::OMPIteratorExprClass:
15229   case Expr::MemberExprClass:
15230   case Expr::CompoundAssignOperatorClass:
15231   case Expr::CompoundLiteralExprClass:
15232   case Expr::ExtVectorElementExprClass:
15233   case Expr::DesignatedInitExprClass:
15234   case Expr::ArrayInitLoopExprClass:
15235   case Expr::ArrayInitIndexExprClass:
15236   case Expr::NoInitExprClass:
15237   case Expr::DesignatedInitUpdateExprClass:
15238   case Expr::ImplicitValueInitExprClass:
15239   case Expr::ParenListExprClass:
15240   case Expr::VAArgExprClass:
15241   case Expr::AddrLabelExprClass:
15242   case Expr::StmtExprClass:
15243   case Expr::CXXMemberCallExprClass:
15244   case Expr::CUDAKernelCallExprClass:
15245   case Expr::CXXAddrspaceCastExprClass:
15246   case Expr::CXXDynamicCastExprClass:
15247   case Expr::CXXTypeidExprClass:
15248   case Expr::CXXUuidofExprClass:
15249   case Expr::MSPropertyRefExprClass:
15250   case Expr::MSPropertySubscriptExprClass:
15251   case Expr::CXXNullPtrLiteralExprClass:
15252   case Expr::UserDefinedLiteralClass:
15253   case Expr::CXXThisExprClass:
15254   case Expr::CXXThrowExprClass:
15255   case Expr::CXXNewExprClass:
15256   case Expr::CXXDeleteExprClass:
15257   case Expr::CXXPseudoDestructorExprClass:
15258   case Expr::UnresolvedLookupExprClass:
15259   case Expr::TypoExprClass:
15260   case Expr::RecoveryExprClass:
15261   case Expr::DependentScopeDeclRefExprClass:
15262   case Expr::CXXConstructExprClass:
15263   case Expr::CXXInheritedCtorInitExprClass:
15264   case Expr::CXXStdInitializerListExprClass:
15265   case Expr::CXXBindTemporaryExprClass:
15266   case Expr::ExprWithCleanupsClass:
15267   case Expr::CXXTemporaryObjectExprClass:
15268   case Expr::CXXUnresolvedConstructExprClass:
15269   case Expr::CXXDependentScopeMemberExprClass:
15270   case Expr::UnresolvedMemberExprClass:
15271   case Expr::ObjCStringLiteralClass:
15272   case Expr::ObjCBoxedExprClass:
15273   case Expr::ObjCArrayLiteralClass:
15274   case Expr::ObjCDictionaryLiteralClass:
15275   case Expr::ObjCEncodeExprClass:
15276   case Expr::ObjCMessageExprClass:
15277   case Expr::ObjCSelectorExprClass:
15278   case Expr::ObjCProtocolExprClass:
15279   case Expr::ObjCIvarRefExprClass:
15280   case Expr::ObjCPropertyRefExprClass:
15281   case Expr::ObjCSubscriptRefExprClass:
15282   case Expr::ObjCIsaExprClass:
15283   case Expr::ObjCAvailabilityCheckExprClass:
15284   case Expr::ShuffleVectorExprClass:
15285   case Expr::ConvertVectorExprClass:
15286   case Expr::BlockExprClass:
15287   case Expr::NoStmtClass:
15288   case Expr::OpaqueValueExprClass:
15289   case Expr::PackExpansionExprClass:
15290   case Expr::SubstNonTypeTemplateParmPackExprClass:
15291   case Expr::FunctionParmPackExprClass:
15292   case Expr::AsTypeExprClass:
15293   case Expr::ObjCIndirectCopyRestoreExprClass:
15294   case Expr::MaterializeTemporaryExprClass:
15295   case Expr::PseudoObjectExprClass:
15296   case Expr::AtomicExprClass:
15297   case Expr::LambdaExprClass:
15298   case Expr::CXXFoldExprClass:
15299   case Expr::CoawaitExprClass:
15300   case Expr::DependentCoawaitExprClass:
15301   case Expr::CoyieldExprClass:
15302   case Expr::SYCLUniqueStableNameExprClass:
15303     return ICEDiag(IK_NotICE, E->getBeginLoc());
15304 
15305   case Expr::InitListExprClass: {
15306     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15307     // form "T x = { a };" is equivalent to "T x = a;".
15308     // Unless we're initializing a reference, T is a scalar as it is known to be
15309     // of integral or enumeration type.
15310     if (E->isPRValue())
15311       if (cast<InitListExpr>(E)->getNumInits() == 1)
15312         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15313     return ICEDiag(IK_NotICE, E->getBeginLoc());
15314   }
15315 
15316   case Expr::SizeOfPackExprClass:
15317   case Expr::GNUNullExprClass:
15318   case Expr::SourceLocExprClass:
15319     return NoDiag();
15320 
15321   case Expr::SubstNonTypeTemplateParmExprClass:
15322     return
15323       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15324 
15325   case Expr::ConstantExprClass:
15326     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15327 
15328   case Expr::ParenExprClass:
15329     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15330   case Expr::GenericSelectionExprClass:
15331     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15332   case Expr::IntegerLiteralClass:
15333   case Expr::FixedPointLiteralClass:
15334   case Expr::CharacterLiteralClass:
15335   case Expr::ObjCBoolLiteralExprClass:
15336   case Expr::CXXBoolLiteralExprClass:
15337   case Expr::CXXScalarValueInitExprClass:
15338   case Expr::TypeTraitExprClass:
15339   case Expr::ConceptSpecializationExprClass:
15340   case Expr::RequiresExprClass:
15341   case Expr::ArrayTypeTraitExprClass:
15342   case Expr::ExpressionTraitExprClass:
15343   case Expr::CXXNoexceptExprClass:
15344     return NoDiag();
15345   case Expr::CallExprClass:
15346   case Expr::CXXOperatorCallExprClass: {
15347     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15348     // constant expressions, but they can never be ICEs because an ICE cannot
15349     // contain an operand of (pointer to) function type.
15350     const CallExpr *CE = cast<CallExpr>(E);
15351     if (CE->getBuiltinCallee())
15352       return CheckEvalInICE(E, Ctx);
15353     return ICEDiag(IK_NotICE, E->getBeginLoc());
15354   }
15355   case Expr::CXXRewrittenBinaryOperatorClass:
15356     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15357                     Ctx);
15358   case Expr::DeclRefExprClass: {
15359     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15360     if (isa<EnumConstantDecl>(D))
15361       return NoDiag();
15362 
15363     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15364     // integer variables in constant expressions:
15365     //
15366     // C++ 7.1.5.1p2
15367     //   A variable of non-volatile const-qualified integral or enumeration
15368     //   type initialized by an ICE can be used in ICEs.
15369     //
15370     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15371     // that mode, use of reference variables should not be allowed.
15372     const VarDecl *VD = dyn_cast<VarDecl>(D);
15373     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15374         !VD->getType()->isReferenceType())
15375       return NoDiag();
15376 
15377     return ICEDiag(IK_NotICE, E->getBeginLoc());
15378   }
15379   case Expr::UnaryOperatorClass: {
15380     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15381     switch (Exp->getOpcode()) {
15382     case UO_PostInc:
15383     case UO_PostDec:
15384     case UO_PreInc:
15385     case UO_PreDec:
15386     case UO_AddrOf:
15387     case UO_Deref:
15388     case UO_Coawait:
15389       // C99 6.6/3 allows increment and decrement within unevaluated
15390       // subexpressions of constant expressions, but they can never be ICEs
15391       // because an ICE cannot contain an lvalue operand.
15392       return ICEDiag(IK_NotICE, E->getBeginLoc());
15393     case UO_Extension:
15394     case UO_LNot:
15395     case UO_Plus:
15396     case UO_Minus:
15397     case UO_Not:
15398     case UO_Real:
15399     case UO_Imag:
15400       return CheckICE(Exp->getSubExpr(), Ctx);
15401     }
15402     llvm_unreachable("invalid unary operator class");
15403   }
15404   case Expr::OffsetOfExprClass: {
15405     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15406     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15407     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15408     // compliance: we should warn earlier for offsetof expressions with
15409     // array subscripts that aren't ICEs, and if the array subscripts
15410     // are ICEs, the value of the offsetof must be an integer constant.
15411     return CheckEvalInICE(E, Ctx);
15412   }
15413   case Expr::UnaryExprOrTypeTraitExprClass: {
15414     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15415     if ((Exp->getKind() ==  UETT_SizeOf) &&
15416         Exp->getTypeOfArgument()->isVariableArrayType())
15417       return ICEDiag(IK_NotICE, E->getBeginLoc());
15418     return NoDiag();
15419   }
15420   case Expr::BinaryOperatorClass: {
15421     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15422     switch (Exp->getOpcode()) {
15423     case BO_PtrMemD:
15424     case BO_PtrMemI:
15425     case BO_Assign:
15426     case BO_MulAssign:
15427     case BO_DivAssign:
15428     case BO_RemAssign:
15429     case BO_AddAssign:
15430     case BO_SubAssign:
15431     case BO_ShlAssign:
15432     case BO_ShrAssign:
15433     case BO_AndAssign:
15434     case BO_XorAssign:
15435     case BO_OrAssign:
15436       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15437       // constant expressions, but they can never be ICEs because an ICE cannot
15438       // contain an lvalue operand.
15439       return ICEDiag(IK_NotICE, E->getBeginLoc());
15440 
15441     case BO_Mul:
15442     case BO_Div:
15443     case BO_Rem:
15444     case BO_Add:
15445     case BO_Sub:
15446     case BO_Shl:
15447     case BO_Shr:
15448     case BO_LT:
15449     case BO_GT:
15450     case BO_LE:
15451     case BO_GE:
15452     case BO_EQ:
15453     case BO_NE:
15454     case BO_And:
15455     case BO_Xor:
15456     case BO_Or:
15457     case BO_Comma:
15458     case BO_Cmp: {
15459       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15460       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15461       if (Exp->getOpcode() == BO_Div ||
15462           Exp->getOpcode() == BO_Rem) {
15463         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15464         // we don't evaluate one.
15465         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15466           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15467           if (REval == 0)
15468             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15469           if (REval.isSigned() && REval.isAllOnes()) {
15470             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15471             if (LEval.isMinSignedValue())
15472               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15473           }
15474         }
15475       }
15476       if (Exp->getOpcode() == BO_Comma) {
15477         if (Ctx.getLangOpts().C99) {
15478           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15479           // if it isn't evaluated.
15480           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15481             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15482         } else {
15483           // In both C89 and C++, commas in ICEs are illegal.
15484           return ICEDiag(IK_NotICE, E->getBeginLoc());
15485         }
15486       }
15487       return Worst(LHSResult, RHSResult);
15488     }
15489     case BO_LAnd:
15490     case BO_LOr: {
15491       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15492       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15493       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15494         // Rare case where the RHS has a comma "side-effect"; we need
15495         // to actually check the condition to see whether the side
15496         // with the comma is evaluated.
15497         if ((Exp->getOpcode() == BO_LAnd) !=
15498             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15499           return RHSResult;
15500         return NoDiag();
15501       }
15502 
15503       return Worst(LHSResult, RHSResult);
15504     }
15505     }
15506     llvm_unreachable("invalid binary operator kind");
15507   }
15508   case Expr::ImplicitCastExprClass:
15509   case Expr::CStyleCastExprClass:
15510   case Expr::CXXFunctionalCastExprClass:
15511   case Expr::CXXStaticCastExprClass:
15512   case Expr::CXXReinterpretCastExprClass:
15513   case Expr::CXXConstCastExprClass:
15514   case Expr::ObjCBridgedCastExprClass: {
15515     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15516     if (isa<ExplicitCastExpr>(E)) {
15517       if (const FloatingLiteral *FL
15518             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15519         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15520         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15521         APSInt IgnoredVal(DestWidth, !DestSigned);
15522         bool Ignored;
15523         // If the value does not fit in the destination type, the behavior is
15524         // undefined, so we are not required to treat it as a constant
15525         // expression.
15526         if (FL->getValue().convertToInteger(IgnoredVal,
15527                                             llvm::APFloat::rmTowardZero,
15528                                             &Ignored) & APFloat::opInvalidOp)
15529           return ICEDiag(IK_NotICE, E->getBeginLoc());
15530         return NoDiag();
15531       }
15532     }
15533     switch (cast<CastExpr>(E)->getCastKind()) {
15534     case CK_LValueToRValue:
15535     case CK_AtomicToNonAtomic:
15536     case CK_NonAtomicToAtomic:
15537     case CK_NoOp:
15538     case CK_IntegralToBoolean:
15539     case CK_IntegralCast:
15540       return CheckICE(SubExpr, Ctx);
15541     default:
15542       return ICEDiag(IK_NotICE, E->getBeginLoc());
15543     }
15544   }
15545   case Expr::BinaryConditionalOperatorClass: {
15546     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15547     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15548     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15549     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15550     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15551     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15552     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15553         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15554     return FalseResult;
15555   }
15556   case Expr::ConditionalOperatorClass: {
15557     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15558     // If the condition (ignoring parens) is a __builtin_constant_p call,
15559     // then only the true side is actually considered in an integer constant
15560     // expression, and it is fully evaluated.  This is an important GNU
15561     // extension.  See GCC PR38377 for discussion.
15562     if (const CallExpr *CallCE
15563         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15564       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15565         return CheckEvalInICE(E, Ctx);
15566     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15567     if (CondResult.Kind == IK_NotICE)
15568       return CondResult;
15569 
15570     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15571     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15572 
15573     if (TrueResult.Kind == IK_NotICE)
15574       return TrueResult;
15575     if (FalseResult.Kind == IK_NotICE)
15576       return FalseResult;
15577     if (CondResult.Kind == IK_ICEIfUnevaluated)
15578       return CondResult;
15579     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15580       return NoDiag();
15581     // Rare case where the diagnostics depend on which side is evaluated
15582     // Note that if we get here, CondResult is 0, and at least one of
15583     // TrueResult and FalseResult is non-zero.
15584     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15585       return FalseResult;
15586     return TrueResult;
15587   }
15588   case Expr::CXXDefaultArgExprClass:
15589     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15590   case Expr::CXXDefaultInitExprClass:
15591     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15592   case Expr::ChooseExprClass: {
15593     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15594   }
15595   case Expr::BuiltinBitCastExprClass: {
15596     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15597       return ICEDiag(IK_NotICE, E->getBeginLoc());
15598     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15599   }
15600   }
15601 
15602   llvm_unreachable("Invalid StmtClass!");
15603 }
15604 
15605 /// Evaluate an expression as a C++11 integral constant expression.
15606 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15607                                                     const Expr *E,
15608                                                     llvm::APSInt *Value,
15609                                                     SourceLocation *Loc) {
15610   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15611     if (Loc) *Loc = E->getExprLoc();
15612     return false;
15613   }
15614 
15615   APValue Result;
15616   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15617     return false;
15618 
15619   if (!Result.isInt()) {
15620     if (Loc) *Loc = E->getExprLoc();
15621     return false;
15622   }
15623 
15624   if (Value) *Value = Result.getInt();
15625   return true;
15626 }
15627 
15628 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15629                                  SourceLocation *Loc) const {
15630   assert(!isValueDependent() &&
15631          "Expression evaluator can't be called on a dependent expression.");
15632 
15633   if (Ctx.getLangOpts().CPlusPlus11)
15634     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15635 
15636   ICEDiag D = CheckICE(this, Ctx);
15637   if (D.Kind != IK_ICE) {
15638     if (Loc) *Loc = D.Loc;
15639     return false;
15640   }
15641   return true;
15642 }
15643 
15644 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15645                                                     SourceLocation *Loc,
15646                                                     bool isEvaluated) const {
15647   if (isValueDependent()) {
15648     // Expression evaluator can't succeed on a dependent expression.
15649     return None;
15650   }
15651 
15652   APSInt Value;
15653 
15654   if (Ctx.getLangOpts().CPlusPlus11) {
15655     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15656       return Value;
15657     return None;
15658   }
15659 
15660   if (!isIntegerConstantExpr(Ctx, Loc))
15661     return None;
15662 
15663   // The only possible side-effects here are due to UB discovered in the
15664   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15665   // required to treat the expression as an ICE, so we produce the folded
15666   // value.
15667   EvalResult ExprResult;
15668   Expr::EvalStatus Status;
15669   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15670   Info.InConstantContext = true;
15671 
15672   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15673     llvm_unreachable("ICE cannot be evaluated!");
15674 
15675   return ExprResult.Val.getInt();
15676 }
15677 
15678 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15679   assert(!isValueDependent() &&
15680          "Expression evaluator can't be called on a dependent expression.");
15681 
15682   return CheckICE(this, Ctx).Kind == IK_ICE;
15683 }
15684 
15685 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15686                                SourceLocation *Loc) const {
15687   assert(!isValueDependent() &&
15688          "Expression evaluator can't be called on a dependent expression.");
15689 
15690   // We support this checking in C++98 mode in order to diagnose compatibility
15691   // issues.
15692   assert(Ctx.getLangOpts().CPlusPlus);
15693 
15694   // Build evaluation settings.
15695   Expr::EvalStatus Status;
15696   SmallVector<PartialDiagnosticAt, 8> Diags;
15697   Status.Diag = &Diags;
15698   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15699 
15700   APValue Scratch;
15701   bool IsConstExpr =
15702       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15703       // FIXME: We don't produce a diagnostic for this, but the callers that
15704       // call us on arbitrary full-expressions should generally not care.
15705       Info.discardCleanups() && !Status.HasSideEffects;
15706 
15707   if (!Diags.empty()) {
15708     IsConstExpr = false;
15709     if (Loc) *Loc = Diags[0].first;
15710   } else if (!IsConstExpr) {
15711     // FIXME: This shouldn't happen.
15712     if (Loc) *Loc = getExprLoc();
15713   }
15714 
15715   return IsConstExpr;
15716 }
15717 
15718 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15719                                     const FunctionDecl *Callee,
15720                                     ArrayRef<const Expr*> Args,
15721                                     const Expr *This) const {
15722   assert(!isValueDependent() &&
15723          "Expression evaluator can't be called on a dependent expression.");
15724 
15725   Expr::EvalStatus Status;
15726   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15727   Info.InConstantContext = true;
15728 
15729   LValue ThisVal;
15730   const LValue *ThisPtr = nullptr;
15731   if (This) {
15732 #ifndef NDEBUG
15733     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15734     assert(MD && "Don't provide `this` for non-methods.");
15735     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15736 #endif
15737     if (!This->isValueDependent() &&
15738         EvaluateObjectArgument(Info, This, ThisVal) &&
15739         !Info.EvalStatus.HasSideEffects)
15740       ThisPtr = &ThisVal;
15741 
15742     // Ignore any side-effects from a failed evaluation. This is safe because
15743     // they can't interfere with any other argument evaluation.
15744     Info.EvalStatus.HasSideEffects = false;
15745   }
15746 
15747   CallRef Call = Info.CurrentCall->createCall(Callee);
15748   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15749        I != E; ++I) {
15750     unsigned Idx = I - Args.begin();
15751     if (Idx >= Callee->getNumParams())
15752       break;
15753     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15754     if ((*I)->isValueDependent() ||
15755         !EvaluateCallArg(PVD, *I, Call, Info) ||
15756         Info.EvalStatus.HasSideEffects) {
15757       // If evaluation fails, throw away the argument entirely.
15758       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15759         *Slot = APValue();
15760     }
15761 
15762     // Ignore any side-effects from a failed evaluation. This is safe because
15763     // they can't interfere with any other argument evaluation.
15764     Info.EvalStatus.HasSideEffects = false;
15765   }
15766 
15767   // Parameter cleanups happen in the caller and are not part of this
15768   // evaluation.
15769   Info.discardCleanups();
15770   Info.EvalStatus.HasSideEffects = false;
15771 
15772   // Build fake call to Callee.
15773   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15774   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15775   FullExpressionRAII Scope(Info);
15776   return Evaluate(Value, Info, this) && Scope.destroy() &&
15777          !Info.EvalStatus.HasSideEffects;
15778 }
15779 
15780 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15781                                    SmallVectorImpl<
15782                                      PartialDiagnosticAt> &Diags) {
15783   // FIXME: It would be useful to check constexpr function templates, but at the
15784   // moment the constant expression evaluator cannot cope with the non-rigorous
15785   // ASTs which we build for dependent expressions.
15786   if (FD->isDependentContext())
15787     return true;
15788 
15789   Expr::EvalStatus Status;
15790   Status.Diag = &Diags;
15791 
15792   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15793   Info.InConstantContext = true;
15794   Info.CheckingPotentialConstantExpression = true;
15795 
15796   // The constexpr VM attempts to compile all methods to bytecode here.
15797   if (Info.EnableNewConstInterp) {
15798     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15799     return Diags.empty();
15800   }
15801 
15802   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15803   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15804 
15805   // Fabricate an arbitrary expression on the stack and pretend that it
15806   // is a temporary being used as the 'this' pointer.
15807   LValue This;
15808   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15809   This.set({&VIE, Info.CurrentCall->Index});
15810 
15811   ArrayRef<const Expr*> Args;
15812 
15813   APValue Scratch;
15814   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15815     // Evaluate the call as a constant initializer, to allow the construction
15816     // of objects of non-literal types.
15817     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15818     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15819   } else {
15820     SourceLocation Loc = FD->getLocation();
15821     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15822                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15823   }
15824 
15825   return Diags.empty();
15826 }
15827 
15828 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15829                                               const FunctionDecl *FD,
15830                                               SmallVectorImpl<
15831                                                 PartialDiagnosticAt> &Diags) {
15832   assert(!E->isValueDependent() &&
15833          "Expression evaluator can't be called on a dependent expression.");
15834 
15835   Expr::EvalStatus Status;
15836   Status.Diag = &Diags;
15837 
15838   EvalInfo Info(FD->getASTContext(), Status,
15839                 EvalInfo::EM_ConstantExpressionUnevaluated);
15840   Info.InConstantContext = true;
15841   Info.CheckingPotentialConstantExpression = true;
15842 
15843   // Fabricate a call stack frame to give the arguments a plausible cover story.
15844   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15845 
15846   APValue ResultScratch;
15847   Evaluate(ResultScratch, Info, E);
15848   return Diags.empty();
15849 }
15850 
15851 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15852                                  unsigned Type) const {
15853   if (!getType()->isPointerType())
15854     return false;
15855 
15856   Expr::EvalStatus Status;
15857   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15858   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15859 }
15860 
15861 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
15862                                   EvalInfo &Info) {
15863   if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
15864     return false;
15865 
15866   LValue String;
15867 
15868   if (!EvaluatePointer(E, String, Info))
15869     return false;
15870 
15871   QualType CharTy = E->getType()->getPointeeType();
15872 
15873   // Fast path: if it's a string literal, search the string value.
15874   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
15875           String.getLValueBase().dyn_cast<const Expr *>())) {
15876     StringRef Str = S->getBytes();
15877     int64_t Off = String.Offset.getQuantity();
15878     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
15879         S->getCharByteWidth() == 1 &&
15880         // FIXME: Add fast-path for wchar_t too.
15881         Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
15882       Str = Str.substr(Off);
15883 
15884       StringRef::size_type Pos = Str.find(0);
15885       if (Pos != StringRef::npos)
15886         Str = Str.substr(0, Pos);
15887 
15888       Result = Str.size();
15889       return true;
15890     }
15891 
15892     // Fall through to slow path.
15893   }
15894 
15895   // Slow path: scan the bytes of the string looking for the terminating 0.
15896   for (uint64_t Strlen = 0; /**/; ++Strlen) {
15897     APValue Char;
15898     if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
15899         !Char.isInt())
15900       return false;
15901     if (!Char.getInt()) {
15902       Result = Strlen;
15903       return true;
15904     }
15905     if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
15906       return false;
15907   }
15908 }
15909 
15910 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
15911   Expr::EvalStatus Status;
15912   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15913   return EvaluateBuiltinStrLen(this, Result, Info);
15914 }
15915