Home | History | Annotate | Download | only in AST
      1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements the Expr constant evaluator.
     11 //
     12 // Constant expression evaluation produces four main results:
     13 //
     14 //  * A success/failure flag indicating whether constant folding was successful.
     15 //    This is the 'bool' return value used by most of the code in this file. A
     16 //    'false' return value indicates that constant folding has failed, and any
     17 //    appropriate diagnostic has already been produced.
     18 //
     19 //  * An evaluated result, valid only if constant folding has not failed.
     20 //
     21 //  * A flag indicating if evaluation encountered (unevaluated) side-effects.
     22 //    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
     23 //    where it is possible to determine the evaluated result regardless.
     24 //
     25 //  * A set of notes indicating why the evaluation was not a constant expression
     26 //    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
     27 //    too, why the expression could not be folded.
     28 //
     29 // If we are checking for a potential constant expression, failure to constant
     30 // fold a potential constant sub-expression will be indicated by a 'false'
     31 // return value (the expression could not be folded) and no diagnostic (the
     32 // expression is not necessarily non-constant).
     33 //
     34 //===----------------------------------------------------------------------===//
     35 
     36 #include "clang/AST/APValue.h"
     37 #include "clang/AST/ASTContext.h"
     38 #include "clang/AST/ASTDiagnostic.h"
     39 #include "clang/AST/ASTLambda.h"
     40 #include "clang/AST/CharUnits.h"
     41 #include "clang/AST/Expr.h"
     42 #include "clang/AST/RecordLayout.h"
     43 #include "clang/AST/StmtVisitor.h"
     44 #include "clang/AST/TypeLoc.h"
     45 #include "clang/Basic/Builtins.h"
     46 #include "clang/Basic/TargetInfo.h"
     47 #include "llvm/ADT/SmallString.h"
     48 #include "llvm/Support/raw_ostream.h"
     49 #include <cstring>
     50 #include <functional>
     51 
     52 using namespace clang;
     53 using llvm::APSInt;
     54 using llvm::APFloat;
     55 
     56 static bool IsGlobalLValue(APValue::LValueBase B);
     57 
     58 namespace {
     59   struct LValue;
     60   struct CallStackFrame;
     61   struct EvalInfo;
     62 
     63   static QualType getType(APValue::LValueBase B) {
     64     if (!B) return QualType();
     65     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
     66       return D->getType();
     67 
     68     const Expr *Base = B.get<const Expr*>();
     69 
     70     // For a materialized temporary, the type of the temporary we materialized
     71     // may not be the type of the expression.
     72     if (const MaterializeTemporaryExpr *MTE =
     73             dyn_cast<MaterializeTemporaryExpr>(Base)) {
     74       SmallVector<const Expr *, 2> CommaLHSs;
     75       SmallVector<SubobjectAdjustment, 2> Adjustments;
     76       const Expr *Temp = MTE->GetTemporaryExpr();
     77       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
     78                                                                Adjustments);
     79       // Keep any cv-qualifiers from the reference if we generated a temporary
     80       // for it.
     81       if (Inner != Temp)
     82         return Inner->getType();
     83     }
     84 
     85     return Base->getType();
     86   }
     87 
     88   /// Get an LValue path entry, which is known to not be an array index, as a
     89   /// field or base class.
     90   static
     91   APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
     92     APValue::BaseOrMemberType Value;
     93     Value.setFromOpaqueValue(E.BaseOrMember);
     94     return Value;
     95   }
     96 
     97   /// Get an LValue path entry, which is known to not be an array index, as a
     98   /// field declaration.
     99   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
    100     return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
    101   }
    102   /// Get an LValue path entry, which is known to not be an array index, as a
    103   /// base class declaration.
    104   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
    105     return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
    106   }
    107   /// Determine whether this LValue path entry for a base class names a virtual
    108   /// base class.
    109   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
    110     return getAsBaseOrMember(E).getInt();
    111   }
    112 
    113   /// Find the path length and type of the most-derived subobject in the given
    114   /// path, and find the size of the containing array, if any.
    115   static
    116   unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
    117                                     ArrayRef<APValue::LValuePathEntry> Path,
    118                                     uint64_t &ArraySize, QualType &Type,
    119                                     bool &IsArray) {
    120     unsigned MostDerivedLength = 0;
    121     Type = Base;
    122     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
    123       if (Type->isArrayType()) {
    124         const ConstantArrayType *CAT =
    125           cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
    126         Type = CAT->getElementType();
    127         ArraySize = CAT->getSize().getZExtValue();
    128         MostDerivedLength = I + 1;
    129         IsArray = true;
    130       } else if (Type->isAnyComplexType()) {
    131         const ComplexType *CT = Type->castAs<ComplexType>();
    132         Type = CT->getElementType();
    133         ArraySize = 2;
    134         MostDerivedLength = I + 1;
    135         IsArray = true;
    136       } else if (const FieldDecl *FD = getAsField(Path[I])) {
    137         Type = FD->getType();
    138         ArraySize = 0;
    139         MostDerivedLength = I + 1;
    140         IsArray = false;
    141       } else {
    142         // Path[I] describes a base class.
    143         ArraySize = 0;
    144         IsArray = false;
    145       }
    146     }
    147     return MostDerivedLength;
    148   }
    149 
    150   // The order of this enum is important for diagnostics.
    151   enum CheckSubobjectKind {
    152     CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
    153     CSK_This, CSK_Real, CSK_Imag
    154   };
    155 
    156   /// A path from a glvalue to a subobject of that glvalue.
    157   struct SubobjectDesignator {
    158     /// True if the subobject was named in a manner not supported by C++11. Such
    159     /// lvalues can still be folded, but they are not core constant expressions
    160     /// and we cannot perform lvalue-to-rvalue conversions on them.
    161     unsigned Invalid : 1;
    162 
    163     /// Is this a pointer one past the end of an object?
    164     unsigned IsOnePastTheEnd : 1;
    165 
    166     /// Indicator of whether the most-derived object is an array element.
    167     unsigned MostDerivedIsArrayElement : 1;
    168 
    169     /// The length of the path to the most-derived object of which this is a
    170     /// subobject.
    171     unsigned MostDerivedPathLength : 29;
    172 
    173     /// The size of the array of which the most-derived object is an element.
    174     /// This will always be 0 if the most-derived object is not an array
    175     /// element. 0 is not an indicator of whether or not the most-derived object
    176     /// is an array, however, because 0-length arrays are allowed.
    177     uint64_t MostDerivedArraySize;
    178 
    179     /// The type of the most derived object referred to by this address.
    180     QualType MostDerivedType;
    181 
    182     typedef APValue::LValuePathEntry PathEntry;
    183 
    184     /// The entries on the path from the glvalue to the designated subobject.
    185     SmallVector<PathEntry, 8> Entries;
    186 
    187     SubobjectDesignator() : Invalid(true) {}
    188 
    189     explicit SubobjectDesignator(QualType T)
    190         : Invalid(false), IsOnePastTheEnd(false),
    191           MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
    192           MostDerivedArraySize(0), MostDerivedType(T) {}
    193 
    194     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
    195         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
    196           MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
    197           MostDerivedArraySize(0) {
    198       if (!Invalid) {
    199         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
    200         ArrayRef<PathEntry> VEntries = V.getLValuePath();
    201         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
    202         if (V.getLValueBase()) {
    203           bool IsArray = false;
    204           MostDerivedPathLength =
    205               findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
    206                                        V.getLValuePath(), MostDerivedArraySize,
    207                                        MostDerivedType, IsArray);
    208           MostDerivedIsArrayElement = IsArray;
    209         }
    210       }
    211     }
    212 
    213     void setInvalid() {
    214       Invalid = true;
    215       Entries.clear();
    216     }
    217 
    218     /// Determine whether this is a one-past-the-end pointer.
    219     bool isOnePastTheEnd() const {
    220       assert(!Invalid);
    221       if (IsOnePastTheEnd)
    222         return true;
    223       if (MostDerivedIsArrayElement &&
    224           Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
    225         return true;
    226       return false;
    227     }
    228 
    229     /// Check that this refers to a valid subobject.
    230     bool isValidSubobject() const {
    231       if (Invalid)
    232         return false;
    233       return !isOnePastTheEnd();
    234     }
    235     /// Check that this refers to a valid subobject, and if not, produce a
    236     /// relevant diagnostic and set the designator as invalid.
    237     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
    238 
    239     /// Update this designator to refer to the first element within this array.
    240     void addArrayUnchecked(const ConstantArrayType *CAT) {
    241       PathEntry Entry;
    242       Entry.ArrayIndex = 0;
    243       Entries.push_back(Entry);
    244 
    245       // This is a most-derived object.
    246       MostDerivedType = CAT->getElementType();
    247       MostDerivedIsArrayElement = true;
    248       MostDerivedArraySize = CAT->getSize().getZExtValue();
    249       MostDerivedPathLength = Entries.size();
    250     }
    251     /// Update this designator to refer to the given base or member of this
    252     /// object.
    253     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
    254       PathEntry Entry;
    255       APValue::BaseOrMemberType Value(D, Virtual);
    256       Entry.BaseOrMember = Value.getOpaqueValue();
    257       Entries.push_back(Entry);
    258 
    259       // If this isn't a base class, it's a new most-derived object.
    260       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
    261         MostDerivedType = FD->getType();
    262         MostDerivedIsArrayElement = false;
    263         MostDerivedArraySize = 0;
    264         MostDerivedPathLength = Entries.size();
    265       }
    266     }
    267     /// Update this designator to refer to the given complex component.
    268     void addComplexUnchecked(QualType EltTy, bool Imag) {
    269       PathEntry Entry;
    270       Entry.ArrayIndex = Imag;
    271       Entries.push_back(Entry);
    272 
    273       // This is technically a most-derived object, though in practice this
    274       // is unlikely to matter.
    275       MostDerivedType = EltTy;
    276       MostDerivedIsArrayElement = true;
    277       MostDerivedArraySize = 2;
    278       MostDerivedPathLength = Entries.size();
    279     }
    280     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
    281     /// Add N to the address of this subobject.
    282     void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
    283       if (Invalid) return;
    284       if (MostDerivedPathLength == Entries.size() &&
    285           MostDerivedIsArrayElement) {
    286         Entries.back().ArrayIndex += N;
    287         if (Entries.back().ArrayIndex > MostDerivedArraySize) {
    288           diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
    289           setInvalid();
    290         }
    291         return;
    292       }
    293       // [expr.add]p4: For the purposes of these operators, a pointer to a
    294       // nonarray object behaves the same as a pointer to the first element of
    295       // an array of length one with the type of the object as its element type.
    296       if (IsOnePastTheEnd && N == (uint64_t)-1)
    297         IsOnePastTheEnd = false;
    298       else if (!IsOnePastTheEnd && N == 1)
    299         IsOnePastTheEnd = true;
    300       else if (N != 0) {
    301         diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
    302         setInvalid();
    303       }
    304     }
    305   };
    306 
    307   /// A stack frame in the constexpr call stack.
    308   struct CallStackFrame {
    309     EvalInfo &Info;
    310 
    311     /// Parent - The caller of this stack frame.
    312     CallStackFrame *Caller;
    313 
    314     /// CallLoc - The location of the call expression for this call.
    315     SourceLocation CallLoc;
    316 
    317     /// Callee - The function which was called.
    318     const FunctionDecl *Callee;
    319 
    320     /// Index - The call index of this call.
    321     unsigned Index;
    322 
    323     /// This - The binding for the this pointer in this call, if any.
    324     const LValue *This;
    325 
    326     /// Arguments - Parameter bindings for this function call, indexed by
    327     /// parameters' function scope indices.
    328     APValue *Arguments;
    329 
    330     // Note that we intentionally use std::map here so that references to
    331     // values are stable.
    332     typedef std::map<const void*, APValue> MapTy;
    333     typedef MapTy::const_iterator temp_iterator;
    334     /// Temporaries - Temporary lvalues materialized within this stack frame.
    335     MapTy Temporaries;
    336 
    337     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
    338                    const FunctionDecl *Callee, const LValue *This,
    339                    APValue *Arguments);
    340     ~CallStackFrame();
    341 
    342     APValue *getTemporary(const void *Key) {
    343       MapTy::iterator I = Temporaries.find(Key);
    344       return I == Temporaries.end() ? nullptr : &I->second;
    345     }
    346     APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
    347   };
    348 
    349   /// Temporarily override 'this'.
    350   class ThisOverrideRAII {
    351   public:
    352     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
    353         : Frame(Frame), OldThis(Frame.This) {
    354       if (Enable)
    355         Frame.This = NewThis;
    356     }
    357     ~ThisOverrideRAII() {
    358       Frame.This = OldThis;
    359     }
    360   private:
    361     CallStackFrame &Frame;
    362     const LValue *OldThis;
    363   };
    364 
    365   /// A partial diagnostic which we might know in advance that we are not going
    366   /// to emit.
    367   class OptionalDiagnostic {
    368     PartialDiagnostic *Diag;
    369 
    370   public:
    371     explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
    372       : Diag(Diag) {}
    373 
    374     template<typename T>
    375     OptionalDiagnostic &operator<<(const T &v) {
    376       if (Diag)
    377         *Diag << v;
    378       return *this;
    379     }
    380 
    381     OptionalDiagnostic &operator<<(const APSInt &I) {
    382       if (Diag) {
    383         SmallVector<char, 32> Buffer;
    384         I.toString(Buffer);
    385         *Diag << StringRef(Buffer.data(), Buffer.size());
    386       }
    387       return *this;
    388     }
    389 
    390     OptionalDiagnostic &operator<<(const APFloat &F) {
    391       if (Diag) {
    392         // FIXME: Force the precision of the source value down so we don't
    393         // print digits which are usually useless (we don't really care here if
    394         // we truncate a digit by accident in edge cases).  Ideally,
    395         // APFloat::toString would automatically print the shortest
    396         // representation which rounds to the correct value, but it's a bit
    397         // tricky to implement.
    398         unsigned precision =
    399             llvm::APFloat::semanticsPrecision(F.getSemantics());
    400         precision = (precision * 59 + 195) / 196;
    401         SmallVector<char, 32> Buffer;
    402         F.toString(Buffer, precision);
    403         *Diag << StringRef(Buffer.data(), Buffer.size());
    404       }
    405       return *this;
    406     }
    407   };
    408 
    409   /// A cleanup, and a flag indicating whether it is lifetime-extended.
    410   class Cleanup {
    411     llvm::PointerIntPair<APValue*, 1, bool> Value;
    412 
    413   public:
    414     Cleanup(APValue *Val, bool IsLifetimeExtended)
    415         : Value(Val, IsLifetimeExtended) {}
    416 
    417     bool isLifetimeExtended() const { return Value.getInt(); }
    418     void endLifetime() {
    419       *Value.getPointer() = APValue();
    420     }
    421   };
    422 
    423   /// EvalInfo - This is a private struct used by the evaluator to capture
    424   /// information about a subexpression as it is folded.  It retains information
    425   /// about the AST context, but also maintains information about the folded
    426   /// expression.
    427   ///
    428   /// If an expression could be evaluated, it is still possible it is not a C
    429   /// "integer constant expression" or constant expression.  If not, this struct
    430   /// captures information about how and why not.
    431   ///
    432   /// One bit of information passed *into* the request for constant folding
    433   /// indicates whether the subexpression is "evaluated" or not according to C
    434   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
    435   /// evaluate the expression regardless of what the RHS is, but C only allows
    436   /// certain things in certain situations.
    437   struct EvalInfo {
    438     ASTContext &Ctx;
    439 
    440     /// EvalStatus - Contains information about the evaluation.
    441     Expr::EvalStatus &EvalStatus;
    442 
    443     /// CurrentCall - The top of the constexpr call stack.
    444     CallStackFrame *CurrentCall;
    445 
    446     /// CallStackDepth - The number of calls in the call stack right now.
    447     unsigned CallStackDepth;
    448 
    449     /// NextCallIndex - The next call index to assign.
    450     unsigned NextCallIndex;
    451 
    452     /// StepsLeft - The remaining number of evaluation steps we're permitted
    453     /// to perform. This is essentially a limit for the number of statements
    454     /// we will evaluate.
    455     unsigned StepsLeft;
    456 
    457     /// BottomFrame - The frame in which evaluation started. This must be
    458     /// initialized after CurrentCall and CallStackDepth.
    459     CallStackFrame BottomFrame;
    460 
    461     /// A stack of values whose lifetimes end at the end of some surrounding
    462     /// evaluation frame.
    463     llvm::SmallVector<Cleanup, 16> CleanupStack;
    464 
    465     /// EvaluatingDecl - This is the declaration whose initializer is being
    466     /// evaluated, if any.
    467     APValue::LValueBase EvaluatingDecl;
    468 
    469     /// EvaluatingDeclValue - This is the value being constructed for the
    470     /// declaration whose initializer is being evaluated, if any.
    471     APValue *EvaluatingDeclValue;
    472 
    473     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
    474     /// notes attached to it will also be stored, otherwise they will not be.
    475     bool HasActiveDiagnostic;
    476 
    477     /// \brief Have we emitted a diagnostic explaining why we couldn't constant
    478     /// fold (not just why it's not strictly a constant expression)?
    479     bool HasFoldFailureDiagnostic;
    480 
    481     /// \brief Whether or not we're currently speculatively evaluating.
    482     bool IsSpeculativelyEvaluating;
    483 
    484     enum EvaluationMode {
    485       /// Evaluate as a constant expression. Stop if we find that the expression
    486       /// is not a constant expression.
    487       EM_ConstantExpression,
    488 
    489       /// Evaluate as a potential constant expression. Keep going if we hit a
    490       /// construct that we can't evaluate yet (because we don't yet know the
    491       /// value of something) but stop if we hit something that could never be
    492       /// a constant expression.
    493       EM_PotentialConstantExpression,
    494 
    495       /// Fold the expression to a constant. Stop if we hit a side-effect that
    496       /// we can't model.
    497       EM_ConstantFold,
    498 
    499       /// Evaluate the expression looking for integer overflow and similar
    500       /// issues. Don't worry about side-effects, and try to visit all
    501       /// subexpressions.
    502       EM_EvaluateForOverflow,
    503 
    504       /// Evaluate in any way we know how. Don't worry about side-effects that
    505       /// can't be modeled.
    506       EM_IgnoreSideEffects,
    507 
    508       /// Evaluate as a constant expression. Stop if we find that the expression
    509       /// is not a constant expression. Some expressions can be retried in the
    510       /// optimizer if we don't constant fold them here, but in an unevaluated
    511       /// context we try to fold them immediately since the optimizer never
    512       /// gets a chance to look at it.
    513       EM_ConstantExpressionUnevaluated,
    514 
    515       /// Evaluate as a potential constant expression. Keep going if we hit a
    516       /// construct that we can't evaluate yet (because we don't yet know the
    517       /// value of something) but stop if we hit something that could never be
    518       /// a constant expression. Some expressions can be retried in the
    519       /// optimizer if we don't constant fold them here, but in an unevaluated
    520       /// context we try to fold them immediately since the optimizer never
    521       /// gets a chance to look at it.
    522       EM_PotentialConstantExpressionUnevaluated,
    523 
    524       /// Evaluate as a constant expression. Continue evaluating if we find a
    525       /// MemberExpr with a base that can't be evaluated.
    526       EM_DesignatorFold,
    527     } EvalMode;
    528 
    529     /// Are we checking whether the expression is a potential constant
    530     /// expression?
    531     bool checkingPotentialConstantExpression() const {
    532       return EvalMode == EM_PotentialConstantExpression ||
    533              EvalMode == EM_PotentialConstantExpressionUnevaluated;
    534     }
    535 
    536     /// Are we checking an expression for overflow?
    537     // FIXME: We should check for any kind of undefined or suspicious behavior
    538     // in such constructs, not just overflow.
    539     bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
    540 
    541     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
    542       : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
    543         CallStackDepth(0), NextCallIndex(1),
    544         StepsLeft(getLangOpts().ConstexprStepLimit),
    545         BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
    546         EvaluatingDecl((const ValueDecl *)nullptr),
    547         EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
    548         HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
    549         EvalMode(Mode) {}
    550 
    551     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
    552       EvaluatingDecl = Base;
    553       EvaluatingDeclValue = &Value;
    554     }
    555 
    556     const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
    557 
    558     bool CheckCallLimit(SourceLocation Loc) {
    559       // Don't perform any constexpr calls (other than the call we're checking)
    560       // when checking a potential constant expression.
    561       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
    562         return false;
    563       if (NextCallIndex == 0) {
    564         // NextCallIndex has wrapped around.
    565         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
    566         return false;
    567       }
    568       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
    569         return true;
    570       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
    571         << getLangOpts().ConstexprCallDepth;
    572       return false;
    573     }
    574 
    575     CallStackFrame *getCallFrame(unsigned CallIndex) {
    576       assert(CallIndex && "no call index in getCallFrame");
    577       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
    578       // be null in this loop.
    579       CallStackFrame *Frame = CurrentCall;
    580       while (Frame->Index > CallIndex)
    581         Frame = Frame->Caller;
    582       return (Frame->Index == CallIndex) ? Frame : nullptr;
    583     }
    584 
    585     bool nextStep(const Stmt *S) {
    586       if (!StepsLeft) {
    587         FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
    588         return false;
    589       }
    590       --StepsLeft;
    591       return true;
    592     }
    593 
    594   private:
    595     /// Add a diagnostic to the diagnostics list.
    596     PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
    597       PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
    598       EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
    599       return EvalStatus.Diag->back().second;
    600     }
    601 
    602     /// Add notes containing a call stack to the current point of evaluation.
    603     void addCallStack(unsigned Limit);
    604 
    605   private:
    606     OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
    607                             unsigned ExtraNotes, bool IsCCEDiag) {
    608 
    609       if (EvalStatus.Diag) {
    610         // If we have a prior diagnostic, it will be noting that the expression
    611         // isn't a constant expression. This diagnostic is more important,
    612         // unless we require this evaluation to produce a constant expression.
    613         //
    614         // FIXME: We might want to show both diagnostics to the user in
    615         // EM_ConstantFold mode.
    616         if (!EvalStatus.Diag->empty()) {
    617           switch (EvalMode) {
    618           case EM_ConstantFold:
    619           case EM_IgnoreSideEffects:
    620           case EM_EvaluateForOverflow:
    621             if (!HasFoldFailureDiagnostic)
    622               break;
    623             // We've already failed to fold something. Keep that diagnostic.
    624           case EM_ConstantExpression:
    625           case EM_PotentialConstantExpression:
    626           case EM_ConstantExpressionUnevaluated:
    627           case EM_PotentialConstantExpressionUnevaluated:
    628           case EM_DesignatorFold:
    629             HasActiveDiagnostic = false;
    630             return OptionalDiagnostic();
    631           }
    632         }
    633 
    634         unsigned CallStackNotes = CallStackDepth - 1;
    635         unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
    636         if (Limit)
    637           CallStackNotes = std::min(CallStackNotes, Limit + 1);
    638         if (checkingPotentialConstantExpression())
    639           CallStackNotes = 0;
    640 
    641         HasActiveDiagnostic = true;
    642         HasFoldFailureDiagnostic = !IsCCEDiag;
    643         EvalStatus.Diag->clear();
    644         EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
    645         addDiag(Loc, DiagId);
    646         if (!checkingPotentialConstantExpression())
    647           addCallStack(Limit);
    648         return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
    649       }
    650       HasActiveDiagnostic = false;
    651       return OptionalDiagnostic();
    652     }
    653   public:
    654     // Diagnose that the evaluation could not be folded (FF => FoldFailure)
    655     OptionalDiagnostic
    656     FFDiag(SourceLocation Loc,
    657           diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
    658           unsigned ExtraNotes = 0) {
    659       return Diag(Loc, DiagId, ExtraNotes, false);
    660     }
    661 
    662     OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
    663                               = diag::note_invalid_subexpr_in_const_expr,
    664                             unsigned ExtraNotes = 0) {
    665       if (EvalStatus.Diag)
    666         return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
    667       HasActiveDiagnostic = false;
    668       return OptionalDiagnostic();
    669     }
    670 
    671     /// Diagnose that the evaluation does not produce a C++11 core constant
    672     /// expression.
    673     ///
    674     /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
    675     /// EM_PotentialConstantExpression mode and we produce one of these.
    676     OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
    677                                  = diag::note_invalid_subexpr_in_const_expr,
    678                                unsigned ExtraNotes = 0) {
    679       // Don't override a previous diagnostic. Don't bother collecting
    680       // diagnostics if we're evaluating for overflow.
    681       if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
    682         HasActiveDiagnostic = false;
    683         return OptionalDiagnostic();
    684       }
    685       return Diag(Loc, DiagId, ExtraNotes, true);
    686     }
    687     OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
    688                                  = diag::note_invalid_subexpr_in_const_expr,
    689                                unsigned ExtraNotes = 0) {
    690       return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
    691     }
    692     /// Add a note to a prior diagnostic.
    693     OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
    694       if (!HasActiveDiagnostic)
    695         return OptionalDiagnostic();
    696       return OptionalDiagnostic(&addDiag(Loc, DiagId));
    697     }
    698 
    699     /// Add a stack of notes to a prior diagnostic.
    700     void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
    701       if (HasActiveDiagnostic) {
    702         EvalStatus.Diag->insert(EvalStatus.Diag->end(),
    703                                 Diags.begin(), Diags.end());
    704       }
    705     }
    706 
    707     /// Should we continue evaluation after encountering a side-effect that we
    708     /// couldn't model?
    709     bool keepEvaluatingAfterSideEffect() {
    710       switch (EvalMode) {
    711       case EM_PotentialConstantExpression:
    712       case EM_PotentialConstantExpressionUnevaluated:
    713       case EM_EvaluateForOverflow:
    714       case EM_IgnoreSideEffects:
    715         return true;
    716 
    717       case EM_ConstantExpression:
    718       case EM_ConstantExpressionUnevaluated:
    719       case EM_ConstantFold:
    720       case EM_DesignatorFold:
    721         return false;
    722       }
    723       llvm_unreachable("Missed EvalMode case");
    724     }
    725 
    726     /// Note that we have had a side-effect, and determine whether we should
    727     /// keep evaluating.
    728     bool noteSideEffect() {
    729       EvalStatus.HasSideEffects = true;
    730       return keepEvaluatingAfterSideEffect();
    731     }
    732 
    733     /// Should we continue evaluation after encountering undefined behavior?
    734     bool keepEvaluatingAfterUndefinedBehavior() {
    735       switch (EvalMode) {
    736       case EM_EvaluateForOverflow:
    737       case EM_IgnoreSideEffects:
    738       case EM_ConstantFold:
    739       case EM_DesignatorFold:
    740         return true;
    741 
    742       case EM_PotentialConstantExpression:
    743       case EM_PotentialConstantExpressionUnevaluated:
    744       case EM_ConstantExpression:
    745       case EM_ConstantExpressionUnevaluated:
    746         return false;
    747       }
    748       llvm_unreachable("Missed EvalMode case");
    749     }
    750 
    751     /// Note that we hit something that was technically undefined behavior, but
    752     /// that we can evaluate past it (such as signed overflow or floating-point
    753     /// division by zero.)
    754     bool noteUndefinedBehavior() {
    755       EvalStatus.HasUndefinedBehavior = true;
    756       return keepEvaluatingAfterUndefinedBehavior();
    757     }
    758 
    759     /// Should we continue evaluation as much as possible after encountering a
    760     /// construct which can't be reduced to a value?
    761     bool keepEvaluatingAfterFailure() {
    762       if (!StepsLeft)
    763         return false;
    764 
    765       switch (EvalMode) {
    766       case EM_PotentialConstantExpression:
    767       case EM_PotentialConstantExpressionUnevaluated:
    768       case EM_EvaluateForOverflow:
    769         return true;
    770 
    771       case EM_ConstantExpression:
    772       case EM_ConstantExpressionUnevaluated:
    773       case EM_ConstantFold:
    774       case EM_IgnoreSideEffects:
    775       case EM_DesignatorFold:
    776         return false;
    777       }
    778       llvm_unreachable("Missed EvalMode case");
    779     }
    780 
    781     /// Notes that we failed to evaluate an expression that other expressions
    782     /// directly depend on, and determine if we should keep evaluating. This
    783     /// should only be called if we actually intend to keep evaluating.
    784     ///
    785     /// Call noteSideEffect() instead if we may be able to ignore the value that
    786     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
    787     ///
    788     /// (Foo(), 1)      // use noteSideEffect
    789     /// (Foo() || true) // use noteSideEffect
    790     /// Foo() + 1       // use noteFailure
    791     LLVM_ATTRIBUTE_UNUSED_RESULT bool noteFailure() {
    792       // Failure when evaluating some expression often means there is some
    793       // subexpression whose evaluation was skipped. Therefore, (because we
    794       // don't track whether we skipped an expression when unwinding after an
    795       // evaluation failure) every evaluation failure that bubbles up from a
    796       // subexpression implies that a side-effect has potentially happened. We
    797       // skip setting the HasSideEffects flag to true until we decide to
    798       // continue evaluating after that point, which happens here.
    799       bool KeepGoing = keepEvaluatingAfterFailure();
    800       EvalStatus.HasSideEffects |= KeepGoing;
    801       return KeepGoing;
    802     }
    803 
    804     bool allowInvalidBaseExpr() const {
    805       return EvalMode == EM_DesignatorFold;
    806     }
    807   };
    808 
    809   /// Object used to treat all foldable expressions as constant expressions.
    810   struct FoldConstant {
    811     EvalInfo &Info;
    812     bool Enabled;
    813     bool HadNoPriorDiags;
    814     EvalInfo::EvaluationMode OldMode;
    815 
    816     explicit FoldConstant(EvalInfo &Info, bool Enabled)
    817       : Info(Info),
    818         Enabled(Enabled),
    819         HadNoPriorDiags(Info.EvalStatus.Diag &&
    820                         Info.EvalStatus.Diag->empty() &&
    821                         !Info.EvalStatus.HasSideEffects),
    822         OldMode(Info.EvalMode) {
    823       if (Enabled &&
    824           (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
    825            Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
    826         Info.EvalMode = EvalInfo::EM_ConstantFold;
    827     }
    828     void keepDiagnostics() { Enabled = false; }
    829     ~FoldConstant() {
    830       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
    831           !Info.EvalStatus.HasSideEffects)
    832         Info.EvalStatus.Diag->clear();
    833       Info.EvalMode = OldMode;
    834     }
    835   };
    836 
    837   /// RAII object used to treat the current evaluation as the correct pointer
    838   /// offset fold for the current EvalMode
    839   struct FoldOffsetRAII {
    840     EvalInfo &Info;
    841     EvalInfo::EvaluationMode OldMode;
    842     explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject)
    843         : Info(Info), OldMode(Info.EvalMode) {
    844       if (!Info.checkingPotentialConstantExpression())
    845         Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold
    846                                   : EvalInfo::EM_ConstantFold;
    847     }
    848 
    849     ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
    850   };
    851 
    852   /// RAII object used to optionally suppress diagnostics and side-effects from
    853   /// a speculative evaluation.
    854   class SpeculativeEvaluationRAII {
    855     /// Pair of EvalInfo, and a bit that stores whether or not we were
    856     /// speculatively evaluating when we created this RAII.
    857     llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
    858     Expr::EvalStatus Old;
    859 
    860     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
    861       InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
    862       Old = Other.Old;
    863       Other.InfoAndOldSpecEval.setPointer(nullptr);
    864     }
    865 
    866     void maybeRestoreState() {
    867       EvalInfo *Info = InfoAndOldSpecEval.getPointer();
    868       if (!Info)
    869         return;
    870 
    871       Info->EvalStatus = Old;
    872       Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
    873     }
    874 
    875   public:
    876     SpeculativeEvaluationRAII() = default;
    877 
    878     SpeculativeEvaluationRAII(
    879         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
    880         : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
    881           Old(Info.EvalStatus) {
    882       Info.EvalStatus.Diag = NewDiag;
    883       Info.IsSpeculativelyEvaluating = true;
    884     }
    885 
    886     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
    887     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
    888       moveFromAndCancel(std::move(Other));
    889     }
    890 
    891     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
    892       maybeRestoreState();
    893       moveFromAndCancel(std::move(Other));
    894       return *this;
    895     }
    896 
    897     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
    898   };
    899 
    900   /// RAII object wrapping a full-expression or block scope, and handling
    901   /// the ending of the lifetime of temporaries created within it.
    902   template<bool IsFullExpression>
    903   class ScopeRAII {
    904     EvalInfo &Info;
    905     unsigned OldStackSize;
    906   public:
    907     ScopeRAII(EvalInfo &Info)
    908         : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
    909     ~ScopeRAII() {
    910       // Body moved to a static method to encourage the compiler to inline away
    911       // instances of this class.
    912       cleanup(Info, OldStackSize);
    913     }
    914   private:
    915     static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
    916       unsigned NewEnd = OldStackSize;
    917       for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
    918            I != N; ++I) {
    919         if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
    920           // Full-expression cleanup of a lifetime-extended temporary: nothing
    921           // to do, just move this cleanup to the right place in the stack.
    922           std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
    923           ++NewEnd;
    924         } else {
    925           // End the lifetime of the object.
    926           Info.CleanupStack[I].endLifetime();
    927         }
    928       }
    929       Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
    930                               Info.CleanupStack.end());
    931     }
    932   };
    933   typedef ScopeRAII<false> BlockScopeRAII;
    934   typedef ScopeRAII<true> FullExpressionRAII;
    935 }
    936 
    937 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
    938                                          CheckSubobjectKind CSK) {
    939   if (Invalid)
    940     return false;
    941   if (isOnePastTheEnd()) {
    942     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
    943       << CSK;
    944     setInvalid();
    945     return false;
    946   }
    947   return true;
    948 }
    949 
    950 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
    951                                                     const Expr *E, uint64_t N) {
    952   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
    953     Info.CCEDiag(E, diag::note_constexpr_array_index)
    954       << static_cast<int>(N) << /*array*/ 0
    955       << static_cast<unsigned>(MostDerivedArraySize);
    956   else
    957     Info.CCEDiag(E, diag::note_constexpr_array_index)
    958       << static_cast<int>(N) << /*non-array*/ 1;
    959   setInvalid();
    960 }
    961 
    962 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
    963                                const FunctionDecl *Callee, const LValue *This,
    964                                APValue *Arguments)
    965     : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
    966       Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
    967   Info.CurrentCall = this;
    968   ++Info.CallStackDepth;
    969 }
    970 
    971 CallStackFrame::~CallStackFrame() {
    972   assert(Info.CurrentCall == this && "calls retired out of order");
    973   --Info.CallStackDepth;
    974   Info.CurrentCall = Caller;
    975 }
    976 
    977 APValue &CallStackFrame::createTemporary(const void *Key,
    978                                          bool IsLifetimeExtended) {
    979   APValue &Result = Temporaries[Key];
    980   assert(Result.isUninit() && "temporary created multiple times");
    981   Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
    982   return Result;
    983 }
    984 
    985 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
    986 
    987 void EvalInfo::addCallStack(unsigned Limit) {
    988   // Determine which calls to skip, if any.
    989   unsigned ActiveCalls = CallStackDepth - 1;
    990   unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
    991   if (Limit && Limit < ActiveCalls) {
    992     SkipStart = Limit / 2 + Limit % 2;
    993     SkipEnd = ActiveCalls - Limit / 2;
    994   }
    995 
    996   // Walk the call stack and add the diagnostics.
    997   unsigned CallIdx = 0;
    998   for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
    999        Frame = Frame->Caller, ++CallIdx) {
   1000     // Skip this call?
   1001     if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
   1002       if (CallIdx == SkipStart) {
   1003         // Note that we're skipping calls.
   1004         addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
   1005           << unsigned(ActiveCalls - Limit);
   1006       }
   1007       continue;
   1008     }
   1009 
   1010     // Use a different note for an inheriting constructor, because from the
   1011     // user's perspective it's not really a function at all.
   1012     if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
   1013       if (CD->isInheritingConstructor()) {
   1014         addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
   1015           << CD->getParent();
   1016         continue;
   1017       }
   1018     }
   1019 
   1020     SmallVector<char, 128> Buffer;
   1021     llvm::raw_svector_ostream Out(Buffer);
   1022     describeCall(Frame, Out);
   1023     addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
   1024   }
   1025 }
   1026 
   1027 namespace {
   1028   struct ComplexValue {
   1029   private:
   1030     bool IsInt;
   1031 
   1032   public:
   1033     APSInt IntReal, IntImag;
   1034     APFloat FloatReal, FloatImag;
   1035 
   1036     ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
   1037 
   1038     void makeComplexFloat() { IsInt = false; }
   1039     bool isComplexFloat() const { return !IsInt; }
   1040     APFloat &getComplexFloatReal() { return FloatReal; }
   1041     APFloat &getComplexFloatImag() { return FloatImag; }
   1042 
   1043     void makeComplexInt() { IsInt = true; }
   1044     bool isComplexInt() const { return IsInt; }
   1045     APSInt &getComplexIntReal() { return IntReal; }
   1046     APSInt &getComplexIntImag() { return IntImag; }
   1047 
   1048     void moveInto(APValue &v) const {
   1049       if (isComplexFloat())
   1050         v = APValue(FloatReal, FloatImag);
   1051       else
   1052         v = APValue(IntReal, IntImag);
   1053     }
   1054     void setFrom(const APValue &v) {
   1055       assert(v.isComplexFloat() || v.isComplexInt());
   1056       if (v.isComplexFloat()) {
   1057         makeComplexFloat();
   1058         FloatReal = v.getComplexFloatReal();
   1059         FloatImag = v.getComplexFloatImag();
   1060       } else {
   1061         makeComplexInt();
   1062         IntReal = v.getComplexIntReal();
   1063         IntImag = v.getComplexIntImag();
   1064       }
   1065     }
   1066   };
   1067 
   1068   struct LValue {
   1069     APValue::LValueBase Base;
   1070     CharUnits Offset;
   1071     unsigned InvalidBase : 1;
   1072     unsigned CallIndex : 31;
   1073     SubobjectDesignator Designator;
   1074 
   1075     const APValue::LValueBase getLValueBase() const { return Base; }
   1076     CharUnits &getLValueOffset() { return Offset; }
   1077     const CharUnits &getLValueOffset() const { return Offset; }
   1078     unsigned getLValueCallIndex() const { return CallIndex; }
   1079     SubobjectDesignator &getLValueDesignator() { return Designator; }
   1080     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
   1081 
   1082     void moveInto(APValue &V) const {
   1083       if (Designator.Invalid)
   1084         V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
   1085       else
   1086         V = APValue(Base, Offset, Designator.Entries,
   1087                     Designator.IsOnePastTheEnd, CallIndex);
   1088     }
   1089     void setFrom(ASTContext &Ctx, const APValue &V) {
   1090       assert(V.isLValue());
   1091       Base = V.getLValueBase();
   1092       Offset = V.getLValueOffset();
   1093       InvalidBase = false;
   1094       CallIndex = V.getLValueCallIndex();
   1095       Designator = SubobjectDesignator(Ctx, V);
   1096     }
   1097 
   1098     void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
   1099       Base = B;
   1100       Offset = CharUnits::Zero();
   1101       InvalidBase = BInvalid;
   1102       CallIndex = I;
   1103       Designator = SubobjectDesignator(getType(B));
   1104     }
   1105 
   1106     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
   1107       set(B, I, true);
   1108     }
   1109 
   1110     // Check that this LValue is not based on a null pointer. If it is, produce
   1111     // a diagnostic and mark the designator as invalid.
   1112     bool checkNullPointer(EvalInfo &Info, const Expr *E,
   1113                           CheckSubobjectKind CSK) {
   1114       if (Designator.Invalid)
   1115         return false;
   1116       if (!Base) {
   1117         Info.CCEDiag(E, diag::note_constexpr_null_subobject)
   1118           << CSK;
   1119         Designator.setInvalid();
   1120         return false;
   1121       }
   1122       return true;
   1123     }
   1124 
   1125     // Check this LValue refers to an object. If not, set the designator to be
   1126     // invalid and emit a diagnostic.
   1127     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
   1128       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
   1129              Designator.checkSubobject(Info, E, CSK);
   1130     }
   1131 
   1132     void addDecl(EvalInfo &Info, const Expr *E,
   1133                  const Decl *D, bool Virtual = false) {
   1134       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
   1135         Designator.addDeclUnchecked(D, Virtual);
   1136     }
   1137     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
   1138       if (checkSubobject(Info, E, CSK_ArrayToPointer))
   1139         Designator.addArrayUnchecked(CAT);
   1140     }
   1141     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
   1142       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
   1143         Designator.addComplexUnchecked(EltTy, Imag);
   1144     }
   1145     void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
   1146       if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
   1147         Designator.adjustIndex(Info, E, N);
   1148     }
   1149   };
   1150 
   1151   struct MemberPtr {
   1152     MemberPtr() {}
   1153     explicit MemberPtr(const ValueDecl *Decl) :
   1154       DeclAndIsDerivedMember(Decl, false), Path() {}
   1155 
   1156     /// The member or (direct or indirect) field referred to by this member
   1157     /// pointer, or 0 if this is a null member pointer.
   1158     const ValueDecl *getDecl() const {
   1159       return DeclAndIsDerivedMember.getPointer();
   1160     }
   1161     /// Is this actually a member of some type derived from the relevant class?
   1162     bool isDerivedMember() const {
   1163       return DeclAndIsDerivedMember.getInt();
   1164     }
   1165     /// Get the class which the declaration actually lives in.
   1166     const CXXRecordDecl *getContainingRecord() const {
   1167       return cast<CXXRecordDecl>(
   1168           DeclAndIsDerivedMember.getPointer()->getDeclContext());
   1169     }
   1170 
   1171     void moveInto(APValue &V) const {
   1172       V = APValue(getDecl(), isDerivedMember(), Path);
   1173     }
   1174     void setFrom(const APValue &V) {
   1175       assert(V.isMemberPointer());
   1176       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
   1177       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
   1178       Path.clear();
   1179       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
   1180       Path.insert(Path.end(), P.begin(), P.end());
   1181     }
   1182 
   1183     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
   1184     /// whether the member is a member of some class derived from the class type
   1185     /// of the member pointer.
   1186     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
   1187     /// Path - The path of base/derived classes from the member declaration's
   1188     /// class (exclusive) to the class type of the member pointer (inclusive).
   1189     SmallVector<const CXXRecordDecl*, 4> Path;
   1190 
   1191     /// Perform a cast towards the class of the Decl (either up or down the
   1192     /// hierarchy).
   1193     bool castBack(const CXXRecordDecl *Class) {
   1194       assert(!Path.empty());
   1195       const CXXRecordDecl *Expected;
   1196       if (Path.size() >= 2)
   1197         Expected = Path[Path.size() - 2];
   1198       else
   1199         Expected = getContainingRecord();
   1200       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
   1201         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
   1202         // if B does not contain the original member and is not a base or
   1203         // derived class of the class containing the original member, the result
   1204         // of the cast is undefined.
   1205         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
   1206         // (D::*). We consider that to be a language defect.
   1207         return false;
   1208       }
   1209       Path.pop_back();
   1210       return true;
   1211     }
   1212     /// Perform a base-to-derived member pointer cast.
   1213     bool castToDerived(const CXXRecordDecl *Derived) {
   1214       if (!getDecl())
   1215         return true;
   1216       if (!isDerivedMember()) {
   1217         Path.push_back(Derived);
   1218         return true;
   1219       }
   1220       if (!castBack(Derived))
   1221         return false;
   1222       if (Path.empty())
   1223         DeclAndIsDerivedMember.setInt(false);
   1224       return true;
   1225     }
   1226     /// Perform a derived-to-base member pointer cast.
   1227     bool castToBase(const CXXRecordDecl *Base) {
   1228       if (!getDecl())
   1229         return true;
   1230       if (Path.empty())
   1231         DeclAndIsDerivedMember.setInt(true);
   1232       if (isDerivedMember()) {
   1233         Path.push_back(Base);
   1234         return true;
   1235       }
   1236       return castBack(Base);
   1237     }
   1238   };
   1239 
   1240   /// Compare two member pointers, which are assumed to be of the same type.
   1241   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
   1242     if (!LHS.getDecl() || !RHS.getDecl())
   1243       return !LHS.getDecl() && !RHS.getDecl();
   1244     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
   1245       return false;
   1246     return LHS.Path == RHS.Path;
   1247   }
   1248 }
   1249 
   1250 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
   1251 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
   1252                             const LValue &This, const Expr *E,
   1253                             bool AllowNonLiteralTypes = false);
   1254 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
   1255 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
   1256 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
   1257                                   EvalInfo &Info);
   1258 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
   1259 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
   1260 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
   1261                                     EvalInfo &Info);
   1262 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
   1263 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
   1264 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
   1265 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
   1266 
   1267 //===----------------------------------------------------------------------===//
   1268 // Misc utilities
   1269 //===----------------------------------------------------------------------===//
   1270 
   1271 /// Produce a string describing the given constexpr call.
   1272 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
   1273   unsigned ArgIndex = 0;
   1274   bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
   1275                       !isa<CXXConstructorDecl>(Frame->Callee) &&
   1276                       cast<CXXMethodDecl>(Frame->Callee)->isInstance();
   1277 
   1278   if (!IsMemberCall)
   1279     Out << *Frame->Callee << '(';
   1280 
   1281   if (Frame->This && IsMemberCall) {
   1282     APValue Val;
   1283     Frame->This->moveInto(Val);
   1284     Val.printPretty(Out, Frame->Info.Ctx,
   1285                     Frame->This->Designator.MostDerivedType);
   1286     // FIXME: Add parens around Val if needed.
   1287     Out << "->" << *Frame->Callee << '(';
   1288     IsMemberCall = false;
   1289   }
   1290 
   1291   for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
   1292        E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
   1293     if (ArgIndex > (unsigned)IsMemberCall)
   1294       Out << ", ";
   1295 
   1296     const ParmVarDecl *Param = *I;
   1297     const APValue &Arg = Frame->Arguments[ArgIndex];
   1298     Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
   1299 
   1300     if (ArgIndex == 0 && IsMemberCall)
   1301       Out << "->" << *Frame->Callee << '(';
   1302   }
   1303 
   1304   Out << ')';
   1305 }
   1306 
   1307 /// Evaluate an expression to see if it had side-effects, and discard its
   1308 /// result.
   1309 /// \return \c true if the caller should keep evaluating.
   1310 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
   1311   APValue Scratch;
   1312   if (!Evaluate(Scratch, Info, E))
   1313     // We don't need the value, but we might have skipped a side effect here.
   1314     return Info.noteSideEffect();
   1315   return true;
   1316 }
   1317 
   1318 /// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
   1319 /// return its existing value.
   1320 static int64_t getExtValue(const APSInt &Value) {
   1321   return Value.isSigned() ? Value.getSExtValue()
   1322                           : static_cast<int64_t>(Value.getZExtValue());
   1323 }
   1324 
   1325 /// Should this call expression be treated as a string literal?
   1326 static bool IsStringLiteralCall(const CallExpr *E) {
   1327   unsigned Builtin = E->getBuiltinCallee();
   1328   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
   1329           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
   1330 }
   1331 
   1332 static bool IsGlobalLValue(APValue::LValueBase B) {
   1333   // C++11 [expr.const]p3 An address constant expression is a prvalue core
   1334   // constant expression of pointer type that evaluates to...
   1335 
   1336   // ... a null pointer value, or a prvalue core constant expression of type
   1337   // std::nullptr_t.
   1338   if (!B) return true;
   1339 
   1340   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
   1341     // ... the address of an object with static storage duration,
   1342     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
   1343       return VD->hasGlobalStorage();
   1344     // ... the address of a function,
   1345     return isa<FunctionDecl>(D);
   1346   }
   1347 
   1348   const Expr *E = B.get<const Expr*>();
   1349   switch (E->getStmtClass()) {
   1350   default:
   1351     return false;
   1352   case Expr::CompoundLiteralExprClass: {
   1353     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
   1354     return CLE->isFileScope() && CLE->isLValue();
   1355   }
   1356   case Expr::MaterializeTemporaryExprClass:
   1357     // A materialized temporary might have been lifetime-extended to static
   1358     // storage duration.
   1359     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
   1360   // A string literal has static storage duration.
   1361   case Expr::StringLiteralClass:
   1362   case Expr::PredefinedExprClass:
   1363   case Expr::ObjCStringLiteralClass:
   1364   case Expr::ObjCEncodeExprClass:
   1365   case Expr::CXXTypeidExprClass:
   1366   case Expr::CXXUuidofExprClass:
   1367     return true;
   1368   case Expr::CallExprClass:
   1369     return IsStringLiteralCall(cast<CallExpr>(E));
   1370   // For GCC compatibility, &&label has static storage duration.
   1371   case Expr::AddrLabelExprClass:
   1372     return true;
   1373   // A Block literal expression may be used as the initialization value for
   1374   // Block variables at global or local static scope.
   1375   case Expr::BlockExprClass:
   1376     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
   1377   case Expr::ImplicitValueInitExprClass:
   1378     // FIXME:
   1379     // We can never form an lvalue with an implicit value initialization as its
   1380     // base through expression evaluation, so these only appear in one case: the
   1381     // implicit variable declaration we invent when checking whether a constexpr
   1382     // constructor can produce a constant expression. We must assume that such
   1383     // an expression might be a global lvalue.
   1384     return true;
   1385   }
   1386 }
   1387 
   1388 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
   1389   assert(Base && "no location for a null lvalue");
   1390   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
   1391   if (VD)
   1392     Info.Note(VD->getLocation(), diag::note_declared_at);
   1393   else
   1394     Info.Note(Base.get<const Expr*>()->getExprLoc(),
   1395               diag::note_constexpr_temporary_here);
   1396 }
   1397 
   1398 /// Check that this reference or pointer core constant expression is a valid
   1399 /// value for an address or reference constant expression. Return true if we
   1400 /// can fold this expression, whether or not it's a constant expression.
   1401 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
   1402                                           QualType Type, const LValue &LVal) {
   1403   bool IsReferenceType = Type->isReferenceType();
   1404 
   1405   APValue::LValueBase Base = LVal.getLValueBase();
   1406   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
   1407 
   1408   // Check that the object is a global. Note that the fake 'this' object we
   1409   // manufacture when checking potential constant expressions is conservatively
   1410   // assumed to be global here.
   1411   if (!IsGlobalLValue(Base)) {
   1412     if (Info.getLangOpts().CPlusPlus11) {
   1413       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
   1414       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
   1415         << IsReferenceType << !Designator.Entries.empty()
   1416         << !!VD << VD;
   1417       NoteLValueLocation(Info, Base);
   1418     } else {
   1419       Info.FFDiag(Loc);
   1420     }
   1421     // Don't allow references to temporaries to escape.
   1422     return false;
   1423   }
   1424   assert((Info.checkingPotentialConstantExpression() ||
   1425           LVal.getLValueCallIndex() == 0) &&
   1426          "have call index for global lvalue");
   1427 
   1428   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
   1429     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
   1430       // Check if this is a thread-local variable.
   1431       if (Var->getTLSKind())
   1432         return false;
   1433 
   1434       // A dllimport variable never acts like a constant.
   1435       if (Var->hasAttr<DLLImportAttr>())
   1436         return false;
   1437     }
   1438     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
   1439       // __declspec(dllimport) must be handled very carefully:
   1440       // We must never initialize an expression with the thunk in C++.
   1441       // Doing otherwise would allow the same id-expression to yield
   1442       // different addresses for the same function in different translation
   1443       // units.  However, this means that we must dynamically initialize the
   1444       // expression with the contents of the import address table at runtime.
   1445       //
   1446       // The C language has no notion of ODR; furthermore, it has no notion of
   1447       // dynamic initialization.  This means that we are permitted to
   1448       // perform initialization with the address of the thunk.
   1449       if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
   1450         return false;
   1451     }
   1452   }
   1453 
   1454   // Allow address constant expressions to be past-the-end pointers. This is
   1455   // an extension: the standard requires them to point to an object.
   1456   if (!IsReferenceType)
   1457     return true;
   1458 
   1459   // A reference constant expression must refer to an object.
   1460   if (!Base) {
   1461     // FIXME: diagnostic
   1462     Info.CCEDiag(Loc);
   1463     return true;
   1464   }
   1465 
   1466   // Does this refer one past the end of some object?
   1467   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
   1468     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
   1469     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
   1470       << !Designator.Entries.empty() << !!VD << VD;
   1471     NoteLValueLocation(Info, Base);
   1472   }
   1473 
   1474   return true;
   1475 }
   1476 
   1477 /// Check that this core constant expression is of literal type, and if not,
   1478 /// produce an appropriate diagnostic.
   1479 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
   1480                              const LValue *This = nullptr) {
   1481   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
   1482     return true;
   1483 
   1484   // C++1y: A constant initializer for an object o [...] may also invoke
   1485   // constexpr constructors for o and its subobjects even if those objects
   1486   // are of non-literal class types.
   1487   if (Info.getLangOpts().CPlusPlus14 && This &&
   1488       Info.EvaluatingDecl == This->getLValueBase())
   1489     return true;
   1490 
   1491   // Prvalue constant expressions must be of literal types.
   1492   if (Info.getLangOpts().CPlusPlus11)
   1493     Info.FFDiag(E, diag::note_constexpr_nonliteral)
   1494       << E->getType();
   1495   else
   1496     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
   1497   return false;
   1498 }
   1499 
   1500 /// Check that this core constant expression value is a valid value for a
   1501 /// constant expression. If not, report an appropriate diagnostic. Does not
   1502 /// check that the expression is of literal type.
   1503 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
   1504                                     QualType Type, const APValue &Value) {
   1505   if (Value.isUninit()) {
   1506     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
   1507       << true << Type;
   1508     return false;
   1509   }
   1510 
   1511   // We allow _Atomic(T) to be initialized from anything that T can be
   1512   // initialized from.
   1513   if (const AtomicType *AT = Type->getAs<AtomicType>())
   1514     Type = AT->getValueType();
   1515 
   1516   // Core issue 1454: For a literal constant expression of array or class type,
   1517   // each subobject of its value shall have been initialized by a constant
   1518   // expression.
   1519   if (Value.isArray()) {
   1520     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
   1521     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
   1522       if (!CheckConstantExpression(Info, DiagLoc, EltTy,
   1523                                    Value.getArrayInitializedElt(I)))
   1524         return false;
   1525     }
   1526     if (!Value.hasArrayFiller())
   1527       return true;
   1528     return CheckConstantExpression(Info, DiagLoc, EltTy,
   1529                                    Value.getArrayFiller());
   1530   }
   1531   if (Value.isUnion() && Value.getUnionField()) {
   1532     return CheckConstantExpression(Info, DiagLoc,
   1533                                    Value.getUnionField()->getType(),
   1534                                    Value.getUnionValue());
   1535   }
   1536   if (Value.isStruct()) {
   1537     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
   1538     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
   1539       unsigned BaseIndex = 0;
   1540       for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
   1541              End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
   1542         if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
   1543                                      Value.getStructBase(BaseIndex)))
   1544           return false;
   1545       }
   1546     }
   1547     for (const auto *I : RD->fields()) {
   1548       if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
   1549                                    Value.getStructField(I->getFieldIndex())))
   1550         return false;
   1551     }
   1552   }
   1553 
   1554   if (Value.isLValue()) {
   1555     LValue LVal;
   1556     LVal.setFrom(Info.Ctx, Value);
   1557     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
   1558   }
   1559 
   1560   // Everything else is fine.
   1561   return true;
   1562 }
   1563 
   1564 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
   1565   return LVal.Base.dyn_cast<const ValueDecl*>();
   1566 }
   1567 
   1568 static bool IsLiteralLValue(const LValue &Value) {
   1569   if (Value.CallIndex)
   1570     return false;
   1571   const Expr *E = Value.Base.dyn_cast<const Expr*>();
   1572   return E && !isa<MaterializeTemporaryExpr>(E);
   1573 }
   1574 
   1575 static bool IsWeakLValue(const LValue &Value) {
   1576   const ValueDecl *Decl = GetLValueBaseDecl(Value);
   1577   return Decl && Decl->isWeak();
   1578 }
   1579 
   1580 static bool isZeroSized(const LValue &Value) {
   1581   const ValueDecl *Decl = GetLValueBaseDecl(Value);
   1582   if (Decl && isa<VarDecl>(Decl)) {
   1583     QualType Ty = Decl->getType();
   1584     if (Ty->isArrayType())
   1585       return Ty->isIncompleteType() ||
   1586              Decl->getASTContext().getTypeSize(Ty) == 0;
   1587   }
   1588   return false;
   1589 }
   1590 
   1591 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
   1592   // A null base expression indicates a null pointer.  These are always
   1593   // evaluatable, and they are false unless the offset is zero.
   1594   if (!Value.getLValueBase()) {
   1595     Result = !Value.getLValueOffset().isZero();
   1596     return true;
   1597   }
   1598 
   1599   // We have a non-null base.  These are generally known to be true, but if it's
   1600   // a weak declaration it can be null at runtime.
   1601   Result = true;
   1602   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
   1603   return !Decl || !Decl->isWeak();
   1604 }
   1605 
   1606 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
   1607   switch (Val.getKind()) {
   1608   case APValue::Uninitialized:
   1609     return false;
   1610   case APValue::Int:
   1611     Result = Val.getInt().getBoolValue();
   1612     return true;
   1613   case APValue::Float:
   1614     Result = !Val.getFloat().isZero();
   1615     return true;
   1616   case APValue::ComplexInt:
   1617     Result = Val.getComplexIntReal().getBoolValue() ||
   1618              Val.getComplexIntImag().getBoolValue();
   1619     return true;
   1620   case APValue::ComplexFloat:
   1621     Result = !Val.getComplexFloatReal().isZero() ||
   1622              !Val.getComplexFloatImag().isZero();
   1623     return true;
   1624   case APValue::LValue:
   1625     return EvalPointerValueAsBool(Val, Result);
   1626   case APValue::MemberPointer:
   1627     Result = Val.getMemberPointerDecl();
   1628     return true;
   1629   case APValue::Vector:
   1630   case APValue::Array:
   1631   case APValue::Struct:
   1632   case APValue::Union:
   1633   case APValue::AddrLabelDiff:
   1634     return false;
   1635   }
   1636 
   1637   llvm_unreachable("unknown APValue kind");
   1638 }
   1639 
   1640 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
   1641                                        EvalInfo &Info) {
   1642   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
   1643   APValue Val;
   1644   if (!Evaluate(Val, Info, E))
   1645     return false;
   1646   return HandleConversionToBool(Val, Result);
   1647 }
   1648 
   1649 template<typename T>
   1650 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
   1651                            const T &SrcValue, QualType DestType) {
   1652   Info.CCEDiag(E, diag::note_constexpr_overflow)
   1653     << SrcValue << DestType;
   1654   return Info.noteUndefinedBehavior();
   1655 }
   1656 
   1657 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
   1658                                  QualType SrcType, const APFloat &Value,
   1659                                  QualType DestType, APSInt &Result) {
   1660   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
   1661   // Determine whether we are converting to unsigned or signed.
   1662   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
   1663 
   1664   Result = APSInt(DestWidth, !DestSigned);
   1665   bool ignored;
   1666   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
   1667       & APFloat::opInvalidOp)
   1668     return HandleOverflow(Info, E, Value, DestType);
   1669   return true;
   1670 }
   1671 
   1672 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
   1673                                    QualType SrcType, QualType DestType,
   1674                                    APFloat &Result) {
   1675   APFloat Value = Result;
   1676   bool ignored;
   1677   if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
   1678                      APFloat::rmNearestTiesToEven, &ignored)
   1679       & APFloat::opOverflow)
   1680     return HandleOverflow(Info, E, Value, DestType);
   1681   return true;
   1682 }
   1683 
   1684 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
   1685                                  QualType DestType, QualType SrcType,
   1686                                  const APSInt &Value) {
   1687   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
   1688   APSInt Result = Value;
   1689   // Figure out if this is a truncate, extend or noop cast.
   1690   // If the input is signed, do a sign extend, noop, or truncate.
   1691   Result = Result.extOrTrunc(DestWidth);
   1692   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
   1693   return Result;
   1694 }
   1695 
   1696 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
   1697                                  QualType SrcType, const APSInt &Value,
   1698                                  QualType DestType, APFloat &Result) {
   1699   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
   1700   if (Result.convertFromAPInt(Value, Value.isSigned(),
   1701                               APFloat::rmNearestTiesToEven)
   1702       & APFloat::opOverflow)
   1703     return HandleOverflow(Info, E, Value, DestType);
   1704   return true;
   1705 }
   1706 
   1707 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
   1708                                   APValue &Value, const FieldDecl *FD) {
   1709   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
   1710 
   1711   if (!Value.isInt()) {
   1712     // Trying to store a pointer-cast-to-integer into a bitfield.
   1713     // FIXME: In this case, we should provide the diagnostic for casting
   1714     // a pointer to an integer.
   1715     assert(Value.isLValue() && "integral value neither int nor lvalue?");
   1716     Info.FFDiag(E);
   1717     return false;
   1718   }
   1719 
   1720   APSInt &Int = Value.getInt();
   1721   unsigned OldBitWidth = Int.getBitWidth();
   1722   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
   1723   if (NewBitWidth < OldBitWidth)
   1724     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
   1725   return true;
   1726 }
   1727 
   1728 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
   1729                                   llvm::APInt &Res) {
   1730   APValue SVal;
   1731   if (!Evaluate(SVal, Info, E))
   1732     return false;
   1733   if (SVal.isInt()) {
   1734     Res = SVal.getInt();
   1735     return true;
   1736   }
   1737   if (SVal.isFloat()) {
   1738     Res = SVal.getFloat().bitcastToAPInt();
   1739     return true;
   1740   }
   1741   if (SVal.isVector()) {
   1742     QualType VecTy = E->getType();
   1743     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
   1744     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
   1745     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
   1746     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
   1747     Res = llvm::APInt::getNullValue(VecSize);
   1748     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
   1749       APValue &Elt = SVal.getVectorElt(i);
   1750       llvm::APInt EltAsInt;
   1751       if (Elt.isInt()) {
   1752         EltAsInt = Elt.getInt();
   1753       } else if (Elt.isFloat()) {
   1754         EltAsInt = Elt.getFloat().bitcastToAPInt();
   1755       } else {
   1756         // Don't try to handle vectors of anything other than int or float
   1757         // (not sure if it's possible to hit this case).
   1758         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
   1759         return false;
   1760       }
   1761       unsigned BaseEltSize = EltAsInt.getBitWidth();
   1762       if (BigEndian)
   1763         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
   1764       else
   1765         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
   1766     }
   1767     return true;
   1768   }
   1769   // Give up if the input isn't an int, float, or vector.  For example, we
   1770   // reject "(v4i16)(intptr_t)&a".
   1771   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
   1772   return false;
   1773 }
   1774 
   1775 /// Perform the given integer operation, which is known to need at most BitWidth
   1776 /// bits, and check for overflow in the original type (if that type was not an
   1777 /// unsigned type).
   1778 template<typename Operation>
   1779 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
   1780                                  const APSInt &LHS, const APSInt &RHS,
   1781                                  unsigned BitWidth, Operation Op,
   1782                                  APSInt &Result) {
   1783   if (LHS.isUnsigned()) {
   1784     Result = Op(LHS, RHS);
   1785     return true;
   1786   }
   1787 
   1788   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
   1789   Result = Value.trunc(LHS.getBitWidth());
   1790   if (Result.extend(BitWidth) != Value) {
   1791     if (Info.checkingForOverflow())
   1792       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
   1793                                        diag::warn_integer_constant_overflow)
   1794           << Result.toString(10) << E->getType();
   1795     else
   1796       return HandleOverflow(Info, E, Value, E->getType());
   1797   }
   1798   return true;
   1799 }
   1800 
   1801 /// Perform the given binary integer operation.
   1802 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
   1803                               BinaryOperatorKind Opcode, APSInt RHS,
   1804                               APSInt &Result) {
   1805   switch (Opcode) {
   1806   default:
   1807     Info.FFDiag(E);
   1808     return false;
   1809   case BO_Mul:
   1810     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
   1811                                 std::multiplies<APSInt>(), Result);
   1812   case BO_Add:
   1813     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
   1814                                 std::plus<APSInt>(), Result);
   1815   case BO_Sub:
   1816     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
   1817                                 std::minus<APSInt>(), Result);
   1818   case BO_And: Result = LHS & RHS; return true;
   1819   case BO_Xor: Result = LHS ^ RHS; return true;
   1820   case BO_Or:  Result = LHS | RHS; return true;
   1821   case BO_Div:
   1822   case BO_Rem:
   1823     if (RHS == 0) {
   1824       Info.FFDiag(E, diag::note_expr_divide_by_zero);
   1825       return false;
   1826     }
   1827     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
   1828     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
   1829     // this operation and gives the two's complement result.
   1830     if (RHS.isNegative() && RHS.isAllOnesValue() &&
   1831         LHS.isSigned() && LHS.isMinSignedValue())
   1832       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
   1833                             E->getType());
   1834     return true;
   1835   case BO_Shl: {
   1836     if (Info.getLangOpts().OpenCL)
   1837       // OpenCL 6.3j: shift values are effectively % word size of LHS.
   1838       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
   1839                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
   1840                     RHS.isUnsigned());
   1841     else if (RHS.isSigned() && RHS.isNegative()) {
   1842       // During constant-folding, a negative shift is an opposite shift. Such
   1843       // a shift is not a constant expression.
   1844       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
   1845       RHS = -RHS;
   1846       goto shift_right;
   1847     }
   1848   shift_left:
   1849     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
   1850     // the shifted type.
   1851     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
   1852     if (SA != RHS) {
   1853       Info.CCEDiag(E, diag::note_constexpr_large_shift)
   1854         << RHS << E->getType() << LHS.getBitWidth();
   1855     } else if (LHS.isSigned()) {
   1856       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
   1857       // operand, and must not overflow the corresponding unsigned type.
   1858       if (LHS.isNegative())
   1859         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
   1860       else if (LHS.countLeadingZeros() < SA)
   1861         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
   1862     }
   1863     Result = LHS << SA;
   1864     return true;
   1865   }
   1866   case BO_Shr: {
   1867     if (Info.getLangOpts().OpenCL)
   1868       // OpenCL 6.3j: shift values are effectively % word size of LHS.
   1869       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
   1870                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
   1871                     RHS.isUnsigned());
   1872     else if (RHS.isSigned() && RHS.isNegative()) {
   1873       // During constant-folding, a negative shift is an opposite shift. Such a
   1874       // shift is not a constant expression.
   1875       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
   1876       RHS = -RHS;
   1877       goto shift_left;
   1878     }
   1879   shift_right:
   1880     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
   1881     // shifted type.
   1882     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
   1883     if (SA != RHS)
   1884       Info.CCEDiag(E, diag::note_constexpr_large_shift)
   1885         << RHS << E->getType() << LHS.getBitWidth();
   1886     Result = LHS >> SA;
   1887     return true;
   1888   }
   1889 
   1890   case BO_LT: Result = LHS < RHS; return true;
   1891   case BO_GT: Result = LHS > RHS; return true;
   1892   case BO_LE: Result = LHS <= RHS; return true;
   1893   case BO_GE: Result = LHS >= RHS; return true;
   1894   case BO_EQ: Result = LHS == RHS; return true;
   1895   case BO_NE: Result = LHS != RHS; return true;
   1896   }
   1897 }
   1898 
   1899 /// Perform the given binary floating-point operation, in-place, on LHS.
   1900 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
   1901                                   APFloat &LHS, BinaryOperatorKind Opcode,
   1902                                   const APFloat &RHS) {
   1903   switch (Opcode) {
   1904   default:
   1905     Info.FFDiag(E);
   1906     return false;
   1907   case BO_Mul:
   1908     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
   1909     break;
   1910   case BO_Add:
   1911     LHS.add(RHS, APFloat::rmNearestTiesToEven);
   1912     break;
   1913   case BO_Sub:
   1914     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
   1915     break;
   1916   case BO_Div:
   1917     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
   1918     break;
   1919   }
   1920 
   1921   if (LHS.isInfinity() || LHS.isNaN()) {
   1922     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
   1923     return Info.noteUndefinedBehavior();
   1924   }
   1925   return true;
   1926 }
   1927 
   1928 /// Cast an lvalue referring to a base subobject to a derived class, by
   1929 /// truncating the lvalue's path to the given length.
   1930 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
   1931                                const RecordDecl *TruncatedType,
   1932                                unsigned TruncatedElements) {
   1933   SubobjectDesignator &D = Result.Designator;
   1934 
   1935   // Check we actually point to a derived class object.
   1936   if (TruncatedElements == D.Entries.size())
   1937     return true;
   1938   assert(TruncatedElements >= D.MostDerivedPathLength &&
   1939          "not casting to a derived class");
   1940   if (!Result.checkSubobject(Info, E, CSK_Derived))
   1941     return false;
   1942 
   1943   // Truncate the path to the subobject, and remove any derived-to-base offsets.
   1944   const RecordDecl *RD = TruncatedType;
   1945   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
   1946     if (RD->isInvalidDecl()) return false;
   1947     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
   1948     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
   1949     if (isVirtualBaseClass(D.Entries[I]))
   1950       Result.Offset -= Layout.getVBaseClassOffset(Base);
   1951     else
   1952       Result.Offset -= Layout.getBaseClassOffset(Base);
   1953     RD = Base;
   1954   }
   1955   D.Entries.resize(TruncatedElements);
   1956   return true;
   1957 }
   1958 
   1959 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
   1960                                    const CXXRecordDecl *Derived,
   1961                                    const CXXRecordDecl *Base,
   1962                                    const ASTRecordLayout *RL = nullptr) {
   1963   if (!RL) {
   1964     if (Derived->isInvalidDecl()) return false;
   1965     RL = &Info.Ctx.getASTRecordLayout(Derived);
   1966   }
   1967 
   1968   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
   1969   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
   1970   return true;
   1971 }
   1972 
   1973 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
   1974                              const CXXRecordDecl *DerivedDecl,
   1975                              const CXXBaseSpecifier *Base) {
   1976   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
   1977 
   1978   if (!Base->isVirtual())
   1979     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
   1980 
   1981   SubobjectDesignator &D = Obj.Designator;
   1982   if (D.Invalid)
   1983     return false;
   1984 
   1985   // Extract most-derived object and corresponding type.
   1986   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
   1987   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
   1988     return false;
   1989 
   1990   // Find the virtual base class.
   1991   if (DerivedDecl->isInvalidDecl()) return false;
   1992   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
   1993   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
   1994   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
   1995   return true;
   1996 }
   1997 
   1998 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
   1999                                  QualType Type, LValue &Result) {
   2000   for (CastExpr::path_const_iterator PathI = E->path_begin(),
   2001                                      PathE = E->path_end();
   2002        PathI != PathE; ++PathI) {
   2003     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
   2004                           *PathI))
   2005       return false;
   2006     Type = (*PathI)->getType();
   2007   }
   2008   return true;
   2009 }
   2010 
   2011 /// Update LVal to refer to the given field, which must be a member of the type
   2012 /// currently described by LVal.
   2013 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
   2014                                const FieldDecl *FD,
   2015                                const ASTRecordLayout *RL = nullptr) {
   2016   if (!RL) {
   2017     if (FD->getParent()->isInvalidDecl()) return false;
   2018     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
   2019   }
   2020 
   2021   unsigned I = FD->getFieldIndex();
   2022   LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
   2023   LVal.addDecl(Info, E, FD);
   2024   return true;
   2025 }
   2026 
   2027 /// Update LVal to refer to the given indirect field.
   2028 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
   2029                                        LValue &LVal,
   2030                                        const IndirectFieldDecl *IFD) {
   2031   for (const auto *C : IFD->chain())
   2032     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
   2033       return false;
   2034   return true;
   2035 }
   2036 
   2037 /// Get the size of the given type in char units.
   2038 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
   2039                          QualType Type, CharUnits &Size) {
   2040   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
   2041   // extension.
   2042   if (Type->isVoidType() || Type->isFunctionType()) {
   2043     Size = CharUnits::One();
   2044     return true;
   2045   }
   2046 
   2047   if (Type->isDependentType()) {
   2048     Info.FFDiag(Loc);
   2049     return false;
   2050   }
   2051 
   2052   if (!Type->isConstantSizeType()) {
   2053     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
   2054     // FIXME: Better diagnostic.
   2055     Info.FFDiag(Loc);
   2056     return false;
   2057   }
   2058 
   2059   Size = Info.Ctx.getTypeSizeInChars(Type);
   2060   return true;
   2061 }
   2062 
   2063 /// Update a pointer value to model pointer arithmetic.
   2064 /// \param Info - Information about the ongoing evaluation.
   2065 /// \param E - The expression being evaluated, for diagnostic purposes.
   2066 /// \param LVal - The pointer value to be updated.
   2067 /// \param EltTy - The pointee type represented by LVal.
   2068 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
   2069 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
   2070                                         LValue &LVal, QualType EltTy,
   2071                                         int64_t Adjustment) {
   2072   CharUnits SizeOfPointee;
   2073   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
   2074     return false;
   2075 
   2076   // Compute the new offset in the appropriate width.
   2077   LVal.Offset += Adjustment * SizeOfPointee;
   2078   LVal.adjustIndex(Info, E, Adjustment);
   2079   return true;
   2080 }
   2081 
   2082 /// Update an lvalue to refer to a component of a complex number.
   2083 /// \param Info - Information about the ongoing evaluation.
   2084 /// \param LVal - The lvalue to be updated.
   2085 /// \param EltTy - The complex number's component type.
   2086 /// \param Imag - False for the real component, true for the imaginary.
   2087 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
   2088                                        LValue &LVal, QualType EltTy,
   2089                                        bool Imag) {
   2090   if (Imag) {
   2091     CharUnits SizeOfComponent;
   2092     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
   2093       return false;
   2094     LVal.Offset += SizeOfComponent;
   2095   }
   2096   LVal.addComplex(Info, E, EltTy, Imag);
   2097   return true;
   2098 }
   2099 
   2100 /// Try to evaluate the initializer for a variable declaration.
   2101 ///
   2102 /// \param Info   Information about the ongoing evaluation.
   2103 /// \param E      An expression to be used when printing diagnostics.
   2104 /// \param VD     The variable whose initializer should be obtained.
   2105 /// \param Frame  The frame in which the variable was created. Must be null
   2106 ///               if this variable is not local to the evaluation.
   2107 /// \param Result Filled in with a pointer to the value of the variable.
   2108 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
   2109                                 const VarDecl *VD, CallStackFrame *Frame,
   2110                                 APValue *&Result) {
   2111   // If this is a parameter to an active constexpr function call, perform
   2112   // argument substitution.
   2113   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
   2114     // Assume arguments of a potential constant expression are unknown
   2115     // constant expressions.
   2116     if (Info.checkingPotentialConstantExpression())
   2117       return false;
   2118     if (!Frame || !Frame->Arguments) {
   2119       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
   2120       return false;
   2121     }
   2122     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
   2123     return true;
   2124   }
   2125 
   2126   // If this is a local variable, dig out its value.
   2127   if (Frame) {
   2128     Result = Frame->getTemporary(VD);
   2129     if (!Result) {
   2130       // Assume variables referenced within a lambda's call operator that were
   2131       // not declared within the call operator are captures and during checking
   2132       // of a potential constant expression, assume they are unknown constant
   2133       // expressions.
   2134       assert(isLambdaCallOperator(Frame->Callee) &&
   2135              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
   2136              "missing value for local variable");
   2137       if (Info.checkingPotentialConstantExpression())
   2138         return false;
   2139       // FIXME: implement capture evaluation during constant expr evaluation.
   2140       Info.FFDiag(E->getLocStart(),
   2141            diag::note_unimplemented_constexpr_lambda_feature_ast)
   2142           << "captures not currently allowed";
   2143       return false;
   2144     }
   2145     return true;
   2146   }
   2147 
   2148   // Dig out the initializer, and use the declaration which it's attached to.
   2149   const Expr *Init = VD->getAnyInitializer(VD);
   2150   if (!Init || Init->isValueDependent()) {
   2151     // If we're checking a potential constant expression, the variable could be
   2152     // initialized later.
   2153     if (!Info.checkingPotentialConstantExpression())
   2154       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
   2155     return false;
   2156   }
   2157 
   2158   // If we're currently evaluating the initializer of this declaration, use that
   2159   // in-flight value.
   2160   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
   2161     Result = Info.EvaluatingDeclValue;
   2162     return true;
   2163   }
   2164 
   2165   // Never evaluate the initializer of a weak variable. We can't be sure that
   2166   // this is the definition which will be used.
   2167   if (VD->isWeak()) {
   2168     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
   2169     return false;
   2170   }
   2171 
   2172   // Check that we can fold the initializer. In C++, we will have already done
   2173   // this in the cases where it matters for conformance.
   2174   SmallVector<PartialDiagnosticAt, 8> Notes;
   2175   if (!VD->evaluateValue(Notes)) {
   2176     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
   2177               Notes.size() + 1) << VD;
   2178     Info.Note(VD->getLocation(), diag::note_declared_at);
   2179     Info.addNotes(Notes);
   2180     return false;
   2181   } else if (!VD->checkInitIsICE()) {
   2182     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
   2183                  Notes.size() + 1) << VD;
   2184     Info.Note(VD->getLocation(), diag::note_declared_at);
   2185     Info.addNotes(Notes);
   2186   }
   2187 
   2188   Result = VD->getEvaluatedValue();
   2189   return true;
   2190 }
   2191 
   2192 static bool IsConstNonVolatile(QualType T) {
   2193   Qualifiers Quals = T.getQualifiers();
   2194   return Quals.hasConst() && !Quals.hasVolatile();
   2195 }
   2196 
   2197 /// Get the base index of the given base class within an APValue representing
   2198 /// the given derived class.
   2199 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
   2200                              const CXXRecordDecl *Base) {
   2201   Base = Base->getCanonicalDecl();
   2202   unsigned Index = 0;
   2203   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
   2204          E = Derived->bases_end(); I != E; ++I, ++Index) {
   2205     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
   2206       return Index;
   2207   }
   2208 
   2209   llvm_unreachable("base class missing from derived class's bases list");
   2210 }
   2211 
   2212 /// Extract the value of a character from a string literal.
   2213 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
   2214                                             uint64_t Index) {
   2215   // FIXME: Support ObjCEncodeExpr, MakeStringConstant
   2216   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
   2217     Lit = PE->getFunctionName();
   2218   const StringLiteral *S = cast<StringLiteral>(Lit);
   2219   const ConstantArrayType *CAT =
   2220       Info.Ctx.getAsConstantArrayType(S->getType());
   2221   assert(CAT && "string literal isn't an array");
   2222   QualType CharType = CAT->getElementType();
   2223   assert(CharType->isIntegerType() && "unexpected character type");
   2224 
   2225   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
   2226                CharType->isUnsignedIntegerType());
   2227   if (Index < S->getLength())
   2228     Value = S->getCodeUnit(Index);
   2229   return Value;
   2230 }
   2231 
   2232 // Expand a string literal into an array of characters.
   2233 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
   2234                                 APValue &Result) {
   2235   const StringLiteral *S = cast<StringLiteral>(Lit);
   2236   const ConstantArrayType *CAT =
   2237       Info.Ctx.getAsConstantArrayType(S->getType());
   2238   assert(CAT && "string literal isn't an array");
   2239   QualType CharType = CAT->getElementType();
   2240   assert(CharType->isIntegerType() && "unexpected character type");
   2241 
   2242   unsigned Elts = CAT->getSize().getZExtValue();
   2243   Result = APValue(APValue::UninitArray(),
   2244                    std::min(S->getLength(), Elts), Elts);
   2245   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
   2246                CharType->isUnsignedIntegerType());
   2247   if (Result.hasArrayFiller())
   2248     Result.getArrayFiller() = APValue(Value);
   2249   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
   2250     Value = S->getCodeUnit(I);
   2251     Result.getArrayInitializedElt(I) = APValue(Value);
   2252   }
   2253 }
   2254 
   2255 // Expand an array so that it has more than Index filled elements.
   2256 static void expandArray(APValue &Array, unsigned Index) {
   2257   unsigned Size = Array.getArraySize();
   2258   assert(Index < Size);
   2259 
   2260   // Always at least double the number of elements for which we store a value.
   2261   unsigned OldElts = Array.getArrayInitializedElts();
   2262   unsigned NewElts = std::max(Index+1, OldElts * 2);
   2263   NewElts = std::min(Size, std::max(NewElts, 8u));
   2264 
   2265   // Copy the data across.
   2266   APValue NewValue(APValue::UninitArray(), NewElts, Size);
   2267   for (unsigned I = 0; I != OldElts; ++I)
   2268     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
   2269   for (unsigned I = OldElts; I != NewElts; ++I)
   2270     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
   2271   if (NewValue.hasArrayFiller())
   2272     NewValue.getArrayFiller() = Array.getArrayFiller();
   2273   Array.swap(NewValue);
   2274 }
   2275 
   2276 /// Determine whether a type would actually be read by an lvalue-to-rvalue
   2277 /// conversion. If it's of class type, we may assume that the copy operation
   2278 /// is trivial. Note that this is never true for a union type with fields
   2279 /// (because the copy always "reads" the active member) and always true for
   2280 /// a non-class type.
   2281 static bool isReadByLvalueToRvalueConversion(QualType T) {
   2282   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
   2283   if (!RD || (RD->isUnion() && !RD->field_empty()))
   2284     return true;
   2285   if (RD->isEmpty())
   2286     return false;
   2287 
   2288   for (auto *Field : RD->fields())
   2289     if (isReadByLvalueToRvalueConversion(Field->getType()))
   2290       return true;
   2291 
   2292   for (auto &BaseSpec : RD->bases())
   2293     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
   2294       return true;
   2295 
   2296   return false;
   2297 }
   2298 
   2299 /// Diagnose an attempt to read from any unreadable field within the specified
   2300 /// type, which might be a class type.
   2301 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
   2302                                      QualType T) {
   2303   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
   2304   if (!RD)
   2305     return false;
   2306 
   2307   if (!RD->hasMutableFields())
   2308     return false;
   2309 
   2310   for (auto *Field : RD->fields()) {
   2311     // If we're actually going to read this field in some way, then it can't
   2312     // be mutable. If we're in a union, then assigning to a mutable field
   2313     // (even an empty one) can change the active member, so that's not OK.
   2314     // FIXME: Add core issue number for the union case.
   2315     if (Field->isMutable() &&
   2316         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
   2317       Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
   2318       Info.Note(Field->getLocation(), diag::note_declared_at);
   2319       return true;
   2320     }
   2321 
   2322     if (diagnoseUnreadableFields(Info, E, Field->getType()))
   2323       return true;
   2324   }
   2325 
   2326   for (auto &BaseSpec : RD->bases())
   2327     if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
   2328       return true;
   2329 
   2330   // All mutable fields were empty, and thus not actually read.
   2331   return false;
   2332 }
   2333 
   2334 /// Kinds of access we can perform on an object, for diagnostics.
   2335 enum AccessKinds {
   2336   AK_Read,
   2337   AK_Assign,
   2338   AK_Increment,
   2339   AK_Decrement
   2340 };
   2341 
   2342 namespace {
   2343 /// A handle to a complete object (an object that is not a subobject of
   2344 /// another object).
   2345 struct CompleteObject {
   2346   /// The value of the complete object.
   2347   APValue *Value;
   2348   /// The type of the complete object.
   2349   QualType Type;
   2350 
   2351   CompleteObject() : Value(nullptr) {}
   2352   CompleteObject(APValue *Value, QualType Type)
   2353       : Value(Value), Type(Type) {
   2354     assert(Value && "missing value for complete object");
   2355   }
   2356 
   2357   explicit operator bool() const { return Value; }
   2358 };
   2359 } // end anonymous namespace
   2360 
   2361 /// Find the designated sub-object of an rvalue.
   2362 template<typename SubobjectHandler>
   2363 typename SubobjectHandler::result_type
   2364 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
   2365               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
   2366   if (Sub.Invalid)
   2367     // A diagnostic will have already been produced.
   2368     return handler.failed();
   2369   if (Sub.isOnePastTheEnd()) {
   2370     if (Info.getLangOpts().CPlusPlus11)
   2371       Info.FFDiag(E, diag::note_constexpr_access_past_end)
   2372         << handler.AccessKind;
   2373     else
   2374       Info.FFDiag(E);
   2375     return handler.failed();
   2376   }
   2377 
   2378   APValue *O = Obj.Value;
   2379   QualType ObjType = Obj.Type;
   2380   const FieldDecl *LastField = nullptr;
   2381 
   2382   // Walk the designator's path to find the subobject.
   2383   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
   2384     if (O->isUninit()) {
   2385       if (!Info.checkingPotentialConstantExpression())
   2386         Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
   2387       return handler.failed();
   2388     }
   2389 
   2390     if (I == N) {
   2391       // If we are reading an object of class type, there may still be more
   2392       // things we need to check: if there are any mutable subobjects, we
   2393       // cannot perform this read. (This only happens when performing a trivial
   2394       // copy or assignment.)
   2395       if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
   2396           diagnoseUnreadableFields(Info, E, ObjType))
   2397         return handler.failed();
   2398 
   2399       if (!handler.found(*O, ObjType))
   2400         return false;
   2401 
   2402       // If we modified a bit-field, truncate it to the right width.
   2403       if (handler.AccessKind != AK_Read &&
   2404           LastField && LastField->isBitField() &&
   2405           !truncateBitfieldValue(Info, E, *O, LastField))
   2406         return false;
   2407 
   2408       return true;
   2409     }
   2410 
   2411     LastField = nullptr;
   2412     if (ObjType->isArrayType()) {
   2413       // Next subobject is an array element.
   2414       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
   2415       assert(CAT && "vla in literal type?");
   2416       uint64_t Index = Sub.Entries[I].ArrayIndex;
   2417       if (CAT->getSize().ule(Index)) {
   2418         // Note, it should not be possible to form a pointer with a valid
   2419         // designator which points more than one past the end of the array.
   2420         if (Info.getLangOpts().CPlusPlus11)
   2421           Info.FFDiag(E, diag::note_constexpr_access_past_end)
   2422             << handler.AccessKind;
   2423         else
   2424           Info.FFDiag(E);
   2425         return handler.failed();
   2426       }
   2427 
   2428       ObjType = CAT->getElementType();
   2429 
   2430       // An array object is represented as either an Array APValue or as an
   2431       // LValue which refers to a string literal.
   2432       if (O->isLValue()) {
   2433         assert(I == N - 1 && "extracting subobject of character?");
   2434         assert(!O->hasLValuePath() || O->getLValuePath().empty());
   2435         if (handler.AccessKind != AK_Read)
   2436           expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
   2437                               *O);
   2438         else
   2439           return handler.foundString(*O, ObjType, Index);
   2440       }
   2441 
   2442       if (O->getArrayInitializedElts() > Index)
   2443         O = &O->getArrayInitializedElt(Index);
   2444       else if (handler.AccessKind != AK_Read) {
   2445         expandArray(*O, Index);
   2446         O = &O->getArrayInitializedElt(Index);
   2447       } else
   2448         O = &O->getArrayFiller();
   2449     } else if (ObjType->isAnyComplexType()) {
   2450       // Next subobject is a complex number.
   2451       uint64_t Index = Sub.Entries[I].ArrayIndex;
   2452       if (Index > 1) {
   2453         if (Info.getLangOpts().CPlusPlus11)
   2454           Info.FFDiag(E, diag::note_constexpr_access_past_end)
   2455             << handler.AccessKind;
   2456         else
   2457           Info.FFDiag(E);
   2458         return handler.failed();
   2459       }
   2460 
   2461       bool WasConstQualified = ObjType.isConstQualified();
   2462       ObjType = ObjType->castAs<ComplexType>()->getElementType();
   2463       if (WasConstQualified)
   2464         ObjType.addConst();
   2465 
   2466       assert(I == N - 1 && "extracting subobject of scalar?");
   2467       if (O->isComplexInt()) {
   2468         return handler.found(Index ? O->getComplexIntImag()
   2469                                    : O->getComplexIntReal(), ObjType);
   2470       } else {
   2471         assert(O->isComplexFloat());
   2472         return handler.found(Index ? O->getComplexFloatImag()
   2473                                    : O->getComplexFloatReal(), ObjType);
   2474       }
   2475     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
   2476       if (Field->isMutable() && handler.AccessKind == AK_Read) {
   2477         Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
   2478           << Field;
   2479         Info.Note(Field->getLocation(), diag::note_declared_at);
   2480         return handler.failed();
   2481       }
   2482 
   2483       // Next subobject is a class, struct or union field.
   2484       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
   2485       if (RD->isUnion()) {
   2486         const FieldDecl *UnionField = O->getUnionField();
   2487         if (!UnionField ||
   2488             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
   2489           Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
   2490             << handler.AccessKind << Field << !UnionField << UnionField;
   2491           return handler.failed();
   2492         }
   2493         O = &O->getUnionValue();
   2494       } else
   2495         O = &O->getStructField(Field->getFieldIndex());
   2496 
   2497       bool WasConstQualified = ObjType.isConstQualified();
   2498       ObjType = Field->getType();
   2499       if (WasConstQualified && !Field->isMutable())
   2500         ObjType.addConst();
   2501 
   2502       if (ObjType.isVolatileQualified()) {
   2503         if (Info.getLangOpts().CPlusPlus) {
   2504           // FIXME: Include a description of the path to the volatile subobject.
   2505           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
   2506             << handler.AccessKind << 2 << Field;
   2507           Info.Note(Field->getLocation(), diag::note_declared_at);
   2508         } else {
   2509           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
   2510         }
   2511         return handler.failed();
   2512       }
   2513 
   2514       LastField = Field;
   2515     } else {
   2516       // Next subobject is a base class.
   2517       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
   2518       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
   2519       O = &O->getStructBase(getBaseIndex(Derived, Base));
   2520 
   2521       bool WasConstQualified = ObjType.isConstQualified();
   2522       ObjType = Info.Ctx.getRecordType(Base);
   2523       if (WasConstQualified)
   2524         ObjType.addConst();
   2525     }
   2526   }
   2527 }
   2528 
   2529 namespace {
   2530 struct ExtractSubobjectHandler {
   2531   EvalInfo &Info;
   2532   APValue &Result;
   2533 
   2534   static const AccessKinds AccessKind = AK_Read;
   2535 
   2536   typedef bool result_type;
   2537   bool failed() { return false; }
   2538   bool found(APValue &Subobj, QualType SubobjType) {
   2539     Result = Subobj;
   2540     return true;
   2541   }
   2542   bool found(APSInt &Value, QualType SubobjType) {
   2543     Result = APValue(Value);
   2544     return true;
   2545   }
   2546   bool found(APFloat &Value, QualType SubobjType) {
   2547     Result = APValue(Value);
   2548     return true;
   2549   }
   2550   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
   2551     Result = APValue(extractStringLiteralCharacter(
   2552         Info, Subobj.getLValueBase().get<const Expr *>(), Character));
   2553     return true;
   2554   }
   2555 };
   2556 } // end anonymous namespace
   2557 
   2558 const AccessKinds ExtractSubobjectHandler::AccessKind;
   2559 
   2560 /// Extract the designated sub-object of an rvalue.
   2561 static bool extractSubobject(EvalInfo &Info, const Expr *E,
   2562                              const CompleteObject &Obj,
   2563                              const SubobjectDesignator &Sub,
   2564                              APValue &Result) {
   2565   ExtractSubobjectHandler Handler = { Info, Result };
   2566   return findSubobject(Info, E, Obj, Sub, Handler);
   2567 }
   2568 
   2569 namespace {
   2570 struct ModifySubobjectHandler {
   2571   EvalInfo &Info;
   2572   APValue &NewVal;
   2573   const Expr *E;
   2574 
   2575   typedef bool result_type;
   2576   static const AccessKinds AccessKind = AK_Assign;
   2577 
   2578   bool checkConst(QualType QT) {
   2579     // Assigning to a const object has undefined behavior.
   2580     if (QT.isConstQualified()) {
   2581       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
   2582       return false;
   2583     }
   2584     return true;
   2585   }
   2586 
   2587   bool failed() { return false; }
   2588   bool found(APValue &Subobj, QualType SubobjType) {
   2589     if (!checkConst(SubobjType))
   2590       return false;
   2591     // We've been given ownership of NewVal, so just swap it in.
   2592     Subobj.swap(NewVal);
   2593     return true;
   2594   }
   2595   bool found(APSInt &Value, QualType SubobjType) {
   2596     if (!checkConst(SubobjType))
   2597       return false;
   2598     if (!NewVal.isInt()) {
   2599       // Maybe trying to write a cast pointer value into a complex?
   2600       Info.FFDiag(E);
   2601       return false;
   2602     }
   2603     Value = NewVal.getInt();
   2604     return true;
   2605   }
   2606   bool found(APFloat &Value, QualType SubobjType) {
   2607     if (!checkConst(SubobjType))
   2608       return false;
   2609     Value = NewVal.getFloat();
   2610     return true;
   2611   }
   2612   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
   2613     llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
   2614   }
   2615 };
   2616 } // end anonymous namespace
   2617 
   2618 const AccessKinds ModifySubobjectHandler::AccessKind;
   2619 
   2620 /// Update the designated sub-object of an rvalue to the given value.
   2621 static bool modifySubobject(EvalInfo &Info, const Expr *E,
   2622                             const CompleteObject &Obj,
   2623                             const SubobjectDesignator &Sub,
   2624                             APValue &NewVal) {
   2625   ModifySubobjectHandler Handler = { Info, NewVal, E };
   2626   return findSubobject(Info, E, Obj, Sub, Handler);
   2627 }
   2628 
   2629 /// Find the position where two subobject designators diverge, or equivalently
   2630 /// the length of the common initial subsequence.
   2631 static unsigned FindDesignatorMismatch(QualType ObjType,
   2632                                        const SubobjectDesignator &A,
   2633                                        const SubobjectDesignator &B,
   2634                                        bool &WasArrayIndex) {
   2635   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
   2636   for (/**/; I != N; ++I) {
   2637     if (!ObjType.isNull() &&
   2638         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
   2639       // Next subobject is an array element.
   2640       if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
   2641         WasArrayIndex = true;
   2642         return I;
   2643       }
   2644       if (ObjType->isAnyComplexType())
   2645         ObjType = ObjType->castAs<ComplexType>()->getElementType();
   2646       else
   2647         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
   2648     } else {
   2649       if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
   2650         WasArrayIndex = false;
   2651         return I;
   2652       }
   2653       if (const FieldDecl *FD = getAsField(A.Entries[I]))
   2654         // Next subobject is a field.
   2655         ObjType = FD->getType();
   2656       else
   2657         // Next subobject is a base class.
   2658         ObjType = QualType();
   2659     }
   2660   }
   2661   WasArrayIndex = false;
   2662   return I;
   2663 }
   2664 
   2665 /// Determine whether the given subobject designators refer to elements of the
   2666 /// same array object.
   2667 static bool AreElementsOfSameArray(QualType ObjType,
   2668                                    const SubobjectDesignator &A,
   2669                                    const SubobjectDesignator &B) {
   2670   if (A.Entries.size() != B.Entries.size())
   2671     return false;
   2672 
   2673   bool IsArray = A.MostDerivedIsArrayElement;
   2674   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
   2675     // A is a subobject of the array element.
   2676     return false;
   2677 
   2678   // If A (and B) designates an array element, the last entry will be the array
   2679   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
   2680   // of length 1' case, and the entire path must match.
   2681   bool WasArrayIndex;
   2682   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
   2683   return CommonLength >= A.Entries.size() - IsArray;
   2684 }
   2685 
   2686 /// Find the complete object to which an LValue refers.
   2687 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
   2688                                          AccessKinds AK, const LValue &LVal,
   2689                                          QualType LValType) {
   2690   if (!LVal.Base) {
   2691     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
   2692     return CompleteObject();
   2693   }
   2694 
   2695   CallStackFrame *Frame = nullptr;
   2696   if (LVal.CallIndex) {
   2697     Frame = Info.getCallFrame(LVal.CallIndex);
   2698     if (!Frame) {
   2699       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
   2700         << AK << LVal.Base.is<const ValueDecl*>();
   2701       NoteLValueLocation(Info, LVal.Base);
   2702       return CompleteObject();
   2703     }
   2704   }
   2705 
   2706   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
   2707   // is not a constant expression (even if the object is non-volatile). We also
   2708   // apply this rule to C++98, in order to conform to the expected 'volatile'
   2709   // semantics.
   2710   if (LValType.isVolatileQualified()) {
   2711     if (Info.getLangOpts().CPlusPlus)
   2712       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
   2713         << AK << LValType;
   2714     else
   2715       Info.FFDiag(E);
   2716     return CompleteObject();
   2717   }
   2718 
   2719   // Compute value storage location and type of base object.
   2720   APValue *BaseVal = nullptr;
   2721   QualType BaseType = getType(LVal.Base);
   2722 
   2723   if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
   2724     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
   2725     // In C++11, constexpr, non-volatile variables initialized with constant
   2726     // expressions are constant expressions too. Inside constexpr functions,
   2727     // parameters are constant expressions even if they're non-const.
   2728     // In C++1y, objects local to a constant expression (those with a Frame) are
   2729     // both readable and writable inside constant expressions.
   2730     // In C, such things can also be folded, although they are not ICEs.
   2731     const VarDecl *VD = dyn_cast<VarDecl>(D);
   2732     if (VD) {
   2733       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
   2734         VD = VDef;
   2735     }
   2736     if (!VD || VD->isInvalidDecl()) {
   2737       Info.FFDiag(E);
   2738       return CompleteObject();
   2739     }
   2740 
   2741     // Accesses of volatile-qualified objects are not allowed.
   2742     if (BaseType.isVolatileQualified()) {
   2743       if (Info.getLangOpts().CPlusPlus) {
   2744         Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
   2745           << AK << 1 << VD;
   2746         Info.Note(VD->getLocation(), diag::note_declared_at);
   2747       } else {
   2748         Info.FFDiag(E);
   2749       }
   2750       return CompleteObject();
   2751     }
   2752 
   2753     // Unless we're looking at a local variable or argument in a constexpr call,
   2754     // the variable we're reading must be const.
   2755     if (!Frame) {
   2756       if (Info.getLangOpts().CPlusPlus14 &&
   2757           VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
   2758         // OK, we can read and modify an object if we're in the process of
   2759         // evaluating its initializer, because its lifetime began in this
   2760         // evaluation.
   2761       } else if (AK != AK_Read) {
   2762         // All the remaining cases only permit reading.
   2763         Info.FFDiag(E, diag::note_constexpr_modify_global);
   2764         return CompleteObject();
   2765       } else if (VD->isConstexpr()) {
   2766         // OK, we can read this variable.
   2767       } else if (BaseType->isIntegralOrEnumerationType()) {
   2768         // In OpenCL if a variable is in constant address space it is a const value.
   2769         if (!(BaseType.isConstQualified() ||
   2770               (Info.getLangOpts().OpenCL &&
   2771                BaseType.getAddressSpace() == LangAS::opencl_constant))) {
   2772           if (Info.getLangOpts().CPlusPlus) {
   2773             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
   2774             Info.Note(VD->getLocation(), diag::note_declared_at);
   2775           } else {
   2776             Info.FFDiag(E);
   2777           }
   2778           return CompleteObject();
   2779         }
   2780       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
   2781         // We support folding of const floating-point types, in order to make
   2782         // static const data members of such types (supported as an extension)
   2783         // more useful.
   2784         if (Info.getLangOpts().CPlusPlus11) {
   2785           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
   2786           Info.Note(VD->getLocation(), diag::note_declared_at);
   2787         } else {
   2788           Info.CCEDiag(E);
   2789         }
   2790       } else {
   2791         // FIXME: Allow folding of values of any literal type in all languages.
   2792         if (Info.checkingPotentialConstantExpression() &&
   2793             VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
   2794           // The definition of this variable could be constexpr. We can't
   2795           // access it right now, but may be able to in future.
   2796         } else if (Info.getLangOpts().CPlusPlus11) {
   2797           Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
   2798           Info.Note(VD->getLocation(), diag::note_declared_at);
   2799         } else {
   2800           Info.FFDiag(E);
   2801         }
   2802         return CompleteObject();
   2803       }
   2804     }
   2805 
   2806     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
   2807       return CompleteObject();
   2808   } else {
   2809     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
   2810 
   2811     if (!Frame) {
   2812       if (const MaterializeTemporaryExpr *MTE =
   2813               dyn_cast<MaterializeTemporaryExpr>(Base)) {
   2814         assert(MTE->getStorageDuration() == SD_Static &&
   2815                "should have a frame for a non-global materialized temporary");
   2816 
   2817         // Per C++1y [expr.const]p2:
   2818         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
   2819         //   - a [...] glvalue of integral or enumeration type that refers to
   2820         //     a non-volatile const object [...]
   2821         //   [...]
   2822         //   - a [...] glvalue of literal type that refers to a non-volatile
   2823         //     object whose lifetime began within the evaluation of e.
   2824         //
   2825         // C++11 misses the 'began within the evaluation of e' check and
   2826         // instead allows all temporaries, including things like:
   2827         //   int &&r = 1;
   2828         //   int x = ++r;
   2829         //   constexpr int k = r;
   2830         // Therefore we use the C++1y rules in C++11 too.
   2831         const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
   2832         const ValueDecl *ED = MTE->getExtendingDecl();
   2833         if (!(BaseType.isConstQualified() &&
   2834               BaseType->isIntegralOrEnumerationType()) &&
   2835             !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
   2836           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
   2837           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
   2838           return CompleteObject();
   2839         }
   2840 
   2841         BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
   2842         assert(BaseVal && "got reference to unevaluated temporary");
   2843       } else {
   2844         Info.FFDiag(E);
   2845         return CompleteObject();
   2846       }
   2847     } else {
   2848       BaseVal = Frame->getTemporary(Base);
   2849       assert(BaseVal && "missing value for temporary");
   2850     }
   2851 
   2852     // Volatile temporary objects cannot be accessed in constant expressions.
   2853     if (BaseType.isVolatileQualified()) {
   2854       if (Info.getLangOpts().CPlusPlus) {
   2855         Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
   2856           << AK << 0;
   2857         Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
   2858       } else {
   2859         Info.FFDiag(E);
   2860       }
   2861       return CompleteObject();
   2862     }
   2863   }
   2864 
   2865   // During the construction of an object, it is not yet 'const'.
   2866   // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
   2867   // and this doesn't do quite the right thing for const subobjects of the
   2868   // object under construction.
   2869   if (LVal.getLValueBase() == Info.EvaluatingDecl) {
   2870     BaseType = Info.Ctx.getCanonicalType(BaseType);
   2871     BaseType.removeLocalConst();
   2872   }
   2873 
   2874   // In C++1y, we can't safely access any mutable state when we might be
   2875   // evaluating after an unmodeled side effect.
   2876   //
   2877   // FIXME: Not all local state is mutable. Allow local constant subobjects
   2878   // to be read here (but take care with 'mutable' fields).
   2879   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
   2880        Info.EvalStatus.HasSideEffects) ||
   2881       (AK != AK_Read && Info.IsSpeculativelyEvaluating))
   2882     return CompleteObject();
   2883 
   2884   return CompleteObject(BaseVal, BaseType);
   2885 }
   2886 
   2887 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
   2888 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
   2889 /// glvalue referred to by an entity of reference type.
   2890 ///
   2891 /// \param Info - Information about the ongoing evaluation.
   2892 /// \param Conv - The expression for which we are performing the conversion.
   2893 ///               Used for diagnostics.
   2894 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
   2895 ///               case of a non-class type).
   2896 /// \param LVal - The glvalue on which we are attempting to perform this action.
   2897 /// \param RVal - The produced value will be placed here.
   2898 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
   2899                                            QualType Type,
   2900                                            const LValue &LVal, APValue &RVal) {
   2901   if (LVal.Designator.Invalid)
   2902     return false;
   2903 
   2904   // Check for special cases where there is no existing APValue to look at.
   2905   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
   2906   if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
   2907     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
   2908       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
   2909       // initializer until now for such expressions. Such an expression can't be
   2910       // an ICE in C, so this only matters for fold.
   2911       assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
   2912       if (Type.isVolatileQualified()) {
   2913         Info.FFDiag(Conv);
   2914         return false;
   2915       }
   2916       APValue Lit;
   2917       if (!Evaluate(Lit, Info, CLE->getInitializer()))
   2918         return false;
   2919       CompleteObject LitObj(&Lit, Base->getType());
   2920       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
   2921     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
   2922       // We represent a string literal array as an lvalue pointing at the
   2923       // corresponding expression, rather than building an array of chars.
   2924       // FIXME: Support ObjCEncodeExpr, MakeStringConstant
   2925       APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
   2926       CompleteObject StrObj(&Str, Base->getType());
   2927       return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
   2928     }
   2929   }
   2930 
   2931   CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
   2932   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
   2933 }
   2934 
   2935 /// Perform an assignment of Val to LVal. Takes ownership of Val.
   2936 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
   2937                              QualType LValType, APValue &Val) {
   2938   if (LVal.Designator.Invalid)
   2939     return false;
   2940 
   2941   if (!Info.getLangOpts().CPlusPlus14) {
   2942     Info.FFDiag(E);
   2943     return false;
   2944   }
   2945 
   2946   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
   2947   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
   2948 }
   2949 
   2950 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
   2951   return T->isSignedIntegerType() &&
   2952          Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
   2953 }
   2954 
   2955 namespace {
   2956 struct CompoundAssignSubobjectHandler {
   2957   EvalInfo &Info;
   2958   const Expr *E;
   2959   QualType PromotedLHSType;
   2960   BinaryOperatorKind Opcode;
   2961   const APValue &RHS;
   2962 
   2963   static const AccessKinds AccessKind = AK_Assign;
   2964 
   2965   typedef bool result_type;
   2966 
   2967   bool checkConst(QualType QT) {
   2968     // Assigning to a const object has undefined behavior.
   2969     if (QT.isConstQualified()) {
   2970       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
   2971       return false;
   2972     }
   2973     return true;
   2974   }
   2975 
   2976   bool failed() { return false; }
   2977   bool found(APValue &Subobj, QualType SubobjType) {
   2978     switch (Subobj.getKind()) {
   2979     case APValue::Int:
   2980       return found(Subobj.getInt(), SubobjType);
   2981     case APValue::Float:
   2982       return found(Subobj.getFloat(), SubobjType);
   2983     case APValue::ComplexInt:
   2984     case APValue::ComplexFloat:
   2985       // FIXME: Implement complex compound assignment.
   2986       Info.FFDiag(E);
   2987       return false;
   2988     case APValue::LValue:
   2989       return foundPointer(Subobj, SubobjType);
   2990     default:
   2991       // FIXME: can this happen?
   2992       Info.FFDiag(E);
   2993       return false;
   2994     }
   2995   }
   2996   bool found(APSInt &Value, QualType SubobjType) {
   2997     if (!checkConst(SubobjType))
   2998       return false;
   2999 
   3000     if (!SubobjType->isIntegerType() || !RHS.isInt()) {
   3001       // We don't support compound assignment on integer-cast-to-pointer
   3002       // values.
   3003       Info.FFDiag(E);
   3004       return false;
   3005     }
   3006 
   3007     APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
   3008                                     SubobjType, Value);
   3009     if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
   3010       return false;
   3011     Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
   3012     return true;
   3013   }
   3014   bool found(APFloat &Value, QualType SubobjType) {
   3015     return checkConst(SubobjType) &&
   3016            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
   3017                                   Value) &&
   3018            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
   3019            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
   3020   }
   3021   bool foundPointer(APValue &Subobj, QualType SubobjType) {
   3022     if (!checkConst(SubobjType))
   3023       return false;
   3024 
   3025     QualType PointeeType;
   3026     if (const PointerType *PT = SubobjType->getAs<PointerType>())
   3027       PointeeType = PT->getPointeeType();
   3028 
   3029     if (PointeeType.isNull() || !RHS.isInt() ||
   3030         (Opcode != BO_Add && Opcode != BO_Sub)) {
   3031       Info.FFDiag(E);
   3032       return false;
   3033     }
   3034 
   3035     int64_t Offset = getExtValue(RHS.getInt());
   3036     if (Opcode == BO_Sub)
   3037       Offset = -Offset;
   3038 
   3039     LValue LVal;
   3040     LVal.setFrom(Info.Ctx, Subobj);
   3041     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
   3042       return false;
   3043     LVal.moveInto(Subobj);
   3044     return true;
   3045   }
   3046   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
   3047     llvm_unreachable("shouldn't encounter string elements here");
   3048   }
   3049 };
   3050 } // end anonymous namespace
   3051 
   3052 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
   3053 
   3054 /// Perform a compound assignment of LVal <op>= RVal.
   3055 static bool handleCompoundAssignment(
   3056     EvalInfo &Info, const Expr *E,
   3057     const LValue &LVal, QualType LValType, QualType PromotedLValType,
   3058     BinaryOperatorKind Opcode, const APValue &RVal) {
   3059   if (LVal.Designator.Invalid)
   3060     return false;
   3061 
   3062   if (!Info.getLangOpts().CPlusPlus14) {
   3063     Info.FFDiag(E);
   3064     return false;
   3065   }
   3066 
   3067   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
   3068   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
   3069                                              RVal };
   3070   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
   3071 }
   3072 
   3073 namespace {
   3074 struct IncDecSubobjectHandler {
   3075   EvalInfo &Info;
   3076   const Expr *E;
   3077   AccessKinds AccessKind;
   3078   APValue *Old;
   3079 
   3080   typedef bool result_type;
   3081 
   3082   bool checkConst(QualType QT) {
   3083     // Assigning to a const object has undefined behavior.
   3084     if (QT.isConstQualified()) {
   3085       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
   3086       return false;
   3087     }
   3088     return true;
   3089   }
   3090 
   3091   bool failed() { return false; }
   3092   bool found(APValue &Subobj, QualType SubobjType) {
   3093     // Stash the old value. Also clear Old, so we don't clobber it later
   3094     // if we're post-incrementing a complex.
   3095     if (Old) {
   3096       *Old = Subobj;
   3097       Old = nullptr;
   3098     }
   3099 
   3100     switch (Subobj.getKind()) {
   3101     case APValue::Int:
   3102       return found(Subobj.getInt(), SubobjType);
   3103     case APValue::Float:
   3104       return found(Subobj.getFloat(), SubobjType);
   3105     case APValue::ComplexInt:
   3106       return found(Subobj.getComplexIntReal(),
   3107                    SubobjType->castAs<ComplexType>()->getElementType()
   3108                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
   3109     case APValue::ComplexFloat:
   3110       return found(Subobj.getComplexFloatReal(),
   3111                    SubobjType->castAs<ComplexType>()->getElementType()
   3112                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
   3113     case APValue::LValue:
   3114       return foundPointer(Subobj, SubobjType);
   3115     default:
   3116       // FIXME: can this happen?
   3117       Info.FFDiag(E);
   3118       return false;
   3119     }
   3120   }
   3121   bool found(APSInt &Value, QualType SubobjType) {
   3122     if (!checkConst(SubobjType))
   3123       return false;
   3124 
   3125     if (!SubobjType->isIntegerType()) {
   3126       // We don't support increment / decrement on integer-cast-to-pointer
   3127       // values.
   3128       Info.FFDiag(E);
   3129       return false;
   3130     }
   3131 
   3132     if (Old) *Old = APValue(Value);
   3133 
   3134     // bool arithmetic promotes to int, and the conversion back to bool
   3135     // doesn't reduce mod 2^n, so special-case it.
   3136     if (SubobjType->isBooleanType()) {
   3137       if (AccessKind == AK_Increment)
   3138         Value = 1;
   3139       else
   3140         Value = !Value;
   3141       return true;
   3142     }
   3143 
   3144     bool WasNegative = Value.isNegative();
   3145     if (AccessKind == AK_Increment) {
   3146       ++Value;
   3147 
   3148       if (!WasNegative && Value.isNegative() &&
   3149           isOverflowingIntegerType(Info.Ctx, SubobjType)) {
   3150         APSInt ActualValue(Value, /*IsUnsigned*/true);
   3151         return HandleOverflow(Info, E, ActualValue, SubobjType);
   3152       }
   3153     } else {
   3154       --Value;
   3155 
   3156       if (WasNegative && !Value.isNegative() &&
   3157           isOverflowingIntegerType(Info.Ctx, SubobjType)) {
   3158         unsigned BitWidth = Value.getBitWidth();
   3159         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
   3160         ActualValue.setBit(BitWidth);
   3161         return HandleOverflow(Info, E, ActualValue, SubobjType);
   3162       }
   3163     }
   3164     return true;
   3165   }
   3166   bool found(APFloat &Value, QualType SubobjType) {
   3167     if (!checkConst(SubobjType))
   3168       return false;
   3169 
   3170     if (Old) *Old = APValue(Value);
   3171 
   3172     APFloat One(Value.getSemantics(), 1);
   3173     if (AccessKind == AK_Increment)
   3174       Value.add(One, APFloat::rmNearestTiesToEven);
   3175     else
   3176       Value.subtract(One, APFloat::rmNearestTiesToEven);
   3177     return true;
   3178   }
   3179   bool foundPointer(APValue &Subobj, QualType SubobjType) {
   3180     if (!checkConst(SubobjType))
   3181       return false;
   3182 
   3183     QualType PointeeType;
   3184     if (const PointerType *PT = SubobjType->getAs<PointerType>())
   3185       PointeeType = PT->getPointeeType();
   3186     else {
   3187       Info.FFDiag(E);
   3188       return false;
   3189     }
   3190 
   3191     LValue LVal;
   3192     LVal.setFrom(Info.Ctx, Subobj);
   3193     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
   3194                                      AccessKind == AK_Increment ? 1 : -1))
   3195       return false;
   3196     LVal.moveInto(Subobj);
   3197     return true;
   3198   }
   3199   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
   3200     llvm_unreachable("shouldn't encounter string elements here");
   3201   }
   3202 };
   3203 } // end anonymous namespace
   3204 
   3205 /// Perform an increment or decrement on LVal.
   3206 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
   3207                          QualType LValType, bool IsIncrement, APValue *Old) {
   3208   if (LVal.Designator.Invalid)
   3209     return false;
   3210 
   3211   if (!Info.getLangOpts().CPlusPlus14) {
   3212     Info.FFDiag(E);
   3213     return false;
   3214   }
   3215 
   3216   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
   3217   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
   3218   IncDecSubobjectHandler Handler = { Info, E, AK, Old };
   3219   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
   3220 }
   3221 
   3222 /// Build an lvalue for the object argument of a member function call.
   3223 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
   3224                                    LValue &This) {
   3225   if (Object->getType()->isPointerType())
   3226     return EvaluatePointer(Object, This, Info);
   3227 
   3228   if (Object->isGLValue())
   3229     return EvaluateLValue(Object, This, Info);
   3230 
   3231   if (Object->getType()->isLiteralType(Info.Ctx))
   3232     return EvaluateTemporary(Object, This, Info);
   3233 
   3234   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
   3235   return false;
   3236 }
   3237 
   3238 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
   3239 /// lvalue referring to the result.
   3240 ///
   3241 /// \param Info - Information about the ongoing evaluation.
   3242 /// \param LV - An lvalue referring to the base of the member pointer.
   3243 /// \param RHS - The member pointer expression.
   3244 /// \param IncludeMember - Specifies whether the member itself is included in
   3245 ///        the resulting LValue subobject designator. This is not possible when
   3246 ///        creating a bound member function.
   3247 /// \return The field or method declaration to which the member pointer refers,
   3248 ///         or 0 if evaluation fails.
   3249 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
   3250                                                   QualType LVType,
   3251                                                   LValue &LV,
   3252                                                   const Expr *RHS,
   3253                                                   bool IncludeMember = true) {
   3254   MemberPtr MemPtr;
   3255   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
   3256     return nullptr;
   3257 
   3258   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
   3259   // member value, the behavior is undefined.
   3260   if (!MemPtr.getDecl()) {
   3261     // FIXME: Specific diagnostic.
   3262     Info.FFDiag(RHS);
   3263     return nullptr;
   3264   }
   3265 
   3266   if (MemPtr.isDerivedMember()) {
   3267     // This is a member of some derived class. Truncate LV appropriately.
   3268     // The end of the derived-to-base path for the base object must match the
   3269     // derived-to-base path for the member pointer.
   3270     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
   3271         LV.Designator.Entries.size()) {
   3272       Info.FFDiag(RHS);
   3273       return nullptr;
   3274     }
   3275     unsigned PathLengthToMember =
   3276         LV.Designator.Entries.size() - MemPtr.Path.size();
   3277     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
   3278       const CXXRecordDecl *LVDecl = getAsBaseClass(
   3279           LV.Designator.Entries[PathLengthToMember + I]);
   3280       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
   3281       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
   3282         Info.FFDiag(RHS);
   3283         return nullptr;
   3284       }
   3285     }
   3286 
   3287     // Truncate the lvalue to the appropriate derived class.
   3288     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
   3289                             PathLengthToMember))
   3290       return nullptr;
   3291   } else if (!MemPtr.Path.empty()) {
   3292     // Extend the LValue path with the member pointer's path.
   3293     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
   3294                                   MemPtr.Path.size() + IncludeMember);
   3295 
   3296     // Walk down to the appropriate base class.
   3297     if (const PointerType *PT = LVType->getAs<PointerType>())
   3298       LVType = PT->getPointeeType();
   3299     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
   3300     assert(RD && "member pointer access on non-class-type expression");
   3301     // The first class in the path is that of the lvalue.
   3302     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
   3303       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
   3304       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
   3305         return nullptr;
   3306       RD = Base;
   3307     }
   3308     // Finally cast to the class containing the member.
   3309     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
   3310                                 MemPtr.getContainingRecord()))
   3311       return nullptr;
   3312   }
   3313 
   3314   // Add the member. Note that we cannot build bound member functions here.
   3315   if (IncludeMember) {
   3316     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
   3317       if (!HandleLValueMember(Info, RHS, LV, FD))
   3318         return nullptr;
   3319     } else if (const IndirectFieldDecl *IFD =
   3320                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
   3321       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
   3322         return nullptr;
   3323     } else {
   3324       llvm_unreachable("can't construct reference to bound member function");
   3325     }
   3326   }
   3327 
   3328   return MemPtr.getDecl();
   3329 }
   3330 
   3331 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
   3332                                                   const BinaryOperator *BO,
   3333                                                   LValue &LV,
   3334                                                   bool IncludeMember = true) {
   3335   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
   3336 
   3337   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
   3338     if (Info.noteFailure()) {
   3339       MemberPtr MemPtr;
   3340       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
   3341     }
   3342     return nullptr;
   3343   }
   3344 
   3345   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
   3346                                    BO->getRHS(), IncludeMember);
   3347 }
   3348 
   3349 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
   3350 /// the provided lvalue, which currently refers to the base object.
   3351 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
   3352                                     LValue &Result) {
   3353   SubobjectDesignator &D = Result.Designator;
   3354   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
   3355     return false;
   3356 
   3357   QualType TargetQT = E->getType();
   3358   if (const PointerType *PT = TargetQT->getAs<PointerType>())
   3359     TargetQT = PT->getPointeeType();
   3360 
   3361   // Check this cast lands within the final derived-to-base subobject path.
   3362   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
   3363     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
   3364       << D.MostDerivedType << TargetQT;
   3365     return false;
   3366   }
   3367 
   3368   // Check the type of the final cast. We don't need to check the path,
   3369   // since a cast can only be formed if the path is unique.
   3370   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
   3371   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
   3372   const CXXRecordDecl *FinalType;
   3373   if (NewEntriesSize == D.MostDerivedPathLength)
   3374     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
   3375   else
   3376     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
   3377   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
   3378     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
   3379       << D.MostDerivedType << TargetQT;
   3380     return false;
   3381   }
   3382 
   3383   // Truncate the lvalue to the appropriate derived class.
   3384   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
   3385 }
   3386 
   3387 namespace {
   3388 enum EvalStmtResult {
   3389