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 rules only, at the moment), or, if folding failed too,
     27 //    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/CharUnits.h"
     39 #include "clang/AST/RecordLayout.h"
     40 #include "clang/AST/StmtVisitor.h"
     41 #include "clang/AST/TypeLoc.h"
     42 #include "clang/AST/ASTDiagnostic.h"
     43 #include "clang/AST/Expr.h"
     44 #include "clang/Basic/Builtins.h"
     45 #include "clang/Basic/TargetInfo.h"
     46 #include "llvm/ADT/SmallString.h"
     47 #include <cstring>
     48 #include <functional>
     49 
     50 using namespace clang;
     51 using llvm::APSInt;
     52 using llvm::APFloat;
     53 
     54 static bool IsGlobalLValue(APValue::LValueBase B);
     55 
     56 namespace {
     57   struct LValue;
     58   struct CallStackFrame;
     59   struct EvalInfo;
     60 
     61   static QualType getType(APValue::LValueBase B) {
     62     if (!B) return QualType();
     63     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
     64       return D->getType();
     65     return B.get<const Expr*>()->getType();
     66   }
     67 
     68   /// Get an LValue path entry, which is known to not be an array index, as a
     69   /// field or base class.
     70   static
     71   APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
     72     APValue::BaseOrMemberType Value;
     73     Value.setFromOpaqueValue(E.BaseOrMember);
     74     return Value;
     75   }
     76 
     77   /// Get an LValue path entry, which is known to not be an array index, as a
     78   /// field declaration.
     79   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
     80     return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
     81   }
     82   /// Get an LValue path entry, which is known to not be an array index, as a
     83   /// base class declaration.
     84   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
     85     return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
     86   }
     87   /// Determine whether this LValue path entry for a base class names a virtual
     88   /// base class.
     89   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
     90     return getAsBaseOrMember(E).getInt();
     91   }
     92 
     93   /// Find the path length and type of the most-derived subobject in the given
     94   /// path, and find the size of the containing array, if any.
     95   static
     96   unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
     97                                     ArrayRef<APValue::LValuePathEntry> Path,
     98                                     uint64_t &ArraySize, QualType &Type) {
     99     unsigned MostDerivedLength = 0;
    100     Type = Base;
    101     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
    102       if (Type->isArrayType()) {
    103         const ConstantArrayType *CAT =
    104           cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
    105         Type = CAT->getElementType();
    106         ArraySize = CAT->getSize().getZExtValue();
    107         MostDerivedLength = I + 1;
    108       } else if (Type->isAnyComplexType()) {
    109         const ComplexType *CT = Type->castAs<ComplexType>();
    110         Type = CT->getElementType();
    111         ArraySize = 2;
    112         MostDerivedLength = I + 1;
    113       } else if (const FieldDecl *FD = getAsField(Path[I])) {
    114         Type = FD->getType();
    115         ArraySize = 0;
    116         MostDerivedLength = I + 1;
    117       } else {
    118         // Path[I] describes a base class.
    119         ArraySize = 0;
    120       }
    121     }
    122     return MostDerivedLength;
    123   }
    124 
    125   // The order of this enum is important for diagnostics.
    126   enum CheckSubobjectKind {
    127     CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
    128     CSK_This, CSK_Real, CSK_Imag
    129   };
    130 
    131   /// A path from a glvalue to a subobject of that glvalue.
    132   struct SubobjectDesignator {
    133     /// True if the subobject was named in a manner not supported by C++11. Such
    134     /// lvalues can still be folded, but they are not core constant expressions
    135     /// and we cannot perform lvalue-to-rvalue conversions on them.
    136     bool Invalid : 1;
    137 
    138     /// Is this a pointer one past the end of an object?
    139     bool IsOnePastTheEnd : 1;
    140 
    141     /// The length of the path to the most-derived object of which this is a
    142     /// subobject.
    143     unsigned MostDerivedPathLength : 30;
    144 
    145     /// The size of the array of which the most-derived object is an element, or
    146     /// 0 if the most-derived object is not an array element.
    147     uint64_t MostDerivedArraySize;
    148 
    149     /// The type of the most derived object referred to by this address.
    150     QualType MostDerivedType;
    151 
    152     typedef APValue::LValuePathEntry PathEntry;
    153 
    154     /// The entries on the path from the glvalue to the designated subobject.
    155     SmallVector<PathEntry, 8> Entries;
    156 
    157     SubobjectDesignator() : Invalid(true) {}
    158 
    159     explicit SubobjectDesignator(QualType T)
    160       : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
    161         MostDerivedArraySize(0), MostDerivedType(T) {}
    162 
    163     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
    164       : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
    165         MostDerivedPathLength(0), MostDerivedArraySize(0) {
    166       if (!Invalid) {
    167         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
    168         ArrayRef<PathEntry> VEntries = V.getLValuePath();
    169         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
    170         if (V.getLValueBase())
    171           MostDerivedPathLength =
    172               findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
    173                                        V.getLValuePath(), MostDerivedArraySize,
    174                                        MostDerivedType);
    175       }
    176     }
    177 
    178     void setInvalid() {
    179       Invalid = true;
    180       Entries.clear();
    181     }
    182 
    183     /// Determine whether this is a one-past-the-end pointer.
    184     bool isOnePastTheEnd() const {
    185       if (IsOnePastTheEnd)
    186         return true;
    187       if (MostDerivedArraySize &&
    188           Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
    189         return true;
    190       return false;
    191     }
    192 
    193     /// Check that this refers to a valid subobject.
    194     bool isValidSubobject() const {
    195       if (Invalid)
    196         return false;
    197       return !isOnePastTheEnd();
    198     }
    199     /// Check that this refers to a valid subobject, and if not, produce a
    200     /// relevant diagnostic and set the designator as invalid.
    201     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
    202 
    203     /// Update this designator to refer to the first element within this array.
    204     void addArrayUnchecked(const ConstantArrayType *CAT) {
    205       PathEntry Entry;
    206       Entry.ArrayIndex = 0;
    207       Entries.push_back(Entry);
    208 
    209       // This is a most-derived object.
    210       MostDerivedType = CAT->getElementType();
    211       MostDerivedArraySize = CAT->getSize().getZExtValue();
    212       MostDerivedPathLength = Entries.size();
    213     }
    214     /// Update this designator to refer to the given base or member of this
    215     /// object.
    216     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
    217       PathEntry Entry;
    218       APValue::BaseOrMemberType Value(D, Virtual);
    219       Entry.BaseOrMember = Value.getOpaqueValue();
    220       Entries.push_back(Entry);
    221 
    222       // If this isn't a base class, it's a new most-derived object.
    223       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
    224         MostDerivedType = FD->getType();
    225         MostDerivedArraySize = 0;
    226         MostDerivedPathLength = Entries.size();
    227       }
    228     }
    229     /// Update this designator to refer to the given complex component.
    230     void addComplexUnchecked(QualType EltTy, bool Imag) {
    231       PathEntry Entry;
    232       Entry.ArrayIndex = Imag;
    233       Entries.push_back(Entry);
    234 
    235       // This is technically a most-derived object, though in practice this
    236       // is unlikely to matter.
    237       MostDerivedType = EltTy;
    238       MostDerivedArraySize = 2;
    239       MostDerivedPathLength = Entries.size();
    240     }
    241     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
    242     /// Add N to the address of this subobject.
    243     void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
    244       if (Invalid) return;
    245       if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
    246         Entries.back().ArrayIndex += N;
    247         if (Entries.back().ArrayIndex > MostDerivedArraySize) {
    248           diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
    249           setInvalid();
    250         }
    251         return;
    252       }
    253       // [expr.add]p4: For the purposes of these operators, a pointer to a
    254       // nonarray object behaves the same as a pointer to the first element of
    255       // an array of length one with the type of the object as its element type.
    256       if (IsOnePastTheEnd && N == (uint64_t)-1)
    257         IsOnePastTheEnd = false;
    258       else if (!IsOnePastTheEnd && N == 1)
    259         IsOnePastTheEnd = true;
    260       else if (N != 0) {
    261         diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
    262         setInvalid();
    263       }
    264     }
    265   };
    266 
    267   /// A stack frame in the constexpr call stack.
    268   struct CallStackFrame {
    269     EvalInfo &Info;
    270 
    271     /// Parent - The caller of this stack frame.
    272     CallStackFrame *Caller;
    273 
    274     /// CallLoc - The location of the call expression for this call.
    275     SourceLocation CallLoc;
    276 
    277     /// Callee - The function which was called.
    278     const FunctionDecl *Callee;
    279 
    280     /// Index - The call index of this call.
    281     unsigned Index;
    282 
    283     /// This - The binding for the this pointer in this call, if any.
    284     const LValue *This;
    285 
    286     /// ParmBindings - Parameter bindings for this function call, indexed by
    287     /// parameters' function scope indices.
    288     const APValue *Arguments;
    289 
    290     typedef llvm::DenseMap<const Expr*, APValue> MapTy;
    291     typedef MapTy::const_iterator temp_iterator;
    292     /// Temporaries - Temporary lvalues materialized within this stack frame.
    293     MapTy Temporaries;
    294 
    295     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
    296                    const FunctionDecl *Callee, const LValue *This,
    297                    const APValue *Arguments);
    298     ~CallStackFrame();
    299   };
    300 
    301   /// A partial diagnostic which we might know in advance that we are not going
    302   /// to emit.
    303   class OptionalDiagnostic {
    304     PartialDiagnostic *Diag;
    305 
    306   public:
    307     explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
    308 
    309     template<typename T>
    310     OptionalDiagnostic &operator<<(const T &v) {
    311       if (Diag)
    312         *Diag << v;
    313       return *this;
    314     }
    315 
    316     OptionalDiagnostic &operator<<(const APSInt &I) {
    317       if (Diag) {
    318         llvm::SmallVector<char, 32> Buffer;
    319         I.toString(Buffer);
    320         *Diag << StringRef(Buffer.data(), Buffer.size());
    321       }
    322       return *this;
    323     }
    324 
    325     OptionalDiagnostic &operator<<(const APFloat &F) {
    326       if (Diag) {
    327         llvm::SmallVector<char, 32> Buffer;
    328         F.toString(Buffer);
    329         *Diag << StringRef(Buffer.data(), Buffer.size());
    330       }
    331       return *this;
    332     }
    333   };
    334 
    335   /// EvalInfo - This is a private struct used by the evaluator to capture
    336   /// information about a subexpression as it is folded.  It retains information
    337   /// about the AST context, but also maintains information about the folded
    338   /// expression.
    339   ///
    340   /// If an expression could be evaluated, it is still possible it is not a C
    341   /// "integer constant expression" or constant expression.  If not, this struct
    342   /// captures information about how and why not.
    343   ///
    344   /// One bit of information passed *into* the request for constant folding
    345   /// indicates whether the subexpression is "evaluated" or not according to C
    346   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
    347   /// evaluate the expression regardless of what the RHS is, but C only allows
    348   /// certain things in certain situations.
    349   struct EvalInfo {
    350     ASTContext &Ctx;
    351 
    352     /// EvalStatus - Contains information about the evaluation.
    353     Expr::EvalStatus &EvalStatus;
    354 
    355     /// CurrentCall - The top of the constexpr call stack.
    356     CallStackFrame *CurrentCall;
    357 
    358     /// CallStackDepth - The number of calls in the call stack right now.
    359     unsigned CallStackDepth;
    360 
    361     /// NextCallIndex - The next call index to assign.
    362     unsigned NextCallIndex;
    363 
    364     typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
    365     /// OpaqueValues - Values used as the common expression in a
    366     /// BinaryConditionalOperator.
    367     MapTy OpaqueValues;
    368 
    369     /// BottomFrame - The frame in which evaluation started. This must be
    370     /// initialized after CurrentCall and CallStackDepth.
    371     CallStackFrame BottomFrame;
    372 
    373     /// EvaluatingDecl - This is the declaration whose initializer is being
    374     /// evaluated, if any.
    375     const VarDecl *EvaluatingDecl;
    376 
    377     /// EvaluatingDeclValue - This is the value being constructed for the
    378     /// declaration whose initializer is being evaluated, if any.
    379     APValue *EvaluatingDeclValue;
    380 
    381     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
    382     /// notes attached to it will also be stored, otherwise they will not be.
    383     bool HasActiveDiagnostic;
    384 
    385     /// CheckingPotentialConstantExpression - Are we checking whether the
    386     /// expression is a potential constant expression? If so, some diagnostics
    387     /// are suppressed.
    388     bool CheckingPotentialConstantExpression;
    389 
    390     EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
    391       : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
    392         CallStackDepth(0), NextCallIndex(1),
    393         BottomFrame(*this, SourceLocation(), 0, 0, 0),
    394         EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
    395         CheckingPotentialConstantExpression(false) {}
    396 
    397     const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
    398       MapTy::const_iterator i = OpaqueValues.find(e);
    399       if (i == OpaqueValues.end()) return 0;
    400       return &i->second;
    401     }
    402 
    403     void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
    404       EvaluatingDecl = VD;
    405       EvaluatingDeclValue = &Value;
    406     }
    407 
    408     const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
    409 
    410     bool CheckCallLimit(SourceLocation Loc) {
    411       // Don't perform any constexpr calls (other than the call we're checking)
    412       // when checking a potential constant expression.
    413       if (CheckingPotentialConstantExpression && CallStackDepth > 1)
    414         return false;
    415       if (NextCallIndex == 0) {
    416         // NextCallIndex has wrapped around.
    417         Diag(Loc, diag::note_constexpr_call_limit_exceeded);
    418         return false;
    419       }
    420       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
    421         return true;
    422       Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
    423         << getLangOpts().ConstexprCallDepth;
    424       return false;
    425     }
    426 
    427     CallStackFrame *getCallFrame(unsigned CallIndex) {
    428       assert(CallIndex && "no call index in getCallFrame");
    429       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
    430       // be null in this loop.
    431       CallStackFrame *Frame = CurrentCall;
    432       while (Frame->Index > CallIndex)
    433         Frame = Frame->Caller;
    434       return (Frame->Index == CallIndex) ? Frame : 0;
    435     }
    436 
    437   private:
    438     /// Add a diagnostic to the diagnostics list.
    439     PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
    440       PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
    441       EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
    442       return EvalStatus.Diag->back().second;
    443     }
    444 
    445     /// Add notes containing a call stack to the current point of evaluation.
    446     void addCallStack(unsigned Limit);
    447 
    448   public:
    449     /// Diagnose that the evaluation cannot be folded.
    450     OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
    451                               = diag::note_invalid_subexpr_in_const_expr,
    452                             unsigned ExtraNotes = 0) {
    453       // If we have a prior diagnostic, it will be noting that the expression
    454       // isn't a constant expression. This diagnostic is more important.
    455       // FIXME: We might want to show both diagnostics to the user.
    456       if (EvalStatus.Diag) {
    457         unsigned CallStackNotes = CallStackDepth - 1;
    458         unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
    459         if (Limit)
    460           CallStackNotes = std::min(CallStackNotes, Limit + 1);
    461         if (CheckingPotentialConstantExpression)
    462           CallStackNotes = 0;
    463 
    464         HasActiveDiagnostic = true;
    465         EvalStatus.Diag->clear();
    466         EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
    467         addDiag(Loc, DiagId);
    468         if (!CheckingPotentialConstantExpression)
    469           addCallStack(Limit);
    470         return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
    471       }
    472       HasActiveDiagnostic = false;
    473       return OptionalDiagnostic();
    474     }
    475 
    476     OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
    477                               = diag::note_invalid_subexpr_in_const_expr,
    478                             unsigned ExtraNotes = 0) {
    479       if (EvalStatus.Diag)
    480         return Diag(E->getExprLoc(), DiagId, ExtraNotes);
    481       HasActiveDiagnostic = false;
    482       return OptionalDiagnostic();
    483     }
    484 
    485     /// Diagnose that the evaluation does not produce a C++11 core constant
    486     /// expression.
    487     template<typename LocArg>
    488     OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
    489                                  = diag::note_invalid_subexpr_in_const_expr,
    490                                unsigned ExtraNotes = 0) {
    491       // Don't override a previous diagnostic.
    492       if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
    493         HasActiveDiagnostic = false;
    494         return OptionalDiagnostic();
    495       }
    496       return Diag(Loc, DiagId, ExtraNotes);
    497     }
    498 
    499     /// Add a note to a prior diagnostic.
    500     OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
    501       if (!HasActiveDiagnostic)
    502         return OptionalDiagnostic();
    503       return OptionalDiagnostic(&addDiag(Loc, DiagId));
    504     }
    505 
    506     /// Add a stack of notes to a prior diagnostic.
    507     void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
    508       if (HasActiveDiagnostic) {
    509         EvalStatus.Diag->insert(EvalStatus.Diag->end(),
    510                                 Diags.begin(), Diags.end());
    511       }
    512     }
    513 
    514     /// Should we continue evaluation as much as possible after encountering a
    515     /// construct which can't be folded?
    516     bool keepEvaluatingAfterFailure() {
    517       return CheckingPotentialConstantExpression &&
    518              EvalStatus.Diag && EvalStatus.Diag->empty();
    519     }
    520   };
    521 
    522   /// Object used to treat all foldable expressions as constant expressions.
    523   struct FoldConstant {
    524     bool Enabled;
    525 
    526     explicit FoldConstant(EvalInfo &Info)
    527       : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
    528                 !Info.EvalStatus.HasSideEffects) {
    529     }
    530     // Treat the value we've computed since this object was created as constant.
    531     void Fold(EvalInfo &Info) {
    532       if (Enabled && !Info.EvalStatus.Diag->empty() &&
    533           !Info.EvalStatus.HasSideEffects)
    534         Info.EvalStatus.Diag->clear();
    535     }
    536   };
    537 
    538   /// RAII object used to suppress diagnostics and side-effects from a
    539   /// speculative evaluation.
    540   class SpeculativeEvaluationRAII {
    541     EvalInfo &Info;
    542     Expr::EvalStatus Old;
    543 
    544   public:
    545     SpeculativeEvaluationRAII(EvalInfo &Info,
    546                               llvm::SmallVectorImpl<PartialDiagnosticAt>
    547                                 *NewDiag = 0)
    548       : Info(Info), Old(Info.EvalStatus) {
    549       Info.EvalStatus.Diag = NewDiag;
    550     }
    551     ~SpeculativeEvaluationRAII() {
    552       Info.EvalStatus = Old;
    553     }
    554   };
    555 }
    556 
    557 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
    558                                          CheckSubobjectKind CSK) {
    559   if (Invalid)
    560     return false;
    561   if (isOnePastTheEnd()) {
    562     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
    563       << CSK;
    564     setInvalid();
    565     return false;
    566   }
    567   return true;
    568 }
    569 
    570 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
    571                                                     const Expr *E, uint64_t N) {
    572   if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
    573     Info.CCEDiag(E, diag::note_constexpr_array_index)
    574       << static_cast<int>(N) << /*array*/ 0
    575       << static_cast<unsigned>(MostDerivedArraySize);
    576   else
    577     Info.CCEDiag(E, diag::note_constexpr_array_index)
    578       << static_cast<int>(N) << /*non-array*/ 1;
    579   setInvalid();
    580 }
    581 
    582 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
    583                                const FunctionDecl *Callee, const LValue *This,
    584                                const APValue *Arguments)
    585     : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
    586       Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
    587   Info.CurrentCall = this;
    588   ++Info.CallStackDepth;
    589 }
    590 
    591 CallStackFrame::~CallStackFrame() {
    592   assert(Info.CurrentCall == this && "calls retired out of order");
    593   --Info.CallStackDepth;
    594   Info.CurrentCall = Caller;
    595 }
    596 
    597 /// Produce a string describing the given constexpr call.
    598 static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
    599   unsigned ArgIndex = 0;
    600   bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
    601                       !isa<CXXConstructorDecl>(Frame->Callee) &&
    602                       cast<CXXMethodDecl>(Frame->Callee)->isInstance();
    603 
    604   if (!IsMemberCall)
    605     Out << *Frame->Callee << '(';
    606 
    607   for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
    608        E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
    609     if (ArgIndex > (unsigned)IsMemberCall)
    610       Out << ", ";
    611 
    612     const ParmVarDecl *Param = *I;
    613     const APValue &Arg = Frame->Arguments[ArgIndex];
    614     Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
    615 
    616     if (ArgIndex == 0 && IsMemberCall)
    617       Out << "->" << *Frame->Callee << '(';
    618   }
    619 
    620   Out << ')';
    621 }
    622 
    623 void EvalInfo::addCallStack(unsigned Limit) {
    624   // Determine which calls to skip, if any.
    625   unsigned ActiveCalls = CallStackDepth - 1;
    626   unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
    627   if (Limit && Limit < ActiveCalls) {
    628     SkipStart = Limit / 2 + Limit % 2;
    629     SkipEnd = ActiveCalls - Limit / 2;
    630   }
    631 
    632   // Walk the call stack and add the diagnostics.
    633   unsigned CallIdx = 0;
    634   for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
    635        Frame = Frame->Caller, ++CallIdx) {
    636     // Skip this call?
    637     if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
    638       if (CallIdx == SkipStart) {
    639         // Note that we're skipping calls.
    640         addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
    641           << unsigned(ActiveCalls - Limit);
    642       }
    643       continue;
    644     }
    645 
    646     llvm::SmallVector<char, 128> Buffer;
    647     llvm::raw_svector_ostream Out(Buffer);
    648     describeCall(Frame, Out);
    649     addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
    650   }
    651 }
    652 
    653 namespace {
    654   struct ComplexValue {
    655   private:
    656     bool IsInt;
    657 
    658   public:
    659     APSInt IntReal, IntImag;
    660     APFloat FloatReal, FloatImag;
    661 
    662     ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
    663 
    664     void makeComplexFloat() { IsInt = false; }
    665     bool isComplexFloat() const { return !IsInt; }
    666     APFloat &getComplexFloatReal() { return FloatReal; }
    667     APFloat &getComplexFloatImag() { return FloatImag; }
    668 
    669     void makeComplexInt() { IsInt = true; }
    670     bool isComplexInt() const { return IsInt; }
    671     APSInt &getComplexIntReal() { return IntReal; }
    672     APSInt &getComplexIntImag() { return IntImag; }
    673 
    674     void moveInto(APValue &v) const {
    675       if (isComplexFloat())
    676         v = APValue(FloatReal, FloatImag);
    677       else
    678         v = APValue(IntReal, IntImag);
    679     }
    680     void setFrom(const APValue &v) {
    681       assert(v.isComplexFloat() || v.isComplexInt());
    682       if (v.isComplexFloat()) {
    683         makeComplexFloat();
    684         FloatReal = v.getComplexFloatReal();
    685         FloatImag = v.getComplexFloatImag();
    686       } else {
    687         makeComplexInt();
    688         IntReal = v.getComplexIntReal();
    689         IntImag = v.getComplexIntImag();
    690       }
    691     }
    692   };
    693 
    694   struct LValue {
    695     APValue::LValueBase Base;
    696     CharUnits Offset;
    697     unsigned CallIndex;
    698     SubobjectDesignator Designator;
    699 
    700     const APValue::LValueBase getLValueBase() const { return Base; }
    701     CharUnits &getLValueOffset() { return Offset; }
    702     const CharUnits &getLValueOffset() const { return Offset; }
    703     unsigned getLValueCallIndex() const { return CallIndex; }
    704     SubobjectDesignator &getLValueDesignator() { return Designator; }
    705     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
    706 
    707     void moveInto(APValue &V) const {
    708       if (Designator.Invalid)
    709         V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
    710       else
    711         V = APValue(Base, Offset, Designator.Entries,
    712                     Designator.IsOnePastTheEnd, CallIndex);
    713     }
    714     void setFrom(ASTContext &Ctx, const APValue &V) {
    715       assert(V.isLValue());
    716       Base = V.getLValueBase();
    717       Offset = V.getLValueOffset();
    718       CallIndex = V.getLValueCallIndex();
    719       Designator = SubobjectDesignator(Ctx, V);
    720     }
    721 
    722     void set(APValue::LValueBase B, unsigned I = 0) {
    723       Base = B;
    724       Offset = CharUnits::Zero();
    725       CallIndex = I;
    726       Designator = SubobjectDesignator(getType(B));
    727     }
    728 
    729     // Check that this LValue is not based on a null pointer. If it is, produce
    730     // a diagnostic and mark the designator as invalid.
    731     bool checkNullPointer(EvalInfo &Info, const Expr *E,
    732                           CheckSubobjectKind CSK) {
    733       if (Designator.Invalid)
    734         return false;
    735       if (!Base) {
    736         Info.CCEDiag(E, diag::note_constexpr_null_subobject)
    737           << CSK;
    738         Designator.setInvalid();
    739         return false;
    740       }
    741       return true;
    742     }
    743 
    744     // Check this LValue refers to an object. If not, set the designator to be
    745     // invalid and emit a diagnostic.
    746     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
    747       // Outside C++11, do not build a designator referring to a subobject of
    748       // any object: we won't use such a designator for anything.
    749       if (!Info.getLangOpts().CPlusPlus0x)
    750         Designator.setInvalid();
    751       return checkNullPointer(Info, E, CSK) &&
    752              Designator.checkSubobject(Info, E, CSK);
    753     }
    754 
    755     void addDecl(EvalInfo &Info, const Expr *E,
    756                  const Decl *D, bool Virtual = false) {
    757       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
    758         Designator.addDeclUnchecked(D, Virtual);
    759     }
    760     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
    761       if (checkSubobject(Info, E, CSK_ArrayToPointer))
    762         Designator.addArrayUnchecked(CAT);
    763     }
    764     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
    765       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
    766         Designator.addComplexUnchecked(EltTy, Imag);
    767     }
    768     void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
    769       if (checkNullPointer(Info, E, CSK_ArrayIndex))
    770         Designator.adjustIndex(Info, E, N);
    771     }
    772   };
    773 
    774   struct MemberPtr {
    775     MemberPtr() {}
    776     explicit MemberPtr(const ValueDecl *Decl) :
    777       DeclAndIsDerivedMember(Decl, false), Path() {}
    778 
    779     /// The member or (direct or indirect) field referred to by this member
    780     /// pointer, or 0 if this is a null member pointer.
    781     const ValueDecl *getDecl() const {
    782       return DeclAndIsDerivedMember.getPointer();
    783     }
    784     /// Is this actually a member of some type derived from the relevant class?
    785     bool isDerivedMember() const {
    786       return DeclAndIsDerivedMember.getInt();
    787     }
    788     /// Get the class which the declaration actually lives in.
    789     const CXXRecordDecl *getContainingRecord() const {
    790       return cast<CXXRecordDecl>(
    791           DeclAndIsDerivedMember.getPointer()->getDeclContext());
    792     }
    793 
    794     void moveInto(APValue &V) const {
    795       V = APValue(getDecl(), isDerivedMember(), Path);
    796     }
    797     void setFrom(const APValue &V) {
    798       assert(V.isMemberPointer());
    799       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
    800       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
    801       Path.clear();
    802       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
    803       Path.insert(Path.end(), P.begin(), P.end());
    804     }
    805 
    806     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
    807     /// whether the member is a member of some class derived from the class type
    808     /// of the member pointer.
    809     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
    810     /// Path - The path of base/derived classes from the member declaration's
    811     /// class (exclusive) to the class type of the member pointer (inclusive).
    812     SmallVector<const CXXRecordDecl*, 4> Path;
    813 
    814     /// Perform a cast towards the class of the Decl (either up or down the
    815     /// hierarchy).
    816     bool castBack(const CXXRecordDecl *Class) {
    817       assert(!Path.empty());
    818       const CXXRecordDecl *Expected;
    819       if (Path.size() >= 2)
    820         Expected = Path[Path.size() - 2];
    821       else
    822         Expected = getContainingRecord();
    823       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
    824         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
    825         // if B does not contain the original member and is not a base or
    826         // derived class of the class containing the original member, the result
    827         // of the cast is undefined.
    828         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
    829         // (D::*). We consider that to be a language defect.
    830         return false;
    831       }
    832       Path.pop_back();
    833       return true;
    834     }
    835     /// Perform a base-to-derived member pointer cast.
    836     bool castToDerived(const CXXRecordDecl *Derived) {
    837       if (!getDecl())
    838         return true;
    839       if (!isDerivedMember()) {
    840         Path.push_back(Derived);
    841         return true;
    842       }
    843       if (!castBack(Derived))
    844         return false;
    845       if (Path.empty())
    846         DeclAndIsDerivedMember.setInt(false);
    847       return true;
    848     }
    849     /// Perform a derived-to-base member pointer cast.
    850     bool castToBase(const CXXRecordDecl *Base) {
    851       if (!getDecl())
    852         return true;
    853       if (Path.empty())
    854         DeclAndIsDerivedMember.setInt(true);
    855       if (isDerivedMember()) {
    856         Path.push_back(Base);
    857         return true;
    858       }
    859       return castBack(Base);
    860     }
    861   };
    862 
    863   /// Compare two member pointers, which are assumed to be of the same type.
    864   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
    865     if (!LHS.getDecl() || !RHS.getDecl())
    866       return !LHS.getDecl() && !RHS.getDecl();
    867     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
    868       return false;
    869     return LHS.Path == RHS.Path;
    870   }
    871 
    872   /// Kinds of constant expression checking, for diagnostics.
    873   enum CheckConstantExpressionKind {
    874     CCEK_Constant,    ///< A normal constant.
    875     CCEK_ReturnValue, ///< A constexpr function return value.
    876     CCEK_MemberInit   ///< A constexpr constructor mem-initializer.
    877   };
    878 }
    879 
    880 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
    881 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
    882                             const LValue &This, const Expr *E,
    883                             CheckConstantExpressionKind CCEK = CCEK_Constant,
    884                             bool AllowNonLiteralTypes = false);
    885 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
    886 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
    887 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
    888                                   EvalInfo &Info);
    889 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
    890 static bool EvaluateInteger(const Expr *E, APSInt  &Result, EvalInfo &Info);
    891 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
    892                                     EvalInfo &Info);
    893 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
    894 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
    895 
    896 //===----------------------------------------------------------------------===//
    897 // Misc utilities
    898 //===----------------------------------------------------------------------===//
    899 
    900 /// Should this call expression be treated as a string literal?
    901 static bool IsStringLiteralCall(const CallExpr *E) {
    902   unsigned Builtin = E->isBuiltinCall();
    903   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
    904           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
    905 }
    906 
    907 static bool IsGlobalLValue(APValue::LValueBase B) {
    908   // C++11 [expr.const]p3 An address constant expression is a prvalue core
    909   // constant expression of pointer type that evaluates to...
    910 
    911   // ... a null pointer value, or a prvalue core constant expression of type
    912   // std::nullptr_t.
    913   if (!B) return true;
    914 
    915   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
    916     // ... the address of an object with static storage duration,
    917     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
    918       return VD->hasGlobalStorage();
    919     // ... the address of a function,
    920     return isa<FunctionDecl>(D);
    921   }
    922 
    923   const Expr *E = B.get<const Expr*>();
    924   switch (E->getStmtClass()) {
    925   default:
    926     return false;
    927   case Expr::CompoundLiteralExprClass: {
    928     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
    929     return CLE->isFileScope() && CLE->isLValue();
    930   }
    931   // A string literal has static storage duration.
    932   case Expr::StringLiteralClass:
    933   case Expr::PredefinedExprClass:
    934   case Expr::ObjCStringLiteralClass:
    935   case Expr::ObjCEncodeExprClass:
    936   case Expr::CXXTypeidExprClass:
    937   case Expr::CXXUuidofExprClass:
    938     return true;
    939   case Expr::CallExprClass:
    940     return IsStringLiteralCall(cast<CallExpr>(E));
    941   // For GCC compatibility, &&label has static storage duration.
    942   case Expr::AddrLabelExprClass:
    943     return true;
    944   // A Block literal expression may be used as the initialization value for
    945   // Block variables at global or local static scope.
    946   case Expr::BlockExprClass:
    947     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
    948   case Expr::ImplicitValueInitExprClass:
    949     // FIXME:
    950     // We can never form an lvalue with an implicit value initialization as its
    951     // base through expression evaluation, so these only appear in one case: the
    952     // implicit variable declaration we invent when checking whether a constexpr
    953     // constructor can produce a constant expression. We must assume that such
    954     // an expression might be a global lvalue.
    955     return true;
    956   }
    957 }
    958 
    959 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
    960   assert(Base && "no location for a null lvalue");
    961   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
    962   if (VD)
    963     Info.Note(VD->getLocation(), diag::note_declared_at);
    964   else
    965     Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
    966               diag::note_constexpr_temporary_here);
    967 }
    968 
    969 /// Check that this reference or pointer core constant expression is a valid
    970 /// value for an address or reference constant expression. Return true if we
    971 /// can fold this expression, whether or not it's a constant expression.
    972 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
    973                                           QualType Type, const LValue &LVal) {
    974   bool IsReferenceType = Type->isReferenceType();
    975 
    976   APValue::LValueBase Base = LVal.getLValueBase();
    977   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
    978 
    979   // Check that the object is a global. Note that the fake 'this' object we
    980   // manufacture when checking potential constant expressions is conservatively
    981   // assumed to be global here.
    982   if (!IsGlobalLValue(Base)) {
    983     if (Info.getLangOpts().CPlusPlus0x) {
    984       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
    985       Info.Diag(Loc, diag::note_constexpr_non_global, 1)
    986         << IsReferenceType << !Designator.Entries.empty()
    987         << !!VD << VD;
    988       NoteLValueLocation(Info, Base);
    989     } else {
    990       Info.Diag(Loc);
    991     }
    992     // Don't allow references to temporaries to escape.
    993     return false;
    994   }
    995   assert((Info.CheckingPotentialConstantExpression ||
    996           LVal.getLValueCallIndex() == 0) &&
    997          "have call index for global lvalue");
    998 
    999   // Allow address constant expressions to be past-the-end pointers. This is
   1000   // an extension: the standard requires them to point to an object.
   1001   if (!IsReferenceType)
   1002     return true;
   1003 
   1004   // A reference constant expression must refer to an object.
   1005   if (!Base) {
   1006     // FIXME: diagnostic
   1007     Info.CCEDiag(Loc);
   1008     return true;
   1009   }
   1010 
   1011   // Does this refer one past the end of some object?
   1012   if (Designator.isOnePastTheEnd()) {
   1013     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
   1014     Info.Diag(Loc, diag::note_constexpr_past_end, 1)
   1015       << !Designator.Entries.empty() << !!VD << VD;
   1016     NoteLValueLocation(Info, Base);
   1017   }
   1018 
   1019   return true;
   1020 }
   1021 
   1022 /// Check that this core constant expression is of literal type, and if not,
   1023 /// produce an appropriate diagnostic.
   1024 static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
   1025   if (!E->isRValue() || E->getType()->isLiteralType())
   1026     return true;
   1027 
   1028   // Prvalue constant expressions must be of literal types.
   1029   if (Info.getLangOpts().CPlusPlus0x)
   1030     Info.Diag(E, diag::note_constexpr_nonliteral)
   1031       << E->getType();
   1032   else
   1033     Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
   1034   return false;
   1035 }
   1036 
   1037 /// Check that this core constant expression value is a valid value for a
   1038 /// constant expression. If not, report an appropriate diagnostic. Does not
   1039 /// check that the expression is of literal type.
   1040 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
   1041                                     QualType Type, const APValue &Value) {
   1042   // Core issue 1454: For a literal constant expression of array or class type,
   1043   // each subobject of its value shall have been initialized by a constant
   1044   // expression.
   1045   if (Value.isArray()) {
   1046     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
   1047     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
   1048       if (!CheckConstantExpression(Info, DiagLoc, EltTy,
   1049                                    Value.getArrayInitializedElt(I)))
   1050         return false;
   1051     }
   1052     if (!Value.hasArrayFiller())
   1053       return true;
   1054     return CheckConstantExpression(Info, DiagLoc, EltTy,
   1055                                    Value.getArrayFiller());
   1056   }
   1057   if (Value.isUnion() && Value.getUnionField()) {
   1058     return CheckConstantExpression(Info, DiagLoc,
   1059                                    Value.getUnionField()->getType(),
   1060                                    Value.getUnionValue());
   1061   }
   1062   if (Value.isStruct()) {
   1063     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
   1064     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
   1065       unsigned BaseIndex = 0;
   1066       for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
   1067              End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
   1068         if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
   1069                                      Value.getStructBase(BaseIndex)))
   1070           return false;
   1071       }
   1072     }
   1073     for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
   1074          I != E; ++I) {
   1075       if (!CheckConstantExpression(Info, DiagLoc, (*I)->getType(),
   1076                                    Value.getStructField((*I)->getFieldIndex())))
   1077         return false;
   1078     }
   1079   }
   1080 
   1081   if (Value.isLValue()) {
   1082     LValue LVal;
   1083     LVal.setFrom(Info.Ctx, Value);
   1084     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
   1085   }
   1086 
   1087   // Everything else is fine.
   1088   return true;
   1089 }
   1090 
   1091 const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
   1092   return LVal.Base.dyn_cast<const ValueDecl*>();
   1093 }
   1094 
   1095 static bool IsLiteralLValue(const LValue &Value) {
   1096   return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
   1097 }
   1098 
   1099 static bool IsWeakLValue(const LValue &Value) {
   1100   const ValueDecl *Decl = GetLValueBaseDecl(Value);
   1101   return Decl && Decl->isWeak();
   1102 }
   1103 
   1104 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
   1105   // A null base expression indicates a null pointer.  These are always
   1106   // evaluatable, and they are false unless the offset is zero.
   1107   if (!Value.getLValueBase()) {
   1108     Result = !Value.getLValueOffset().isZero();
   1109     return true;
   1110   }
   1111 
   1112   // We have a non-null base.  These are generally known to be true, but if it's
   1113   // a weak declaration it can be null at runtime.
   1114   Result = true;
   1115   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
   1116   return !Decl || !Decl->isWeak();
   1117 }
   1118 
   1119 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
   1120   switch (Val.getKind()) {
   1121   case APValue::Uninitialized:
   1122     return false;
   1123   case APValue::Int:
   1124     Result = Val.getInt().getBoolValue();
   1125     return true;
   1126   case APValue::Float:
   1127     Result = !Val.getFloat().isZero();
   1128     return true;
   1129   case APValue::ComplexInt:
   1130     Result = Val.getComplexIntReal().getBoolValue() ||
   1131              Val.getComplexIntImag().getBoolValue();
   1132     return true;
   1133   case APValue::ComplexFloat:
   1134     Result = !Val.getComplexFloatReal().isZero() ||
   1135              !Val.getComplexFloatImag().isZero();
   1136     return true;
   1137   case APValue::LValue:
   1138     return EvalPointerValueAsBool(Val, Result);
   1139   case APValue::MemberPointer:
   1140     Result = Val.getMemberPointerDecl();
   1141     return true;
   1142   case APValue::Vector:
   1143   case APValue::Array:
   1144   case APValue::Struct:
   1145   case APValue::Union:
   1146   case APValue::AddrLabelDiff:
   1147     return false;
   1148   }
   1149 
   1150   llvm_unreachable("unknown APValue kind");
   1151 }
   1152 
   1153 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
   1154                                        EvalInfo &Info) {
   1155   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
   1156   APValue Val;
   1157   if (!Evaluate(Val, Info, E))
   1158     return false;
   1159   return HandleConversionToBool(Val, Result);
   1160 }
   1161 
   1162 template<typename T>
   1163 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
   1164                            const T &SrcValue, QualType DestType) {
   1165   Info.Diag(E, diag::note_constexpr_overflow)
   1166     << SrcValue << DestType;
   1167   return false;
   1168 }
   1169 
   1170 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
   1171                                  QualType SrcType, const APFloat &Value,
   1172                                  QualType DestType, APSInt &Result) {
   1173   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
   1174   // Determine whether we are converting to unsigned or signed.
   1175   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
   1176 
   1177   Result = APSInt(DestWidth, !DestSigned);
   1178   bool ignored;
   1179   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
   1180       & APFloat::opInvalidOp)
   1181     return HandleOverflow(Info, E, Value, DestType);
   1182   return true;
   1183 }
   1184 
   1185 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
   1186                                    QualType SrcType, QualType DestType,
   1187                                    APFloat &Result) {
   1188   APFloat Value = Result;
   1189   bool ignored;
   1190   if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
   1191                      APFloat::rmNearestTiesToEven, &ignored)
   1192       & APFloat::opOverflow)
   1193     return HandleOverflow(Info, E, Value, DestType);
   1194   return true;
   1195 }
   1196 
   1197 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
   1198                                  QualType DestType, QualType SrcType,
   1199                                  APSInt &Value) {
   1200   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
   1201   APSInt Result = Value;
   1202   // Figure out if this is a truncate, extend or noop cast.
   1203   // If the input is signed, do a sign extend, noop, or truncate.
   1204   Result = Result.extOrTrunc(DestWidth);
   1205   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
   1206   return Result;
   1207 }
   1208 
   1209 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
   1210                                  QualType SrcType, const APSInt &Value,
   1211                                  QualType DestType, APFloat &Result) {
   1212   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
   1213   if (Result.convertFromAPInt(Value, Value.isSigned(),
   1214                               APFloat::rmNearestTiesToEven)
   1215       & APFloat::opOverflow)
   1216     return HandleOverflow(Info, E, Value, DestType);
   1217   return true;
   1218 }
   1219 
   1220 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
   1221                                   llvm::APInt &Res) {
   1222   APValue SVal;
   1223   if (!Evaluate(SVal, Info, E))
   1224     return false;
   1225   if (SVal.isInt()) {
   1226     Res = SVal.getInt();
   1227     return true;
   1228   }
   1229   if (SVal.isFloat()) {
   1230     Res = SVal.getFloat().bitcastToAPInt();
   1231     return true;
   1232   }
   1233   if (SVal.isVector()) {
   1234     QualType VecTy = E->getType();
   1235     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
   1236     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
   1237     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
   1238     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
   1239     Res = llvm::APInt::getNullValue(VecSize);
   1240     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
   1241       APValue &Elt = SVal.getVectorElt(i);
   1242       llvm::APInt EltAsInt;
   1243       if (Elt.isInt()) {
   1244         EltAsInt = Elt.getInt();
   1245       } else if (Elt.isFloat()) {
   1246         EltAsInt = Elt.getFloat().bitcastToAPInt();
   1247       } else {
   1248         // Don't try to handle vectors of anything other than int or float
   1249         // (not sure if it's possible to hit this case).
   1250         Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
   1251         return false;
   1252       }
   1253       unsigned BaseEltSize = EltAsInt.getBitWidth();
   1254       if (BigEndian)
   1255         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
   1256       else
   1257         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
   1258     }
   1259     return true;
   1260   }
   1261   // Give up if the input isn't an int, float, or vector.  For example, we
   1262   // reject "(v4i16)(intptr_t)&a".
   1263   Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
   1264   return false;
   1265 }
   1266 
   1267 /// Cast an lvalue referring to a base subobject to a derived class, by
   1268 /// truncating the lvalue's path to the given length.
   1269 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
   1270                                const RecordDecl *TruncatedType,
   1271                                unsigned TruncatedElements) {
   1272   SubobjectDesignator &D = Result.Designator;
   1273 
   1274   // Check we actually point to a derived class object.
   1275   if (TruncatedElements == D.Entries.size())
   1276     return true;
   1277   assert(TruncatedElements >= D.MostDerivedPathLength &&
   1278          "not casting to a derived class");
   1279   if (!Result.checkSubobject(Info, E, CSK_Derived))
   1280     return false;
   1281 
   1282   // Truncate the path to the subobject, and remove any derived-to-base offsets.
   1283   const RecordDecl *RD = TruncatedType;
   1284   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
   1285     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
   1286     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
   1287     if (isVirtualBaseClass(D.Entries[I]))
   1288       Result.Offset -= Layout.getVBaseClassOffset(Base);
   1289     else
   1290       Result.Offset -= Layout.getBaseClassOffset(Base);
   1291     RD = Base;
   1292   }
   1293   D.Entries.resize(TruncatedElements);
   1294   return true;
   1295 }
   1296 
   1297 static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
   1298                                    const CXXRecordDecl *Derived,
   1299                                    const CXXRecordDecl *Base,
   1300                                    const ASTRecordLayout *RL = 0) {
   1301   if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
   1302   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
   1303   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
   1304 }
   1305 
   1306 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
   1307                              const CXXRecordDecl *DerivedDecl,
   1308                              const CXXBaseSpecifier *Base) {
   1309   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
   1310 
   1311   if (!Base->isVirtual()) {
   1312     HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
   1313     return true;
   1314   }
   1315 
   1316   SubobjectDesignator &D = Obj.Designator;
   1317   if (D.Invalid)
   1318     return false;
   1319 
   1320   // Extract most-derived object and corresponding type.
   1321   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
   1322   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
   1323     return false;
   1324 
   1325   // Find the virtual base class.
   1326   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
   1327   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
   1328   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
   1329   return true;
   1330 }
   1331 
   1332 /// Update LVal to refer to the given field, which must be a member of the type
   1333 /// currently described by LVal.
   1334 static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
   1335                                const FieldDecl *FD,
   1336                                const ASTRecordLayout *RL = 0) {
   1337   if (!RL)
   1338     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
   1339 
   1340   unsigned I = FD->getFieldIndex();
   1341   LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
   1342   LVal.addDecl(Info, E, FD);
   1343 }
   1344 
   1345 /// Update LVal to refer to the given indirect field.
   1346 static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
   1347                                        LValue &LVal,
   1348                                        const IndirectFieldDecl *IFD) {
   1349   for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
   1350                                          CE = IFD->chain_end(); C != CE; ++C)
   1351     HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
   1352 }
   1353 
   1354 /// Get the size of the given type in char units.
   1355 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
   1356                          QualType Type, CharUnits &Size) {
   1357   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
   1358   // extension.
   1359   if (Type->isVoidType() || Type->isFunctionType()) {
   1360     Size = CharUnits::One();
   1361     return true;
   1362   }
   1363 
   1364   if (!Type->isConstantSizeType()) {
   1365     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
   1366     // FIXME: Better diagnostic.
   1367     Info.Diag(Loc);
   1368     return false;
   1369   }
   1370 
   1371   Size = Info.Ctx.getTypeSizeInChars(Type);
   1372   return true;
   1373 }
   1374 
   1375 /// Update a pointer value to model pointer arithmetic.
   1376 /// \param Info - Information about the ongoing evaluation.
   1377 /// \param E - The expression being evaluated, for diagnostic purposes.
   1378 /// \param LVal - The pointer value to be updated.
   1379 /// \param EltTy - The pointee type represented by LVal.
   1380 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
   1381 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
   1382                                         LValue &LVal, QualType EltTy,
   1383                                         int64_t Adjustment) {
   1384   CharUnits SizeOfPointee;
   1385   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
   1386     return false;
   1387 
   1388   // Compute the new offset in the appropriate width.
   1389   LVal.Offset += Adjustment * SizeOfPointee;
   1390   LVal.adjustIndex(Info, E, Adjustment);
   1391   return true;
   1392 }
   1393 
   1394 /// Update an lvalue to refer to a component of a complex number.
   1395 /// \param Info - Information about the ongoing evaluation.
   1396 /// \param LVal - The lvalue to be updated.
   1397 /// \param EltTy - The complex number's component type.
   1398 /// \param Imag - False for the real component, true for the imaginary.
   1399 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
   1400                                        LValue &LVal, QualType EltTy,
   1401                                        bool Imag) {
   1402   if (Imag) {
   1403     CharUnits SizeOfComponent;
   1404     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
   1405       return false;
   1406     LVal.Offset += SizeOfComponent;
   1407   }
   1408   LVal.addComplex(Info, E, EltTy, Imag);
   1409   return true;
   1410 }
   1411 
   1412 /// Try to evaluate the initializer for a variable declaration.
   1413 static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
   1414                                 const VarDecl *VD,
   1415                                 CallStackFrame *Frame, APValue &Result) {
   1416   // If this is a parameter to an active constexpr function call, perform
   1417   // argument substitution.
   1418   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
   1419     // Assume arguments of a potential constant expression are unknown
   1420     // constant expressions.
   1421     if (Info.CheckingPotentialConstantExpression)
   1422       return false;
   1423     if (!Frame || !Frame->Arguments) {
   1424       Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
   1425       return false;
   1426     }
   1427     Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
   1428     return true;
   1429   }
   1430 
   1431   // Dig out the initializer, and use the declaration which it's attached to.
   1432   const Expr *Init = VD->getAnyInitializer(VD);
   1433   if (!Init || Init->isValueDependent()) {
   1434     // If we're checking a potential constant expression, the variable could be
   1435     // initialized later.
   1436     if (!Info.CheckingPotentialConstantExpression)
   1437       Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
   1438     return false;
   1439   }
   1440 
   1441   // If we're currently evaluating the initializer of this declaration, use that
   1442   // in-flight value.
   1443   if (Info.EvaluatingDecl == VD) {
   1444     Result = *Info.EvaluatingDeclValue;
   1445     return !Result.isUninit();
   1446   }
   1447 
   1448   // Never evaluate the initializer of a weak variable. We can't be sure that
   1449   // this is the definition which will be used.
   1450   if (VD->isWeak()) {
   1451     Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
   1452     return false;
   1453   }
   1454 
   1455   // Check that we can fold the initializer. In C++, we will have already done
   1456   // this in the cases where it matters for conformance.
   1457   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
   1458   if (!VD->evaluateValue(Notes)) {
   1459     Info.Diag(E, diag::note_constexpr_var_init_non_constant,
   1460               Notes.size() + 1) << VD;
   1461     Info.Note(VD->getLocation(), diag::note_declared_at);
   1462     Info.addNotes(Notes);
   1463     return false;
   1464   } else if (!VD->checkInitIsICE()) {
   1465     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
   1466                  Notes.size() + 1) << VD;
   1467     Info.Note(VD->getLocation(), diag::note_declared_at);
   1468     Info.addNotes(Notes);
   1469   }
   1470 
   1471   Result = *VD->getEvaluatedValue();
   1472   return true;
   1473 }
   1474 
   1475 static bool IsConstNonVolatile(QualType T) {
   1476   Qualifiers Quals = T.getQualifiers();
   1477   return Quals.hasConst() && !Quals.hasVolatile();
   1478 }
   1479 
   1480 /// Get the base index of the given base class within an APValue representing
   1481 /// the given derived class.
   1482 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
   1483                              const CXXRecordDecl *Base) {
   1484   Base = Base->getCanonicalDecl();
   1485   unsigned Index = 0;
   1486   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
   1487          E = Derived->bases_end(); I != E; ++I, ++Index) {
   1488     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
   1489       return Index;
   1490   }
   1491 
   1492   llvm_unreachable("base class missing from derived class's bases list");
   1493 }
   1494 
   1495 /// Extract the value of a character from a string literal. CharType is used to
   1496 /// determine the expected signedness of the result -- a string literal used to
   1497 /// initialize an array of 'signed char' or 'unsigned char' might contain chars
   1498 /// of the wrong signedness.
   1499 static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
   1500                                             uint64_t Index, QualType CharType) {
   1501   // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
   1502   const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
   1503   assert(S && "unexpected string literal expression kind");
   1504   assert(CharType->isIntegerType() && "unexpected character type");
   1505 
   1506   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
   1507                CharType->isUnsignedIntegerType());
   1508   if (Index < S->getLength())
   1509     Value = S->getCodeUnit(Index);
   1510   return Value;
   1511 }
   1512 
   1513 /// Extract the designated sub-object of an rvalue.
   1514 static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
   1515                              APValue &Obj, QualType ObjType,
   1516                              const SubobjectDesignator &Sub, QualType SubType) {
   1517   if (Sub.Invalid)
   1518     // A diagnostic will have already been produced.
   1519     return false;
   1520   if (Sub.isOnePastTheEnd()) {
   1521     Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
   1522                 (unsigned)diag::note_constexpr_read_past_end :
   1523                 (unsigned)diag::note_invalid_subexpr_in_const_expr);
   1524     return false;
   1525   }
   1526   if (Sub.Entries.empty())
   1527     return true;
   1528   if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
   1529     // This object might be initialized later.
   1530     return false;
   1531 
   1532   APValue *O = &Obj;
   1533   // Walk the designator's path to find the subobject.
   1534   for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
   1535     if (ObjType->isArrayType()) {
   1536       // Next subobject is an array element.
   1537       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
   1538       assert(CAT && "vla in literal type?");
   1539       uint64_t Index = Sub.Entries[I].ArrayIndex;
   1540       if (CAT->getSize().ule(Index)) {
   1541         // Note, it should not be possible to form a pointer with a valid
   1542         // designator which points more than one past the end of the array.
   1543         Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
   1544                     (unsigned)diag::note_constexpr_read_past_end :
   1545                     (unsigned)diag::note_invalid_subexpr_in_const_expr);
   1546         return false;
   1547       }
   1548       // An array object is represented as either an Array APValue or as an
   1549       // LValue which refers to a string literal.
   1550       if (O->isLValue()) {
   1551         assert(I == N - 1 && "extracting subobject of character?");
   1552         assert(!O->hasLValuePath() || O->getLValuePath().empty());
   1553         Obj = APValue(ExtractStringLiteralCharacter(
   1554           Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
   1555         return true;
   1556       } else if (O->getArrayInitializedElts() > Index)
   1557         O = &O->getArrayInitializedElt(Index);
   1558       else
   1559         O = &O->getArrayFiller();
   1560       ObjType = CAT->getElementType();
   1561     } else if (ObjType->isAnyComplexType()) {
   1562       // Next subobject is a complex number.
   1563       uint64_t Index = Sub.Entries[I].ArrayIndex;
   1564       if (Index > 1) {
   1565         Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
   1566                     (unsigned)diag::note_constexpr_read_past_end :
   1567                     (unsigned)diag::note_invalid_subexpr_in_const_expr);
   1568         return false;
   1569       }
   1570       assert(I == N - 1 && "extracting subobject of scalar?");
   1571       if (O->isComplexInt()) {
   1572         Obj = APValue(Index ? O->getComplexIntImag()
   1573                             : O->getComplexIntReal());
   1574       } else {
   1575         assert(O->isComplexFloat());
   1576         Obj = APValue(Index ? O->getComplexFloatImag()
   1577                             : O->getComplexFloatReal());
   1578       }
   1579       return true;
   1580     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
   1581       if (Field->isMutable()) {
   1582         Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
   1583           << Field;
   1584         Info.Note(Field->getLocation(), diag::note_declared_at);
   1585         return false;
   1586       }
   1587 
   1588       // Next subobject is a class, struct or union field.
   1589       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
   1590       if (RD->isUnion()) {
   1591         const FieldDecl *UnionField = O->getUnionField();
   1592         if (!UnionField ||
   1593             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
   1594           Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
   1595             << Field << !UnionField << UnionField;
   1596           return false;
   1597         }
   1598         O = &O->getUnionValue();
   1599       } else
   1600         O = &O->getStructField(Field->getFieldIndex());
   1601       ObjType = Field->getType();
   1602 
   1603       if (ObjType.isVolatileQualified()) {
   1604         if (Info.getLangOpts().CPlusPlus) {
   1605           // FIXME: Include a description of the path to the volatile subobject.
   1606           Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
   1607             << 2 << Field;
   1608           Info.Note(Field->getLocation(), diag::note_declared_at);
   1609         } else {
   1610           Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
   1611         }
   1612         return false;
   1613       }
   1614     } else {
   1615       // Next subobject is a base class.
   1616       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
   1617       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
   1618       O = &O->getStructBase(getBaseIndex(Derived, Base));
   1619       ObjType = Info.Ctx.getRecordType(Base);
   1620     }
   1621 
   1622     if (O->isUninit()) {
   1623       if (!Info.CheckingPotentialConstantExpression)
   1624         Info.Diag(E, diag::note_constexpr_read_uninit);
   1625       return false;
   1626     }
   1627   }
   1628 
   1629   // This may look super-stupid, but it serves an important purpose: if we just
   1630   // swapped Obj and *O, we'd create an object which had itself as a subobject.
   1631   // To avoid the leak, we ensure that Tmp ends up owning the original complete
   1632   // object, which is destroyed by Tmp's destructor.
   1633   APValue Tmp;
   1634   O->swap(Tmp);
   1635   Obj.swap(Tmp);
   1636   return true;
   1637 }
   1638 
   1639 /// Find the position where two subobject designators diverge, or equivalently
   1640 /// the length of the common initial subsequence.
   1641 static unsigned FindDesignatorMismatch(QualType ObjType,
   1642                                        const SubobjectDesignator &A,
   1643                                        const SubobjectDesignator &B,
   1644                                        bool &WasArrayIndex) {
   1645   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
   1646   for (/**/; I != N; ++I) {
   1647     if (!ObjType.isNull() &&
   1648         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
   1649       // Next subobject is an array element.
   1650       if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
   1651         WasArrayIndex = true;
   1652         return I;
   1653       }
   1654       if (ObjType->isAnyComplexType())
   1655         ObjType = ObjType->castAs<ComplexType>()->getElementType();
   1656       else
   1657         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
   1658     } else {
   1659       if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
   1660         WasArrayIndex = false;
   1661         return I;
   1662       }
   1663       if (const FieldDecl *FD = getAsField(A.Entries[I]))
   1664         // Next subobject is a field.
   1665         ObjType = FD->getType();
   1666       else
   1667         // Next subobject is a base class.
   1668         ObjType = QualType();
   1669     }
   1670   }
   1671   WasArrayIndex = false;
   1672   return I;
   1673 }
   1674 
   1675 /// Determine whether the given subobject designators refer to elements of the
   1676 /// same array object.
   1677 static bool AreElementsOfSameArray(QualType ObjType,
   1678                                    const SubobjectDesignator &A,
   1679                                    const SubobjectDesignator &B) {
   1680   if (A.Entries.size() != B.Entries.size())
   1681     return false;
   1682 
   1683   bool IsArray = A.MostDerivedArraySize != 0;
   1684   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
   1685     // A is a subobject of the array element.
   1686     return false;
   1687 
   1688   // If A (and B) designates an array element, the last entry will be the array
   1689   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
   1690   // of length 1' case, and the entire path must match.
   1691   bool WasArrayIndex;
   1692   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
   1693   return CommonLength >= A.Entries.size() - IsArray;
   1694 }
   1695 
   1696 /// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
   1697 /// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
   1698 /// for looking up the glvalue referred to by an entity of reference type.
   1699 ///
   1700 /// \param Info - Information about the ongoing evaluation.
   1701 /// \param Conv - The expression for which we are performing the conversion.
   1702 ///               Used for diagnostics.
   1703 /// \param Type - The type we expect this conversion to produce, before
   1704 ///               stripping cv-qualifiers in the case of a non-clas type.
   1705 /// \param LVal - The glvalue on which we are attempting to perform this action.
   1706 /// \param RVal - The produced value will be placed here.
   1707 static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
   1708                                            QualType Type,
   1709                                            const LValue &LVal, APValue &RVal) {
   1710   if (LVal.Designator.Invalid)
   1711     // A diagnostic will have already been produced.
   1712     return false;
   1713 
   1714   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
   1715 
   1716   if (!LVal.Base) {
   1717     // FIXME: Indirection through a null pointer deserves a specific diagnostic.
   1718     Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
   1719     return false;
   1720   }
   1721 
   1722   CallStackFrame *Frame = 0;
   1723   if (LVal.CallIndex) {
   1724     Frame = Info.getCallFrame(LVal.CallIndex);
   1725     if (!Frame) {
   1726       Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
   1727       NoteLValueLocation(Info, LVal.Base);
   1728       return false;
   1729     }
   1730   }
   1731 
   1732   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
   1733   // is not a constant expression (even if the object is non-volatile). We also
   1734   // apply this rule to C++98, in order to conform to the expected 'volatile'
   1735   // semantics.
   1736   if (Type.isVolatileQualified()) {
   1737     if (Info.getLangOpts().CPlusPlus)
   1738       Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
   1739     else
   1740       Info.Diag(Conv);
   1741     return false;
   1742   }
   1743 
   1744   if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
   1745     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
   1746     // In C++11, constexpr, non-volatile variables initialized with constant
   1747     // expressions are constant expressions too. Inside constexpr functions,
   1748     // parameters are constant expressions even if they're non-const.
   1749     // In C, such things can also be folded, although they are not ICEs.
   1750     const VarDecl *VD = dyn_cast<VarDecl>(D);
   1751     if (VD) {
   1752       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
   1753         VD = VDef;
   1754     }
   1755     if (!VD || VD->isInvalidDecl()) {
   1756       Info.Diag(Conv);
   1757       return false;
   1758     }
   1759 
   1760     // DR1313: If the object is volatile-qualified but the glvalue was not,
   1761     // behavior is undefined so the result is not a constant expression.
   1762     QualType VT = VD->getType();
   1763     if (VT.isVolatileQualified()) {
   1764       if (Info.getLangOpts().CPlusPlus) {
   1765         Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
   1766         Info.Note(VD->getLocation(), diag::note_declared_at);
   1767       } else {
   1768         Info.Diag(Conv);
   1769       }
   1770       return false;
   1771     }
   1772 
   1773     if (!isa<ParmVarDecl>(VD)) {
   1774       if (VD->isConstexpr()) {
   1775         // OK, we can read this variable.
   1776       } else if (VT->isIntegralOrEnumerationType()) {
   1777         if (!VT.isConstQualified()) {
   1778           if (Info.getLangOpts().CPlusPlus) {
   1779             Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
   1780             Info.Note(VD->getLocation(), diag::note_declared_at);
   1781           } else {
   1782             Info.Diag(Conv);
   1783           }
   1784           return false;
   1785         }
   1786       } else if (VT->isFloatingType() && VT.isConstQualified()) {
   1787         // We support folding of const floating-point types, in order to make
   1788         // static const data members of such types (supported as an extension)
   1789         // more useful.
   1790         if (Info.getLangOpts().CPlusPlus0x) {
   1791           Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
   1792           Info.Note(VD->getLocation(), diag::note_declared_at);
   1793         } else {
   1794           Info.CCEDiag(Conv);
   1795         }
   1796       } else {
   1797         // FIXME: Allow folding of values of any literal type in all languages.
   1798         if (Info.getLangOpts().CPlusPlus0x) {
   1799           Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
   1800           Info.Note(VD->getLocation(), diag::note_declared_at);
   1801         } else {
   1802           Info.Diag(Conv);
   1803         }
   1804         return false;
   1805       }
   1806     }
   1807 
   1808     if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
   1809       return false;
   1810 
   1811     if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
   1812       return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
   1813 
   1814     // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
   1815     // conversion. This happens when the declaration and the lvalue should be
   1816     // considered synonymous, for instance when initializing an array of char
   1817     // from a string literal. Continue as if the initializer lvalue was the
   1818     // value we were originally given.
   1819     assert(RVal.getLValueOffset().isZero() &&
   1820            "offset for lvalue init of non-reference");
   1821     Base = RVal.getLValueBase().get<const Expr*>();
   1822 
   1823     if (unsigned CallIndex = RVal.getLValueCallIndex()) {
   1824       Frame = Info.getCallFrame(CallIndex);
   1825       if (!Frame) {
   1826         Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
   1827         NoteLValueLocation(Info, RVal.getLValueBase());
   1828         return false;
   1829       }
   1830     } else {
   1831       Frame = 0;
   1832     }
   1833   }
   1834 
   1835   // Volatile temporary objects cannot be read in constant expressions.
   1836   if (Base->getType().isVolatileQualified()) {
   1837     if (Info.getLangOpts().CPlusPlus) {
   1838       Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
   1839       Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
   1840     } else {
   1841       Info.Diag(Conv);
   1842     }
   1843     return false;
   1844   }
   1845 
   1846   if (Frame) {
   1847     // If this is a temporary expression with a nontrivial initializer, grab the
   1848     // value from the relevant stack frame.
   1849     RVal = Frame->Temporaries[Base];
   1850   } else if (const CompoundLiteralExpr *CLE
   1851              = dyn_cast<CompoundLiteralExpr>(Base)) {
   1852     // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
   1853     // initializer until now for such expressions. Such an expression can't be
   1854     // an ICE in C, so this only matters for fold.
   1855     assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
   1856     if (!Evaluate(RVal, Info, CLE->getInitializer()))
   1857       return false;
   1858   } else if (isa<StringLiteral>(Base)) {
   1859     // We represent a string literal array as an lvalue pointing at the
   1860     // corresponding expression, rather than building an array of chars.
   1861     // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
   1862     RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
   1863   } else {
   1864     Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
   1865     return false;
   1866   }
   1867 
   1868   return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
   1869                           Type);
   1870 }
   1871 
   1872 /// Build an lvalue for the object argument of a member function call.
   1873 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
   1874                                    LValue &This) {
   1875   if (Object->getType()->isPointerType())
   1876     return EvaluatePointer(Object, This, Info);
   1877 
   1878   if (Object->isGLValue())
   1879     return EvaluateLValue(Object, This, Info);
   1880 
   1881   if (Object->getType()->isLiteralType())
   1882     return EvaluateTemporary(Object, This, Info);
   1883 
   1884   return false;
   1885 }
   1886 
   1887 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
   1888 /// lvalue referring to the result.
   1889 ///
   1890 /// \param Info - Information about the ongoing evaluation.
   1891 /// \param BO - The member pointer access operation.
   1892 /// \param LV - Filled in with a reference to the resulting object.
   1893 /// \param IncludeMember - Specifies whether the member itself is included in
   1894 ///        the resulting LValue subobject designator. This is not possible when
   1895 ///        creating a bound member function.
   1896 /// \return The field or method declaration to which the member pointer refers,
   1897 ///         or 0 if evaluation fails.
   1898 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
   1899                                                   const BinaryOperator *BO,
   1900                                                   LValue &LV,
   1901                                                   bool IncludeMember = true) {
   1902   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
   1903 
   1904   bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
   1905   if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
   1906     return 0;
   1907 
   1908   MemberPtr MemPtr;
   1909   if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
   1910     return 0;
   1911 
   1912   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
   1913   // member value, the behavior is undefined.
   1914   if (!MemPtr.getDecl())
   1915     return 0;
   1916 
   1917   if (!EvalObjOK)
   1918     return 0;
   1919 
   1920   if (MemPtr.isDerivedMember()) {
   1921     // This is a member of some derived class. Truncate LV appropriately.
   1922     // The end of the derived-to-base path for the base object must match the
   1923     // derived-to-base path for the member pointer.
   1924     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
   1925         LV.Designator.Entries.size())
   1926       return 0;
   1927     unsigned PathLengthToMember =
   1928         LV.Designator.Entries.size() - MemPtr.Path.size();
   1929     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
   1930       const CXXRecordDecl *LVDecl = getAsBaseClass(
   1931           LV.Designator.Entries[PathLengthToMember + I]);
   1932       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
   1933       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
   1934         return 0;
   1935     }
   1936 
   1937     // Truncate the lvalue to the appropriate derived class.
   1938     if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
   1939                             PathLengthToMember))
   1940       return 0;
   1941   } else if (!MemPtr.Path.empty()) {
   1942     // Extend the LValue path with the member pointer's path.
   1943     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
   1944                                   MemPtr.Path.size() + IncludeMember);
   1945 
   1946     // Walk down to the appropriate base class.
   1947     QualType LVType = BO->getLHS()->getType();
   1948     if (const PointerType *PT = LVType->getAs<PointerType>())
   1949       LVType = PT->getPointeeType();
   1950     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
   1951     assert(RD && "member pointer access on non-class-type expression");
   1952     // The first class in the path is that of the lvalue.
   1953     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
   1954       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
   1955       HandleLValueDirectBase(Info, BO, LV, RD, Base);
   1956       RD = Base;
   1957     }
   1958     // Finally cast to the class containing the member.
   1959     HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
   1960   }
   1961 
   1962   // Add the member. Note that we cannot build bound member functions here.
   1963   if (IncludeMember) {
   1964     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
   1965       HandleLValueMember(Info, BO, LV, FD);
   1966     else if (const IndirectFieldDecl *IFD =
   1967                dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
   1968       HandleLValueIndirectMember(Info, BO, LV, IFD);
   1969     else
   1970       llvm_unreachable("can't construct reference to bound member function");
   1971   }
   1972 
   1973   return MemPtr.getDecl();
   1974 }
   1975 
   1976 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
   1977 /// the provided lvalue, which currently refers to the base object.
   1978 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
   1979                                     LValue &Result) {
   1980   SubobjectDesignator &D = Result.Designator;
   1981   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
   1982     return false;
   1983 
   1984   QualType TargetQT = E->getType();
   1985   if (const PointerType *PT = TargetQT->getAs<PointerType>())
   1986     TargetQT = PT->getPointeeType();
   1987 
   1988   // Check this cast lands within the final derived-to-base subobject path.
   1989   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
   1990     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
   1991       << D.MostDerivedType << TargetQT;
   1992     return false;
   1993   }
   1994 
   1995   // Check the type of the final cast. We don't need to check the path,
   1996   // since a cast can only be formed if the path is unique.
   1997   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
   1998   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
   1999   const CXXRecordDecl *FinalType;
   2000   if (NewEntriesSize == D.MostDerivedPathLength)
   2001     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
   2002   else
   2003     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
   2004   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
   2005     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
   2006       << D.MostDerivedType << TargetQT;
   2007     return false;
   2008   }
   2009 
   2010   // Truncate the lvalue to the appropriate derived class.
   2011   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
   2012 }
   2013 
   2014 namespace {
   2015 enum EvalStmtResult {
   2016   /// Evaluation failed.
   2017   ESR_Failed,
   2018   /// Hit a 'return' statement.
   2019   ESR_Returned,
   2020   /// Evaluation succeeded.
   2021   ESR_Succeeded
   2022 };
   2023 }
   2024 
   2025 // Evaluate a statement.
   2026 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
   2027                                    const Stmt *S) {
   2028   switch (S->getStmtClass()) {
   2029   default:
   2030     return ESR_Failed;
   2031 
   2032   case Stmt::NullStmtClass:
   2033   case Stmt::DeclStmtClass:
   2034     return ESR_Succeeded;
   2035 
   2036   case Stmt::ReturnStmtClass: {
   2037     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
   2038     if (!Evaluate(Result, Info, RetExpr))
   2039       return ESR_Failed;
   2040     return ESR_Returned;
   2041   }
   2042 
   2043   case Stmt::CompoundStmtClass: {
   2044     const CompoundStmt *CS = cast<CompoundStmt>(S);
   2045     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
   2046            BE = CS->body_end(); BI != BE; ++BI) {
   2047       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
   2048       if (ESR != ESR_Succeeded)
   2049         return ESR;
   2050     }
   2051     return ESR_Succeeded;
   2052   }
   2053   }
   2054 }
   2055 
   2056 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
   2057 /// default constructor. If so, we'll fold it whether or not it's marked as
   2058 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
   2059 /// so we need special handling.
   2060 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
   2061                                            const CXXConstructorDecl *CD,
   2062                                            bool IsValueInitialization) {
   2063   if (!CD->isTrivial() || !CD->isDefaultConstructor())
   2064     return false;
   2065 
   2066   // Value-initialization does not call a trivial default constructor, so such a
   2067   // call is a core constant expression whether or not the constructor is
   2068   // constexpr.
   2069   if (!CD->isConstexpr() && !IsValueInitialization) {
   2070     if (Info.getLangOpts().CPlusPlus0x) {
   2071       // FIXME: If DiagDecl is an implicitly-declared special member function,
   2072       // we should be much more explicit about why it's not constexpr.
   2073       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
   2074         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
   2075       Info.Note(CD->getLocation(), diag::note_declared_at);
   2076     } else {
   2077       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
   2078     }
   2079   }
   2080   return true;
   2081 }
   2082 
   2083 /// CheckConstexprFunction - Check that a function can be called in a constant
   2084 /// expression.
   2085 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
   2086                                    const FunctionDecl *Declaration,
   2087                                    const FunctionDecl *Definition) {
   2088   // Potential constant expressions can contain calls to declared, but not yet
   2089   // defined, constexpr functions.
   2090   if (Info.CheckingPotentialConstantExpression && !Definition &&
   2091       Declaration->isConstexpr())
   2092     return false;
   2093 
   2094   // Can we evaluate this function call?
   2095   if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
   2096     return true;
   2097 
   2098   if (Info.getLangOpts().CPlusPlus0x) {
   2099     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
   2100     // FIXME: If DiagDecl is an implicitly-declared special member function, we
   2101     // should be much more explicit about why it's not constexpr.
   2102     Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
   2103       << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
   2104       << DiagDecl;
   2105     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
   2106   } else {
   2107     Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
   2108   }
   2109   return false;
   2110 }
   2111 
   2112 namespace {
   2113 typedef SmallVector<APValue, 8> ArgVector;
   2114 }
   2115 
   2116 /// EvaluateArgs - Evaluate the arguments to a function call.
   2117 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
   2118                          EvalInfo &Info) {
   2119   bool Success = true;
   2120   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
   2121        I != E; ++I) {
   2122     if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
   2123       // If we're checking for a potential constant expression, evaluate all
   2124       // initializers even if some of them fail.
   2125       if (!Info.keepEvaluatingAfterFailure())
   2126         return false;
   2127       Success = false;
   2128     }
   2129   }
   2130   return Success;
   2131 }
   2132 
   2133 /// Evaluate a function call.
   2134 static bool HandleFunctionCall(SourceLocation CallLoc,
   2135                                const FunctionDecl *Callee, const LValue *This,
   2136                                ArrayRef<const Expr*> Args, const Stmt *Body,
   2137                                EvalInfo &Info, APValue &Result) {
   2138   ArgVector ArgValues(Args.size());
   2139   if (!EvaluateArgs(Args, ArgValues, Info))
   2140     return false;
   2141 
   2142   if (!Info.CheckCallLimit(CallLoc))
   2143     return false;
   2144 
   2145   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
   2146   return EvaluateStmt(Result, Info, Body) == ESR_Returned;
   2147 }
   2148 
   2149 /// Evaluate a constructor call.
   2150 static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
   2151                                   ArrayRef<const Expr*> Args,
   2152                                   const CXXConstructorDecl *Definition,
   2153                                   EvalInfo &Info, APValue &Result) {
   2154   ArgVector ArgValues(Args.size());
   2155   if (!EvaluateArgs(Args, ArgValues, Info))
   2156     return false;
   2157 
   2158   if (!Info.CheckCallLimit(CallLoc))
   2159     return false;
   2160 
   2161   const CXXRecordDecl *RD = Definition->getParent();
   2162   if (RD->getNumVBases()) {
   2163     Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
   2164     return false;
   2165   }
   2166 
   2167   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
   2168 
   2169   // If it's a delegating constructor, just delegate.
   2170   if (Definition->isDelegatingConstructor()) {
   2171     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
   2172     return EvaluateInPlace(Result, Info, This, (*I)->getInit());
   2173   }
   2174 
   2175   // For a trivial copy or move constructor, perform an APValue copy. This is
   2176   // essential for unions, where the operations performed by the constructor
   2177   // cannot be represented by ctor-initializers.
   2178   if (Definition->isDefaulted() &&
   2179       ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
   2180        (Definition->isMoveConstructor() && Definition->isTrivial()))) {
   2181     LValue RHS;
   2182     RHS.setFrom(Info.Ctx, ArgValues[0]);
   2183     return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
   2184                                           RHS, Result);
   2185   }
   2186 
   2187   // Reserve space for the struct members.
   2188   if (!RD->isUnion() && Result.isUninit())
   2189     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
   2190                      std::distance(RD->field_begin(), RD->field_end()));
   2191 
   2192   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
   2193 
   2194   bool Success = true;
   2195   unsigned BasesSeen = 0;
   2196 #ifndef NDEBUG
   2197   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
   2198 #endif
   2199   for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
   2200        E = Definition->init_end(); I != E; ++I) {
   2201     LValue Subobject = This;
   2202     APValue *Value = &Result;
   2203 
   2204     // Determine the subobject to initialize.
   2205     if ((*I)->isBaseInitializer()) {
   2206       QualType BaseType((*I)->getBaseClass(), 0);
   2207 #ifndef NDEBUG
   2208       // Non-virtual base classes are initialized in the order in the class
   2209       // definition. We have already checked for virtual base classes.
   2210       assert(!BaseIt->isVirtual() && "virtual base for literal type");
   2211       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
   2212              "base class initializers not in expected order");
   2213       ++BaseIt;
   2214 #endif
   2215       HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
   2216                              BaseType->getAsCXXRecordDecl(), &Layout);
   2217       Value = &Result.getStructBase(BasesSeen++);
   2218     } else if (FieldDecl *FD = (*I)->getMember()) {
   2219       HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
   2220       if (RD->isUnion()) {
   2221         Result = APValue(FD);
   2222         Value = &Result.getUnionValue();
   2223       } else {
   2224         Value = &Result.getStructField(FD->getFieldIndex());
   2225       }
   2226     } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
   2227       // Walk the indirect field decl's chain to find the object to initialize,
   2228       // and make sure we've initialized every step along it.
   2229       for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
   2230                                              CE = IFD->chain_end();
   2231            C != CE; ++C) {
   2232         FieldDecl *FD = cast<FieldDecl>(*C);
   2233         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
   2234         // Switch the union field if it differs. This happens if we had
   2235         // preceding zero-initialization, and we're now initializing a union
   2236         // subobject other than the first.
   2237         // FIXME: In this case, the values of the other subobjects are
   2238         // specified, since zero-initialization sets all padding bits to zero.
   2239         if (Value->isUninit() ||
   2240             (Value->isUnion() && Value->getUnionField() != FD)) {
   2241           if (CD->isUnion())
   2242             *Value = APValue(FD);
   2243           else
   2244             *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
   2245                              std::distance(CD->field_begin(), CD->field_end()));
   2246         }
   2247         HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
   2248         if (CD->isUnion())
   2249           Value = &Value->getUnionValue();
   2250         else
   2251           Value = &Value->getStructField(FD->getFieldIndex());
   2252       }
   2253     } else {
   2254       llvm_unreachable("unknown base initializer kind");
   2255     }
   2256 
   2257     if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
   2258                          (*I)->isBaseInitializer()
   2259                                       ? CCEK_Constant : CCEK_MemberInit)) {
   2260       // If we're checking for a potential constant expression, evaluate all
   2261       // initializers even if some of them fail.
   2262       if (!Info.keepEvaluatingAfterFailure())
   2263         return false;
   2264       Success = false;
   2265     }
   2266   }
   2267 
   2268   return Success;
   2269 }
   2270 
   2271 namespace {
   2272 class HasSideEffect
   2273   : public ConstStmtVisitor<HasSideEffect, bool> {
   2274   const ASTContext &Ctx;
   2275 public:
   2276 
   2277   HasSideEffect(const ASTContext &C) : Ctx(C) {}
   2278 
   2279   // Unhandled nodes conservatively default to having side effects.
   2280   bool VisitStmt(const Stmt *S) {
   2281     return true;
   2282   }
   2283 
   2284   bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
   2285   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
   2286     return Visit(E->getResultExpr());
   2287   }
   2288   bool VisitDeclRefExpr(const DeclRefExpr *E) {
   2289     if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
   2290       return true;
   2291     return false;
   2292   }
   2293   bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
   2294     if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
   2295       return true;
   2296     return false;
   2297   }
   2298 
   2299   // We don't want to evaluate BlockExprs multiple times, as they generate
   2300   // a ton of code.
   2301   bool VisitBlockExpr(const BlockExpr *E) { return true; }
   2302   bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
   2303   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
   2304     { return Visit(E->getInitializer()); }
   2305   bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
   2306   bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
   2307   bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
   2308   bool VisitStringLiteral(const StringLiteral *E) { return false; }
   2309   bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
   2310   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
   2311     { return false; }
   2312   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
   2313     { return Visit(E->getLHS()) || Visit(E->getRHS()); }
   2314   bool VisitChooseExpr(const ChooseExpr *E)
   2315     { return Visit(E->getChosenSubExpr(Ctx)); }
   2316   bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
   2317   bool VisitBinAssign(const BinaryOperator *E) { return true; }
   2318   bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
   2319   bool VisitBinaryOperator(const BinaryOperator *E)
   2320   { return Visit(E->getLHS()) || Visit(E->getRHS()); }
   2321   bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
   2322   bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
   2323   bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
   2324   bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
   2325   bool VisitUnaryDeref(const UnaryOperator *E) {
   2326     if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
   2327       return true;
   2328     return Visit(E->getSubExpr());
   2329   }
   2330   bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
   2331 
   2332   // Has side effects if any element does.
   2333   bool VisitInitListExpr(const InitListExpr *E) {
   2334     for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
   2335       if (Visit(E->getInit(i))) return true;
   2336     if (const Expr *filler = E->getArrayFiller())
   2337       return Visit(filler);
   2338     return false;
   2339   }
   2340 
   2341   bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
   2342 };
   2343 
   2344 class OpaqueValueEvaluation {
   2345   EvalInfo &info;
   2346   OpaqueValueExpr *opaqueValue;
   2347 
   2348 public:
   2349   OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
   2350                         Expr *value)
   2351     : info(info), opaqueValue(opaqueValue) {
   2352 
   2353     // If evaluation fails, fail immediately.
   2354     if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
   2355       this->opaqueValue = 0;
   2356       return;
   2357     }
   2358   }
   2359 
   2360   bool hasError() const { return opaqueValue == 0; }
   2361 
   2362   ~OpaqueValueEvaluation() {
   2363     // FIXME: For a recursive constexpr call, an outer stack frame might have
   2364     // been using this opaque value too, and will now have to re-evaluate the
   2365     // source expression.
   2366     if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
   2367   }
   2368 };
   2369 
   2370 } // end anonymous namespace
   2371 
   2372 //===----------------------------------------------------------------------===//
   2373 // Generic Evaluation
   2374 //===----------------------------------------------------------------------===//
   2375 namespace {
   2376 
   2377 // FIXME: RetTy is always bool. Remove it.
   2378 template <class Derived, typename RetTy=bool>
   2379 class ExprEvaluatorBase
   2380   : public ConstStmtVisitor<Derived, RetTy> {
   2381 private:
   2382   RetTy DerivedSuccess(const APValue &V, const Expr *E) {
   2383     return static_cast<Derived*>(this)->Success(V, E);
   2384   }
   2385   RetTy DerivedZeroInitialization(const Expr *E) {
   2386     return static_cast<Derived*>(this)->ZeroInitialization(E);
   2387   }
   2388 
   2389   // Check whether a conditional operator with a non-constant condition is a
   2390   // potential constant expression. If neither arm is a potential constant
   2391   // expression, then the conditional operator is not either.
   2392   template<typename ConditionalOperator>
   2393   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
   2394     assert(Info.CheckingPotentialConstantExpression);
   2395 
   2396     // Speculatively evaluate both arms.
   2397     {
   2398       llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
   2399       SpeculativeEvaluationRAII Speculate(Info, &Diag);
   2400 
   2401       StmtVisitorTy::Visit(E->getFalseExpr());
   2402       if (Diag.empty())
   2403         return;
   2404 
   2405       Diag.clear();
   2406       StmtVisitorTy::Visit(E->getTrueExpr());
   2407       if (Diag.empty())
   2408         return;
   2409     }
   2410 
   2411     Error(E, diag::note_constexpr_conditional_never_const);
   2412   }
   2413 
   2414 
   2415   template<typename ConditionalOperator>
   2416   bool HandleConditionalOperator(const ConditionalOperator *E) {
   2417     bool BoolResult;
   2418     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
   2419       if (Info.CheckingPotentialConstantExpression)
   2420         CheckPotentialConstantConditional(E);
   2421       return false;
   2422     }
   2423 
   2424     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
   2425     return StmtVisitorTy::Visit(EvalExpr);
   2426   }
   2427 
   2428 protected:
   2429   EvalInfo &Info;
   2430   typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
   2431   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
   2432 
   2433   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
   2434     return Info.CCEDiag(E, D);
   2435   }
   2436 
   2437   RetTy ZeroInitialization(const Expr *E) { return Error(E); }
   2438 
   2439 public:
   2440   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
   2441 
   2442   EvalInfo &getEvalInfo() { return Info; }
   2443 
   2444   /// Report an evaluation error. This should only be called when an error is
   2445   /// first discovered. When propagating an error, just return false.
   2446   bool Error(const Expr *E, diag::kind D) {
   2447     Info.Diag(E, D);
   2448     return false;
   2449   }
   2450   bool Error(const Expr *E) {
   2451     return Error(E, diag::note_invalid_subexpr_in_const_expr);
   2452   }
   2453 
   2454   RetTy VisitStmt(const Stmt *) {
   2455     llvm_unreachable("Expression evaluator should not be called on stmts");
   2456   }
   2457   RetTy VisitExpr(const Expr *E) {
   2458     return Error(E);
   2459   }
   2460 
   2461   RetTy VisitParenExpr(const ParenExpr *E)
   2462     { return StmtVisitorTy::Visit(E->getSubExpr()); }
   2463   RetTy VisitUnaryExtension(const UnaryOperator *E)
   2464     { return StmtVisitorTy::Visit(E->getSubExpr()); }
   2465   RetTy VisitUnaryPlus(const UnaryOperator *E)
   2466     { return StmtVisitorTy::Visit(E->getSubExpr()); }
   2467   RetTy VisitChooseExpr(const ChooseExpr *E)
   2468     { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
   2469   RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
   2470     { return StmtVisitorTy::Visit(E->getResultExpr()); }
   2471   RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
   2472     { return StmtVisitorTy::Visit(E->getReplacement()); }
   2473   RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
   2474     { return StmtVisitorTy::Visit(E->getExpr()); }
   2475   // We cannot create any objects for which cleanups are required, so there is
   2476   // nothing to do here; all cleanups must come from unevaluated subexpressions.
   2477   RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
   2478     { return StmtVisitorTy::Visit(E->getSubExpr()); }
   2479 
   2480   RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
   2481     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
   2482     return static_cast<Derived*>(this)->VisitCastExpr(E);
   2483   }
   2484   RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
   2485     CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
   2486     return static_cast<Derived*>(this)->VisitCastExpr(E);
   2487   }
   2488 
   2489   RetTy VisitBinaryOperator(const BinaryOperator *E) {
   2490     switch (E->getOpcode()) {
   2491     default:
   2492       return Error(E);
   2493 
   2494     case BO_Comma:
   2495       VisitIgnoredValue(E->getLHS());
   2496       return StmtVisitorTy::Visit(E->getRHS());
   2497 
   2498     case BO_PtrMemD:
   2499     case BO_PtrMemI: {
   2500       LValue Obj;
   2501       if (!HandleMemberPointerAccess(Info, E, Obj))
   2502         return false;
   2503       APValue Result;
   2504       if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
   2505         return false;
   2506       return DerivedSuccess(Result, E);
   2507     }
   2508     }
   2509   }
   2510 
   2511   RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
   2512     // Cache the value of the common expression.
   2513     OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
   2514     if (opaque.hasError())
   2515       return false;
   2516 
   2517     return HandleConditionalOperator(E);
   2518   }
   2519 
   2520   RetTy VisitConditionalOperator(const ConditionalOperator *E) {
   2521     bool IsBcpCall = false;
   2522     // If the condition (ignoring parens) is a __builtin_constant_p call,
   2523     // the result is a constant expression if it can be folded without
   2524     // side-effects. This is an important GNU extension. See GCC PR38377
   2525     // for discussion.
   2526     if (const CallExpr *CallCE =
   2527           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
   2528       if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
   2529         IsBcpCall = true;
   2530 
   2531     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
   2532     // constant expression; we can't check whether it's potentially foldable.
   2533     if (Info.CheckingPotentialConstantExpression && IsBcpCall)
   2534       return false;
   2535 
   2536     FoldConstant Fold(Info);
   2537 
   2538     if (!HandleConditionalOperator(E))
   2539       return false;
   2540 
   2541     if (IsBcpCall)
   2542       Fold.Fold(Info);
   2543 
   2544     return true;
   2545   }
   2546 
   2547   RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
   2548     const APValue *Value = Info.getOpaqueValue(E);
   2549     if (!Value) {
   2550       const Expr *Source = E->getSourceExpr();
   2551       if (!Source)
   2552         return Error(E);
   2553       if (Source == E) { // sanity checking.
   2554         assert(0 && "OpaqueValueExpr recursively refers to itself");
   2555         return Error(E);
   2556       }
   2557       return StmtVisitorTy::Visit(Source);
   2558     }
   2559     return DerivedSuccess(*Value, E);
   2560   }
   2561 
   2562   RetTy VisitCallExpr(const CallExpr *E) {
   2563     const Expr *Callee = E->getCallee()->IgnoreParens();
   2564     QualType CalleeType = Callee->getType();
   2565 
   2566     const FunctionDecl *FD = 0;
   2567     LValue *This = 0, ThisVal;
   2568     llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
   2569     bool HasQualifier = false;
   2570 
   2571     // Extract function decl and 'this' pointer from the callee.
   2572     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
   2573       const ValueDecl *Member = 0;
   2574       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
   2575         // Explicit bound member calls, such as x.f() or p->g();
   2576         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
   2577           return false;
   2578         Member = ME->getMemberDecl();
   2579         This = &ThisVal;
   2580         HasQualifier = ME->hasQualifier();
   2581       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
   2582         // Indirect bound member calls ('.*' or '->*').
   2583         Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
   2584         if (!Member) return false;
   2585         This = &ThisVal;
   2586       } else
   2587         return Error(Callee);
   2588 
   2589       FD = dyn_cast<FunctionDecl>(Member);
   2590       if (!FD)
   2591         return Error(Callee);
   2592     } else if (CalleeType->isFunctionPointerType()) {
   2593       LValue Call;
   2594       if (!EvaluatePointer(Callee, Call, Info))
   2595         return false;
   2596 
   2597       if (!Call.getLValueOffset().isZero())
   2598         return Error(Callee);
   2599       FD = dyn_cast_or_null<FunctionDecl>(
   2600                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
   2601       if (!FD)
   2602         return Error(Callee);
   2603 
   2604       // Overloaded operator calls to member functions are represented as normal
   2605       // calls with '*this' as the first argument.
   2606       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
   2607       if (MD && !MD->isStatic()) {
   2608         // FIXME: When selecting an implicit conversion for an overloaded
   2609         // operator delete, we sometimes try to evaluate calls to conversion
   2610         // operators without a 'this' parameter!
   2611         if (Args.empty())
   2612           return Error(E);
   2613 
   2614         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
   2615           return false;
   2616         This = &ThisVal;
   2617         Args = Args.slice(1);
   2618       }
   2619 
   2620       // Don't call function pointers which have been cast to some other type.
   2621       if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
   2622         return Error(E);
   2623     } else
   2624       return Error(E);
   2625 
   2626     if (This && !This->checkSubobject(Info, E, CSK_This))
   2627       return false;
   2628 
   2629     // DR1358 allows virtual constexpr functions in some cases. Don't allow
   2630     // calls to such functions in constant expressions.
   2631     if (This && !HasQualifier &&
   2632         isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
   2633       return Error(E, diag::note_constexpr_virtual_call);
   2634 
   2635     const FunctionDecl *Definition = 0;
   2636     Stmt *Body = FD->getBody(Definition);
   2637     APValue Result;
   2638 
   2639     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
   2640         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
   2641                             Info, Result))
   2642       return false;
   2643 
   2644     return DerivedSuccess(Result, E);
   2645   }
   2646 
   2647   RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
   2648     return StmtVisitorTy::Visit(E->getInitializer());
   2649   }
   2650   RetTy VisitInitListExpr(const InitListExpr *E) {
   2651     if (E->getNumInits() == 0)
   2652       return DerivedZeroInitialization(E);
   2653     if (E->getNumInits() == 1)
   2654       return StmtVisitorTy::Visit(E->getInit(0));
   2655     return Error(E);
   2656   }
   2657   RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
   2658     return DerivedZeroInitialization(E);
   2659   }
   2660   RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
   2661     return DerivedZeroInitialization(E);
   2662   }
   2663   RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
   2664     return DerivedZeroInitialization(E);
   2665   }
   2666 
   2667   /// A member expression where the object is a prvalue is itself a prvalue.
   2668   RetTy VisitMemberExpr(const MemberExpr *E) {
   2669     assert(!E->isArrow() && "missing call to bound member function?");
   2670 
   2671     APValue Val;
   2672     if (!Evaluate(Val, Info, E->getBase()))
   2673       return false;
   2674 
   2675     QualType BaseTy = E->getBase()->getType();
   2676 
   2677     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
   2678     if (!FD) return Error(E);
   2679     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
   2680     assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
   2681            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
   2682 
   2683     SubobjectDesignator Designator(BaseTy);
   2684     Designator.addDeclUnchecked(FD);
   2685 
   2686     return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
   2687            DerivedSuccess(Val, E);
   2688   }
   2689 
   2690   RetTy VisitCastExpr(const CastExpr *E) {
   2691     switch (E->getCastKind()) {
   2692     default:
   2693       break;
   2694 
   2695     case CK_AtomicToNonAtomic:
   2696     case CK_NonAtomicToAtomic:
   2697     case CK_NoOp:
   2698     case CK_UserDefinedConversion:
   2699       return StmtVisitorTy::Visit(E->getSubExpr());
   2700 
   2701     case CK_LValueToRValue: {
   2702       LValue LVal;
   2703       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
   2704         return false;
   2705       APValue RVal;
   2706       // Note, we use the subexpression's type in order to retain cv-qualifiers.
   2707       if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
   2708                                           LVal, RVal))
   2709         return false;
   2710       return DerivedSuccess(RVal, E);
   2711     }
   2712     }
   2713 
   2714     return Error(E);
   2715   }
   2716 
   2717   /// Visit a value which is evaluated, but whose value is ignored.
   2718   void VisitIgnoredValue(const Expr *E) {
   2719     APValue Scratch;
   2720     if (!Evaluate(Scratch, Info, E))
   2721       Info.EvalStatus.HasSideEffects = true;
   2722   }
   2723 };
   2724 
   2725 }
   2726 
   2727 //===----------------------------------------------------------------------===//
   2728 // Common base class for lvalue and temporary evaluation.
   2729 //===----------------------------------------------------------------------===//
   2730 namespace {
   2731 template<class Derived>
   2732 class LValueExprEvaluatorBase
   2733   : public ExprEvaluatorBase<Derived, bool> {
   2734 protected:
   2735   LValue &Result;
   2736   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
   2737   typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
   2738 
   2739   bool Success(APValue::LValueBase B) {
   2740     Result.set(B);
   2741     return true;
   2742   }
   2743 
   2744 public:
   2745   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
   2746     ExprEvaluatorBaseTy(Info), Result(Result) {}
   2747 
   2748   bool Success(const APValue &V, const Expr *E) {
   2749     Result.setFrom(this->Info.Ctx, V);
   2750     return true;
   2751   }
   2752 
   2753   bool VisitMemberExpr(const MemberExpr *E) {
   2754     // Handle non-static data members.
   2755     QualType BaseTy;
   2756     if (E->isArrow()) {
   2757       if (!EvaluatePointer(E->getBase(), Result, this->Info))
   2758         return false;
   2759       BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
   2760     } else if (E->getBase()->isRValue()) {
   2761       assert(E->getBase()->getType()->isRecordType());
   2762       if (!EvaluateTemporary(E->getBase(), Result, this->Info))
   2763         return false;
   2764       BaseTy = E->getBase()->getType();
   2765     } else {
   2766       if (!this->Visit(E->getBase()))
   2767         return false;
   2768       BaseTy = E->getBase()->getType();
   2769     }
   2770 
   2771     const ValueDecl *MD = E->getMemberDecl();
   2772     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
   2773       assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
   2774              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
   2775       (void)BaseTy;
   2776       HandleLValueMember(this->Info, E, Result, FD);
   2777     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
   2778       HandleLValueIndirectMember(this->Info, E, Result, IFD);
   2779     } else
   2780       return this->Error(E);
   2781 
   2782     if (MD->getType()->isReferenceType()) {
   2783       APValue RefValue;
   2784       if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
   2785                                           RefValue))
   2786         return false;
   2787       return Success(RefValue, E);
   2788     }
   2789     return true;
   2790   }
   2791 
   2792   bool VisitBinaryOperator(const BinaryOperator *E) {
   2793     switch (E->getOpcode()) {
   2794     default:
   2795       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
   2796 
   2797     case BO_PtrMemD:
   2798     case BO_PtrMemI:
   2799       return HandleMemberPointerAccess(this->Info, E, Result);
   2800     }
   2801   }
   2802 
   2803   bool VisitCastExpr(const CastExpr *E) {
   2804     switch (E->getCastKind()) {
   2805     default:
   2806       return ExprEvaluatorBaseTy::VisitCastExpr(E);
   2807 
   2808     case CK_DerivedToBase:
   2809     case CK_UncheckedDerivedToBase: {
   2810       if (!this->Visit(E->getSubExpr()))
   2811         return false;
   2812 
   2813       // Now figure out the necessary offset to add to the base LV to get from
   2814       // the derived class to the base class.
   2815       QualType Type = E->getSubExpr()->getType();
   2816 
   2817       for (CastExpr::path_const_iterator PathI = E->path_begin(),
   2818            PathE = E->path_end(); PathI != PathE; ++PathI) {
   2819         if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
   2820                               *PathI))
   2821           return false;
   2822         Type = (*PathI)->getType();
   2823       }
   2824 
   2825       return true;
   2826     }
   2827     }
   2828   }
   2829 };
   2830 }
   2831 
   2832 //===----------------------------------------------------------------------===//
   2833 // LValue Evaluation
   2834 //
   2835 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
   2836 // function designators (in C), decl references to void objects (in C), and
   2837 // temporaries (if building with -Wno-address-of-temporary).
   2838 //
   2839 // LValue evaluation produces values comprising a base expression of one of the
   2840 // following types:
   2841 // - Declarations
   2842 //  * VarDecl
   2843 //  * FunctionDecl
   2844 // - Literals
   2845 //  * CompoundLiteralExpr in C
   2846 //  * StringLiteral
   2847 //  * CXXTypeidExpr
   2848 //  * PredefinedExpr
   2849 //  * ObjCStringLiteralExpr
   2850 //  * ObjCEncodeExpr
   2851 //  * AddrLabelExpr
   2852 //  * BlockExpr
   2853 //  * CallExpr for a MakeStringConstant builtin
   2854 // - Locals and temporaries
   2855 //  * Any Expr, with a CallIndex indicating the function in which the temporary
   2856 //    was evaluated.
   2857 // plus an offset in bytes.
   2858 //===----------------------------------------------------------------------===//
   2859 namespace {
   2860 class LValueExprEvaluator
   2861   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
   2862 public:
   2863   LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
   2864     LValueExprEvaluatorBaseTy(Info, Result) {}
   2865 
   2866   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
   2867 
   2868   bool VisitDeclRefExpr(const DeclRefExpr *E);
   2869   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
   2870   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
   2871   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
   2872   bool VisitMemberExpr(const MemberExpr *E);
   2873   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
   2874   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
   2875   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
   2876   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
   2877   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
   2878   bool VisitUnaryDeref(const UnaryOperator *E);
   2879   bool VisitUnaryReal(const UnaryOperator *E);
   2880   bool VisitUnaryImag(const UnaryOperator *E);
   2881 
   2882   bool VisitCastExpr(const CastExpr *E) {
   2883     switch (E->getCastKind()) {
   2884     default:
   2885       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
   2886 
   2887     case CK_LValueBitCast:
   2888       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
   2889       if (!Visit(E->getSubExpr()))
   2890         return false;
   2891       Result.Designator.setInvalid();
   2892       return true;
   2893 
   2894     case CK_BaseToDerived:
   2895       if (!Visit(E->getSubExpr()))
   2896         return false;
   2897       return HandleBaseToDerivedCast(Info, E, Result);
   2898     }
   2899   }
   2900 };
   2901 } // end anonymous namespace
   2902 
   2903 /// Evaluate an expression as an lvalue. This can be legitimately called on
   2904 /// expressions which are not glvalues, in a few cases:
   2905 ///  * function designators in C,
   2906 ///  * "extern void" objects,
   2907 ///  * temporaries, if building with -Wno-address-of-temporary.
   2908 static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
   2909   assert((E->isGLValue() || E->getType()->isFunctionType() ||
   2910           E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
   2911          "can't evaluate expression as an lvalue");
   2912   return LValueExprEvaluator(Info, Result).Visit(E);
   2913 }
   2914 
   2915 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
   2916   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
   2917     return Success(FD);
   2918   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
   2919     return VisitVarDecl(E, VD);
   2920   return Error(E);
   2921 }
   2922 
   2923 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
   2924   if (!VD->getType()->isReferenceType()) {
   2925     if (isa<ParmVarDecl>(VD)) {
   2926       Result.set(VD, Info.CurrentCall->Index);
   2927       return true;
   2928     }
   2929     return Success(VD);
   2930   }
   2931 
   2932   APValue V;
   2933   if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
   2934     return false;
   2935   return Success(V, E);
   2936 }
   2937 
   2938 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
   2939     const MaterializeTemporaryExpr *E) {
   2940   if (E->GetTemporaryExpr()->isRValue()) {
   2941     if (E->getType()->isRecordType())
   2942       return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
   2943 
   2944     Result.set(E, Info.CurrentCall->Index);
   2945     return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
   2946                            Result, E->GetTemporaryExpr());
   2947   }
   2948 
   2949   // Materialization of an lvalue temporary occurs when we need to force a copy
   2950   // (for instance, if it's a bitfield).
   2951   // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
   2952   if (!Visit(E->GetTemporaryExpr()))
   2953     return false;
   2954   if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
   2955                                       Info.CurrentCall->Temporaries[E]))
   2956     return false;
   2957   Result.set(E, Info.CurrentCall->Index);
   2958   return true;
   2959 }
   2960 
   2961 bool
   2962 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
   2963   assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
   2964   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
   2965   // only see this when folding in C, so there's no standard to follow here.
   2966   return Success(E);
   2967 }
   2968 
   2969 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
   2970   if (E->isTypeOperand())
   2971     return Success(E);
   2972   CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
   2973   if (RD && RD->isPolymorphic()) {
   2974     Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
   2975       << E->getExprOperand()->getType()
   2976       << E->getExprOperand()->getSourceRange();
   2977     return false;
   2978   }
   2979   return Success(E);
   2980 }
   2981 
   2982 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
   2983   return Success(E);
   2984 }
   2985 
   2986 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
   2987   // Handle static data members.
   2988   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
   2989     VisitIgnoredValue(E->getBase());
   2990     return VisitVarDecl(E, VD);
   2991   }
   2992 
   2993   // Handle static member functions.
   2994   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
   2995     if (MD->isStatic()) {
   2996       VisitIgnoredValue(E->getBase());
   2997       return Success(MD);
   2998     }
   2999   }
   3000 
   3001   // Handle non-static data members.
   3002   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
   3003 }
   3004 
   3005 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
   3006   // FIXME: Deal with vectors as array subscript bases.
   3007   if (E->getBase()->getType()->isVectorType())
   3008     return Error(E);
   3009 
   3010   if (!EvaluatePointer(E->getBase(), Result, Info))
   3011     return false;
   3012 
   3013   APSInt Index;
   3014   if (!EvaluateInteger(E->getIdx(), Index, Info))
   3015     return false;
   3016   int64_t IndexValue
   3017     = Index.isSigned() ? Index.getSExtValue()
   3018                        : static_cast<int64_t>(Index.getZExtValue());
   3019 
   3020   return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
   3021 }
   3022 
   3023 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
   3024   return EvaluatePointer(E->getSubExpr(), Result, Info);
   3025 }
   3026 
   3027 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
   3028   if (!Visit(E->getSubExpr()))
   3029     return false;
   3030   // __real is a no-op on scalar lvalues.
   3031   if (E->getSubExpr()->getType()->isAnyComplexType())
   3032     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
   3033   return true;
   3034 }
   3035 
   3036 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
   3037   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
   3038          "lvalue __imag__ on scalar?");
   3039   if (!Visit(E->getSubExpr()))
   3040     return false;
   3041   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
   3042   return true;
   3043 }
   3044 
   3045 //===----------------------------------------------------------------------===//
   3046 // Pointer Evaluation
   3047 //===----------------------------------------------------------------------===//
   3048 
   3049 namespace {
   3050 class PointerExprEvaluator
   3051   : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
   3052   LValue &Result;
   3053 
   3054   bool Success(const Expr *E) {
   3055     Result.set(E);
   3056     return true;
   3057   }
   3058 public:
   3059 
   3060   PointerExprEvaluator(EvalInfo &info, LValue &Result)
   3061     : ExprEvaluatorBaseTy(info), Result(Result) {}
   3062 
   3063   bool Success(const APValue &V, const Expr *E) {
   3064     Result.setFrom(Info.Ctx, V);
   3065     return true;
   3066   }
   3067   bool ZeroInitialization(const Expr *E) {
   3068     return Success((Expr*)0);
   3069   }
   3070 
   3071   bool VisitBinaryOperator(const BinaryOperator *E);
   3072   bool VisitCastExpr(const CastExpr* E);
   3073   bool VisitUnaryAddrOf(const UnaryOperator *E);
   3074   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
   3075       { return Success(E); }
   3076   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
   3077       { return Success(E); }
   3078   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
   3079       { return Success(E); }
   3080   bool VisitCallExpr(const CallExpr *E);
   3081   bool VisitBlockExpr(const BlockExpr *E) {
   3082     if (!E->getBlockDecl()->hasCaptures())
   3083       return Success(E);
   3084     return Error(E);
   3085   }
   3086   bool VisitCXXThisExpr(const CXXThisExpr *E) {
   3087     if (!Info.CurrentCall->This)
   3088       return Error(E);
   3089     Result = *Info.CurrentCall->This;
   3090     return true;
   3091   }
   3092 
   3093   // FIXME: Missing: @protocol, @selector
   3094 };
   3095 } // end anonymous namespace
   3096 
   3097 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
   3098   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
   3099   return PointerExprEvaluator(Info, Result).Visit(E);
   3100 }
   3101 
   3102 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
   3103   if (E->getOpcode() != BO_Add &&
   3104       E->getOpcode() != BO_Sub)
   3105     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
   3106 
   3107   const Expr *PExp = E->getLHS();
   3108   const Expr *IExp = E->getRHS();
   3109   if (IExp->getType()->isPointerType())
   3110     std::swap(PExp, IExp);
   3111 
   3112   bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
   3113   if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
   3114     return false;
   3115 
   3116   llvm::APSInt Offset;
   3117   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
   3118     return false;
   3119   int64_t AdditionalOffset
   3120     = Offset.isSigned() ? Offset.getSExtValue()
   3121                         : static_cast<int64_t>(Offset.getZExtValue());
   3122   if (E->getOpcode() == BO_Sub)
   3123     AdditionalOffset = -AdditionalOffset;
   3124 
   3125   QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
   3126   return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
   3127                                      AdditionalOffset);
   3128 }
   3129 
   3130 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
   3131   return EvaluateLValue(E->getSubExpr(), Result, Info);
   3132 }
   3133 
   3134 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
   3135   const Expr* SubExpr = E->getSubExpr();
   3136 
   3137   switch (E->getCastKind()) {
   3138   default:
   3139     break;
   3140 
   3141   case CK_BitCast:
   3142   case CK_CPointerToObjCPointerCast:
   3143   case CK_BlockPointerToObjCPointerCast:
   3144   case CK_AnyPointerToBlockPointerCast:
   3145     if (!Visit(SubExpr))
   3146       return false;
   3147     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
   3148     // permitted in constant expressions in C++11. Bitcasts from cv void* are
   3149     // also static_casts, but we disallow them as a resolution to DR1312.
   3150     if (!E->getType()->isVoidPointerType()) {
   3151       Result.Designator.setInvalid();
   3152       if (SubExpr->getType()->isVoidPointerType())
   3153         CCEDiag(E, diag::note_constexpr_invalid_cast)
   3154           << 3 << SubExpr->getType();
   3155       else
   3156         CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
   3157     }
   3158     return true;
   3159 
   3160   case CK_DerivedToBase:
   3161   case CK_UncheckedDerivedToBase: {
   3162     if (!EvaluatePointer(E->getSubExpr(), Result, Info))
   3163       return false;
   3164     if (!Result.Base && Result.Offset.isZero())
   3165       return true;
   3166 
   3167     // Now figure out the necessary offset to add to the base LV to get from
   3168     // the derived class to the base class.
   3169     QualType Type =
   3170         E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
   3171 
   3172     for (CastExpr::path_const_iterator PathI = E->path_begin(),
   3173          PathE = E->path_end(); PathI != PathE; ++PathI) {
   3174       if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
   3175                             *PathI))
   3176         return false;
   3177       Type = (*PathI)->getType();
   3178     }
   3179 
   3180     return true;
   3181   }
   3182 
   3183   case CK_BaseToDerived:
   3184     if (!Visit(E->getSubExpr()))
   3185       return false;
   3186     if (!Result.Base && Result.Offset.isZero())
   3187       return true;
   3188     return HandleBaseToDerivedCast(Info, E, Result);
   3189 
   3190   case CK_NullToPointer:
   3191     VisitIgnoredValue(E->getSubExpr());
   3192     return ZeroInitialization(E);
   3193 
   3194   case CK_IntegralToPointer: {
   3195     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
   3196 
   3197     APValue Value;
   3198     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
   3199       break;
   3200 
   3201     if (Value.isInt()) {
   3202       unsigned Size = Info.Ctx.getTypeSize(E->getType());
   3203       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
   3204       Result.Base = (Expr*)0;
   3205       Result.Offset = CharUnits::fromQuantity(N);
   3206       Result.CallIndex = 0;
   3207       Result.Designator.setInvalid();
   3208       return true;
   3209     } else {
   3210       // Cast is of an lvalue, no need to change value.
   3211       Result.setFrom(Info.Ctx, Value);
   3212       return true;
   3213     }
   3214   }
   3215   case CK_ArrayToPointerDecay:
   3216     if (SubExpr->isGLValue()) {
   3217       if (!EvaluateLValue(SubExpr, Result, Info))
   3218         return false;
   3219     } else {
   3220       Result.set(SubExpr, Info.CurrentCall->Index);
   3221       if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
   3222                            Info, Result, SubExpr))
   3223         return false;
   3224     }
   3225     // The result is a pointer to the first element of the array.
   3226     if (const ConstantArrayType *CAT
   3227           = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
   3228       Result.addArray(Info, E, CAT);
   3229     else
   3230       Result.Designator.setInvalid();
   3231     return true;
   3232 
   3233   case CK_FunctionToPointerDecay:
   3234     return EvaluateLValue(SubExpr, Result, Info);
   3235   }
   3236 
   3237   return ExprEvaluatorBaseTy::VisitCastExpr(E);
   3238 }
   3239 
   3240 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
   3241   if (IsStringLiteralCall(E))
   3242     return Success(E);
   3243 
   3244   return ExprEvaluatorBaseTy::VisitCallExpr(E);
   3245 }
   3246 
   3247 //===----------------------------------------------------------------------===//
   3248 // Member Pointer Evaluation
   3249 //===----------------------------------------------------------------------===//
   3250 
   3251 namespace {
   3252 class MemberPointerExprEvaluator
   3253   : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
   3254   MemberPtr &Result;
   3255 
   3256   bool Success(const ValueDecl *D) {
   3257     Result = MemberPtr(D);
   3258     return true;
   3259   }
   3260 public:
   3261 
   3262   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
   3263     : ExprEvaluatorBaseTy(Info), Result(Result) {}
   3264 
   3265   bool Success(const APValue &V, const Expr *E) {
   3266     Result.setFrom(V);
   3267     return true;
   3268   }
   3269   bool ZeroInitialization(const Expr *E) {
   3270     return Success((const ValueDecl*)0);
   3271   }
   3272 
   3273   bool VisitCastExpr(const CastExpr *E);
   3274   bool VisitUnaryAddrOf(const UnaryOperator *E);
   3275 };
   3276 } // end anonymous namespace
   3277 
   3278 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
   3279                                   EvalInfo &Info) {
   3280   assert(E->isRValue() && E->getType()->isMemberPointerType());
   3281   return MemberPointerExprEvaluator(Info, Result).Visit(E);
   3282 }
   3283 
   3284 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
   3285   switch (E->getCastKind()) {
   3286   default:
   3287     return ExprEvaluatorBaseTy::VisitCastExpr(E);
   3288 
   3289   case CK_NullToMemberPointer:
   3290     VisitIgnoredValue(E->getSubExpr());
   3291     return ZeroInitialization(E);
   3292 
   3293   case CK_BaseToDerivedMemberPointer: {
   3294     if (!Visit(E->getSubExpr()))
   3295       return false;
   3296     if (E->path_empty())
   3297       return true;
   3298     // Base-to-derived member pointer casts store the path in derived-to-base
   3299     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
   3300     // the wrong end of the derived->base arc, so stagger the path by one class.
   3301     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
   3302     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
   3303          PathI != PathE; ++PathI) {
   3304       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
   3305       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
   3306       if (!Result.castToDerived(Derived))
   3307         return Error(E);
   3308     }
   3309     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
   3310     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
   3311       return Error(E);
   3312     return true;
   3313   }
   3314 
   3315   case CK_DerivedToBaseMemberPointer:
   3316     if (!Visit(E->getSubExpr()))
   3317       return false;
   3318     for (CastExpr::path_const_iterator PathI = E->path_begin(),
   3319          PathE = E->path_end(); PathI != PathE; ++PathI) {
   3320       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
   3321       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
   3322       if (!Result.castToBase(Base))
   3323         return Error(E);
   3324     }
   3325     return true;
   3326   }
   3327 }
   3328 
   3329 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
   3330   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
   3331   // member can be formed.
   3332   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
   3333 }
   3334 
   3335 //===----------------------------------------------------------------------===//
   3336 // Record Evaluation
   3337 //===----------------------------------------------------------------------===//
   3338 
   3339 namespace {
   3340   class RecordExprEvaluator
   3341   : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
   3342     const LValue &This;
   3343     APValue &Result;
   3344   public:
   3345 
   3346     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
   3347       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
   3348 
   3349     bool Success(const APValue &V, const Expr *E) {
   3350       Result = V;
   3351       return true;
   3352     }
   3353     bool ZeroInitialization(const Expr *E);
   3354 
   3355     bool VisitCastExpr(const CastExpr *E);
   3356     bool VisitInitListExpr(const InitListExpr *E);
   3357     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
   3358   };
   3359 }
   3360 
   3361 /// Perform zero-initialization on an object of non-union class type.
   3362 /// C++11 [dcl.init]p5:
   3363 ///  To zero-initialize an object or reference of type T means:
   3364 ///    [...]
   3365 ///    -- if T is a (possibly cv-qualified) non-union class type,
   3366 ///       each non-static data member and each base-class subobject is
   3367 ///       zero-initialized
   3368 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
   3369                                           const RecordDecl *RD,
   3370                                           const LValue &This, APValue &Result) {
   3371   assert(!RD->isUnion() && "Expected non-union class type");
   3372   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
   3373   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
   3374                    std::distance(RD->field_begin(), RD->field_end()));
   3375 
   3376   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
   3377 
   3378   if (CD) {
   3379     unsigned Index = 0;
   3380     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
   3381            End = CD->bases_end(); I != End; ++I, ++Index) {
   3382       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
   3383       LValue Subobject = This;
   3384       HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
   3385       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
   3386                                          Result.getStructBase(Index)))
   3387         return false;
   3388     }
   3389   }
   3390 
   3391   for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
   3392        I != End; ++I) {
   3393     // -- if T is a reference type, no initialization is performed.
   3394     if ((*I)->getType()->isReferenceType())
   3395       continue;
   3396 
   3397     LValue Subobject = This;
   3398     HandleLValueMember(Info, E, Subobject, *I, &Layout);
   3399 
   3400     ImplicitValueInitExpr VIE((*I)->getType());
   3401     if (!EvaluateInPlace(
   3402           Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
   3403       return false;
   3404   }
   3405 
   3406   return true;
   3407 }
   3408 
   3409 bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
   3410   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
   3411   if (RD->isUnion()) {
   3412     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
   3413     // object's first non-static named data member is zero-initialized
   3414     RecordDecl::field_iterator I = RD->field_begin();
   3415     if (I == RD->field_end()) {
   3416       Result = APValue((const FieldDecl*)0);
   3417       return true;
   3418     }
   3419 
   3420     LValue Subobject = This;
   3421     HandleLValueMember(Info, E, Subobject, *I);
   3422     Result = APValue(*I);
   3423     ImplicitValueInitExpr VIE((*I)->getType());
   3424     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
   3425   }
   3426 
   3427   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
   3428     Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
   3429     return false;
   3430   }
   3431 
   3432   return HandleClassZeroInitialization(Info, E, RD, This, Result);
   3433 }
   3434 
   3435 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
   3436   switch (E->getCastKind()) {
   3437   default:
   3438     return ExprEvaluatorBaseTy::VisitCastExpr(E);
   3439 
   3440   case CK_ConstructorConversion:
   3441     return Visit(E->getSubExpr());
   3442 
   3443   case CK_DerivedToBase:
   3444   case CK_UncheckedDerivedToBase: {
   3445     APValue DerivedObject;
   3446     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
   3447       return false;
   3448     if (!DerivedObject.isStruct())
   3449       return Error(E->getSubExpr());
   3450 
   3451     // Derived-to-base rvalue conversion: just slice off the derived part.
   3452     APValue *Value = &DerivedObject;
   3453     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
   3454     for (CastExpr::path_const_iterator PathI = E->path_begin(),
   3455          PathE = E->path_end(); PathI != PathE; ++PathI) {
   3456       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
   3457       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
   3458       Value = &Value->getStructBase(getBaseIndex(RD, Base));
   3459       RD = Base;
   3460     }
   3461     Result = *Value;
   3462     return true;
   3463   }
   3464   }
   3465 }
   3466 
   3467 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
   3468   // Cannot constant-evaluate std::initializer_list inits.
   3469   if (E->initializesStdInitializerList())
   3470     return false;
   3471 
   3472   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
   3473   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
   3474 
   3475   if (RD->isUnion()) {
   3476     const FieldDecl *Field = E->getInitializedFieldInUnion();
   3477     Result = APValue(Field);
   3478     if (!Field)
   3479       return true;
   3480 
   3481     // If the initializer list for a union does not contain any elements, the
   3482     // first element of the union is value-initialized.
   3483     ImplicitValueInitExpr VIE(Field->getType());
   3484     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
   3485 
   3486     LValue Subobject = This;
   3487     HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
   3488     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
   3489   }
   3490 
   3491   assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
   3492          "initializer list for class with base classes");
   3493   Result = APValue(APValue::UninitStruct(), 0,
   3494                    std::distance(RD->field_begin(), RD->field_end()));
   3495   unsigned ElementNo = 0;
   3496   bool Success = true;
   3497   for (RecordDecl::field_iterator Field = RD->field_begin(),
   3498        FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
   3499     // Anonymous bit-fields are not considered members of the class for
   3500     // purposes of aggregate initialization.
   3501     if (Field->isUnnamedBitfield())
   3502       continue;
   3503 
   3504     LValue Subobject = This;
   3505 
   3506     bool HaveInit = ElementNo < E->getNumInits();
   3507 
   3508     // FIXME: Diagnostics here should point to the end of the initializer
   3509     // list, not the start.
   3510     HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
   3511                        *Field, &Layout);
   3512 
   3513     // Perform an implicit value-initialization for members beyond the end of
   3514     // the initializer list.
   3515     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
   3516 
   3517     if (!EvaluateInPlace(
   3518           Result.getStructField((*Field)->getFieldIndex()),
   3519           Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
   3520       if (!Info.keepEvaluatingAfterFailure())
   3521         return false;
   3522       Success = false;
   3523     }
   3524   }
   3525 
   3526   return Success;
   3527 }
   3528 
   3529 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
   3530   const CXXConstructorDecl *FD = E->getConstructor();
   3531   bool ZeroInit = E->requiresZeroInitialization();
   3532   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
   3533     // If we've already performed zero-initialization, we're already done.
   3534     if (!Result.isUninit())
   3535       return true;
   3536 
   3537     if (ZeroInit)
   3538       return ZeroInitialization(E);
   3539 
   3540     const CXXRecordDecl *RD = FD->getParent();
   3541     if (RD->isUnion())
   3542       Result = APValue((FieldDecl*)0);
   3543     else
   3544       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
   3545                        std::distance(RD->field_begin(), RD->field_end()));
   3546     return true;
   3547   }
   3548 
   3549   const FunctionDecl *Definition = 0;
   3550   FD->getBody(Definition);
   3551 
   3552   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
   3553     return false;
   3554 
   3555   // Avoid materializing a temporary for an elidable copy/move constructor.
   3556   if (E->isElidable() && !ZeroInit)
   3557     if (const MaterializeTemporaryExpr *ME
   3558           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
   3559       return Visit(ME->GetTemporaryExpr());
   3560 
   3561   if (ZeroInit && !ZeroInitialization(E))
   3562     return false;
   3563 
   3564   llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
   3565   return HandleConstructorCall(E->getExprLoc(), This, Args,
   3566                                cast<CXXConstructorDecl>(Definition), Info,
   3567                                Result);
   3568 }
   3569 
   3570 static bool EvaluateRecord(const Expr *E, const LValue &This,
   3571                            APValue &Result, EvalInfo &Info) {
   3572   assert(E->isRValue() && E->getType()->isRecordType() &&
   3573          "can't evaluate expression as a record rvalue");
   3574   return RecordExprEvaluator(Info, This, Result).Visit(E);
   3575 }
   3576 
   3577 //===----------------------------------------------------------------------===//
   3578 // Temporary Evaluation
   3579 //
   3580 // Temporaries are represented in the AST as rvalues, but generally behave like
   3581 // lvalues. The full-object of which the temporary is a subobject is implicitly
   3582 // materialized so that a reference can bind to it.
   3583 //===----------------------------------------------------------------------===//
   3584 namespace {
   3585 class TemporaryExprEvaluator
   3586   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
   3587 public:
   3588   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
   3589     LValueExprEvaluatorBaseTy(Info, Result) {}
   3590 
   3591   /// Visit an expression which constructs the value of this temporary.
   3592   bool VisitConstructExpr(const Expr *E) {
   3593     Result.set(E, Info.CurrentCall->Index);
   3594     return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
   3595   }
   3596 
   3597   bool VisitCastExpr(const CastExpr *E) {
   3598     switch (E->getCastKind()) {
   3599     default:
   3600       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
   3601 
   3602     case CK_ConstructorConversion:
   3603       return VisitConstructExpr(E->getSubExpr());
   3604     }
   3605   }
   3606   bool VisitInitListExpr(const InitListExpr *E) {
   3607     return VisitConstructExpr(E);
   3608   }
   3609   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
   3610     return VisitConstructExpr(E);
   3611   }
   3612   bool VisitCallExpr(const CallExpr *E) {
   3613     return VisitConstructExpr(E);
   3614   }
   3615 };
   3616 } // end anonymous namespace
   3617 
   3618 /// Evaluate an expression of record type as a temporary.
   3619 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
   3620   assert(E->isRValue() && E->getType()->isRecordType());
   3621   return TemporaryExprEvaluator(Info, Result).Visit(E);
   3622 }
   3623 
   3624 //===----------------------------------------------------------------------===//
   3625 // Vector Evaluation
   3626 //===----------------------------------------------------------------------===//
   3627 
   3628 namespace {
   3629   class VectorExprEvaluator
   3630   : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
   3631     APValue &Result;
   3632   public:
   3633 
   3634     VectorExprEvaluator(EvalInfo &info, APValue &Result)
   3635       : ExprEvaluatorBaseTy(info), Result(Result) {}
   3636 
   3637     bool Success(const ArrayRef<APValue> &V, const Expr *E) {
   3638       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
   3639       // FIXME: remove this APValue copy.
   3640       Result = APValue(V.data(), V.size());
   3641       return true;
   3642     }
   3643     bool Success(const APValue &V, const Expr *E) {
   3644       assert(V.isVector());
   3645       Result = V;
   3646       return true;
   3647     }
   3648     bool ZeroInitialization(const Expr *E);
   3649 
   3650     bool VisitUnaryReal(const UnaryOperator *E)
   3651       { return Visit(E->getSubExpr()); }
   3652     bool VisitCastExpr(const CastExpr* E);
   3653     bool VisitInitListExpr(const InitListExpr *E);
   3654     bool VisitUnaryImag(const UnaryOperator *E);
   3655     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
   3656     //                 binary comparisons, binary and/or/xor,
   3657     //                 shufflevector, ExtVectorElementExpr
   3658   };
   3659 } // end anonymous namespace
   3660 
   3661 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
   3662   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
   3663   return VectorExprEvaluator(Info, Result).Visit(E);
   3664 }
   3665 
   3666 bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
   3667   const VectorType *VTy = E->getType()->castAs<VectorType>();
   3668   unsigned NElts = VTy->getNumElements();
   3669 
   3670   const Expr *SE = E->getSubExpr();
   3671   QualType SETy = SE->getType();
   3672 
   3673   switch (E->getCastKind()) {
   3674   case CK_VectorSplat: {
   3675     APValue Val = APValue();
   3676     if (SETy->isIntegerType()) {
   3677       APSInt IntResult;
   3678       if (!EvaluateInteger(SE, IntResult, Info))
   3679          return false;
   3680       Val = APValue(IntResult);
   3681     } else if (SETy->isRealFloatingType()) {
   3682        APFloat F(0.0);
   3683        if (!EvaluateFloat(SE, F, Info))
   3684          return false;
   3685        Val = APValue(F);
   3686     } else {
   3687       return Error(E);
   3688     }
   3689 
   3690     // Splat and create vector APValue.
   3691     SmallVector<APValue, 4> Elts(NElts, Val);
   3692     return Success(Elts, E);
   3693   }
   3694   case CK_BitCast: {
   3695     // Evaluate the operand into an APInt we can extract from.
   3696     llvm::APInt SValInt;
   3697     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
   3698       return false;
   3699     // Extract the elements
   3700     QualType EltTy = VTy->getElementType();
   3701     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
   3702     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
   3703     SmallVector<APValue, 4> Elts;
   3704     if (EltTy->isRealFloatingType()) {
   3705       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
   3706       bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
   3707       unsigned FloatEltSize = EltSize;
   3708       if (&Sem == &APFloat::x87DoubleExtended)
   3709         FloatEltSize = 80;
   3710       for (unsigned i = 0; i < NElts; i++) {
   3711         llvm::APInt Elt;
   3712         if (BigEndian)
   3713           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
   3714         else
   3715           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
   3716         Elts.push_back(APValue(APFloat(Elt, isIEESem)));
   3717       }
   3718     } else if (EltTy->isIntegerType()) {
   3719       for (unsigned i = 0; i < NElts; i++) {
   3720         llvm::APInt Elt;
   3721         if (BigEndian)
   3722           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
   3723         else
   3724           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
   3725         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
   3726       }
   3727     } else {
   3728       return Error(E);
   3729     }
   3730     return Success(Elts, E);
   3731   }
   3732   default:
   3733     return ExprEvaluatorBaseTy::VisitCastExpr(E);
   3734   }
   3735 }
   3736 
   3737 bool
   3738 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
   3739   const VectorType *VT = E->getType()->castAs<VectorType>();
   3740   unsigned NumInits = E->getNumInits();
   3741   unsigned NumElements = VT->getNumElements();
   3742 
   3743   QualType EltTy = VT->getElementType();
   3744   SmallVector<APValue, 4> Elements;
   3745 
   3746   // The number of initializers can be less than the number of
   3747   // vector elements. For OpenCL, this can be due to nested vector
   3748   // initialization. For GCC compatibility, missing trailing elements
   3749   // should be initialized with zeroes.
   3750   unsigned CountInits = 0, CountElts = 0;
   3751   while (CountElts < NumElements) {
   3752     // Handle nested vector initialization.
   3753     if (CountInits < NumInits
   3754         && E->getInit(CountInits)->getType()->isExtVectorType()) {
   3755       APValue v;
   3756       if (!EvaluateVector(E->getInit(CountInits), v, Info))
   3757         return Error(E);
   3758       unsigned vlen = v.getVectorLength();
   3759       for (unsigned j = 0; j < vlen; j++)
   3760         Elements.push_back(v.getVectorElt(j));
   3761       CountElts += vlen;
   3762     } else if (EltTy->isIntegerType()) {
   3763       llvm::APSInt sInt(32);
   3764       if (CountInits < NumInits) {
   3765         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
   3766           return false;
   3767       } else // trailing integer zero.
   3768         sInt = Info.Ctx.MakeIntValue(0, EltTy);
   3769       Elements.push_back(APValue(sInt));
   3770       CountElts++;
   3771     } else {
   3772       llvm::APFloat f(0.0);
   3773       if (CountInits < NumInits) {
   3774         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
   3775           return false;
   3776       } else // trailing float zero.
   3777         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
   3778       Elements.push_back(APValue(f));
   3779       CountElts++;
   3780     }
   3781     CountInits++;
   3782   }
   3783   return Success(Elements, E);
   3784 }
   3785 
   3786 bool
   3787 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
   3788   const VectorType *VT = E->getType()->getAs<VectorType>();
   3789   QualType EltTy = VT->getElementType();
   3790   APValue ZeroElement;
   3791   if (EltTy->isIntegerType())
   3792     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
   3793   else
   3794     ZeroElement =
   3795         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
   3796 
   3797   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
   3798   return Success(Elements, E);
   3799 }
   3800 
   3801 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
   3802   VisitIgnoredValue(E->getSubExpr());
   3803   return ZeroInitialization(E);
   3804 }
   3805 
   3806 //===----------------------------------------------------------------------===//
   3807 // Array Evaluation
   3808 //===----------------------------------------------------------------------===//
   3809 
   3810 namespace {
   3811   class ArrayExprEvaluator
   3812   : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
   3813     const LValue &This;
   3814     APValue &Result;
   3815   public:
   3816 
   3817     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
   3818       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
   3819 
   3820     bool Success(const APValue &V, const Expr *E) {
   3821       assert((V.isArray() || V.isLValue()) &&
   3822              "expected array or string literal");
   3823       Result = V;
   3824       return true;
   3825     }
   3826 
   3827     bool ZeroInitialization(const Expr *E) {
   3828       const ConstantArrayType *CAT =
   3829           Info.Ctx.getAsConstantArrayType(E->getType());
   3830       if (!CAT)
   3831         return Error(E);
   3832 
   3833       Result = APValue(APValue::UninitArray(), 0,
   3834                        CAT->getSize().getZExtValue());
   3835       if (!Result.hasArrayFiller()) return true;
   3836 
   3837       // Zero-initialize all elements.
   3838       LValue Subobject = This;
   3839       Subobject.addArray(Info, E, CAT);
   3840       ImplicitValueInitExpr VIE(CAT->getElementType());
   3841       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
   3842     }
   3843 
   3844     bool VisitInitListExpr(const InitListExpr *E);
   3845     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
   3846   };
   3847 } // end anonymous namespace
   3848 
   3849 static bool EvaluateArray(const Expr *E, const LValue &This,
   3850                           APValue &Result, EvalInfo &Info) {
   3851   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
   3852   return ArrayExprEvaluator(Info, This, Result).Visit(E);
   3853 }
   3854 
   3855 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
   3856   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
   3857   if (!CAT)
   3858     return Error(E);
   3859 
   3860   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
   3861   // an appropriately-typed string literal enclosed in braces.
   3862   if (E->isStringLiteralInit()) {
   3863     LValue LV;
   3864     if (!EvaluateLValue(E->getInit(0), LV, Info))
   3865       return false;
   3866     APValue Val;
   3867     LV.moveInto(Val);
   3868     return Success(Val, E);
   3869   }
   3870 
   3871   bool Success = true;
   3872 
   3873   Result = APValue(APValue::UninitArray(), E->getNumInits(),
   3874                    CAT->getSize().getZExtValue());
   3875   LValue Subobject = This;
   3876   Subobject.addArray(Info, E, CAT);
   3877   unsigned Index = 0;
   3878   for (InitListExpr::const_iterator I = E->begin(), End = E->end();
   3879        I != End; ++I, ++Index) {
   3880     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
   3881                          Info, Subobject, cast<Expr>(*I)) ||
   3882         !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
   3883                                      CAT->getElementType(), 1)) {
   3884       if (!Info.keepEvaluatingAfterFailure())
   3885         return false;
   3886       Success = false;
   3887     }
   3888   }
   3889 
   3890   if (!Result.hasArrayFiller()) return Success;
   3891   assert(E->hasArrayFiller() && "no array filler for incomplete init list");
   3892   // FIXME: The Subobject here isn't necessarily right. This rarely matters,
   3893   // but sometimes does:
   3894   //   struct S { constexpr S() : p(&p) {} void *p; };
   3895   //   S s[10] = {};
   3896   return EvaluateInPlace(Result.getArrayFiller(), Info,
   3897                          Subobject, E->getArrayFiller()) && Success;
   3898 }
   3899 
   3900 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
   3901   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
   3902   if (!CAT)
   3903     return Error(E);
   3904 
   3905   bool HadZeroInit = !Result.isUninit();
   3906   if (!HadZeroInit)
   3907     Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
   3908   if (!Result.hasArrayFiller())
   3909     return true;
   3910 
   3911   const CXXConstructorDecl *FD = E->getConstructor();
   3912 
   3913   bool ZeroInit = E->requiresZeroInitialization();
   3914   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
   3915     if (HadZeroInit)
   3916       return true;
   3917 
   3918     if (ZeroInit) {
   3919       LValue Subobject = This;
   3920       Subobject.addArray(Info, E, CAT);
   3921       ImplicitValueInitExpr VIE(CAT->getElementType());
   3922       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
   3923     }
   3924 
   3925     const CXXRecordDecl *RD = FD->getParent();
   3926     if (RD->isUnion())
   3927       Result.getArrayFiller() = APValue((FieldDecl*)0);
   3928     else
   3929       Result.getArrayFiller() =
   3930           APValue(APValue::UninitStruct(), RD->getNumBases(),
   3931                   std::distance(RD->field_begin(), RD->field_end()));
   3932     return true;
   3933   }
   3934 
   3935   const FunctionDecl *Definition = 0;
   3936   FD->getBody(Definition);
   3937 
   3938   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
   3939     return false;
   3940 
   3941   // FIXME: The Subobject here isn't necessarily right. This rarely matters,
   3942   // but sometimes does:
   3943   //   struct S { constexpr S() : p(&p) {} void *p; };
   3944   //   S s[10];
   3945   LValue Subobject = This;
   3946   Subobject.addArray(Info, E, CAT);
   3947 
   3948   if (ZeroInit && !HadZeroInit) {
   3949     ImplicitValueInitExpr VIE(CAT->getElementType());
   3950     if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
   3951       return false;
   3952   }
   3953 
   3954   llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
   3955   return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
   3956                                cast<CXXConstructorDecl>(Definition),
   3957                                Info, Result.getArrayFiller());
   3958 }
   3959 
   3960 //===----------------------------------------------------------------------===//
   3961 // Integer Evaluation
   3962 //
   3963 // As a GNU extension, we support casting pointers to sufficiently-wide integer
   3964 // types and back in constant folding. Integer values are thus represented
   3965 // either as an integer-valued APValue, or as an lvalue-valued APValue.
   3966 //===----------------------------------------------------------------------===//
   3967 
   3968 namespace {
   3969 class IntExprEvaluator
   3970   : public ExprEvaluatorBase<IntExprEvaluator, bool> {
   3971   APValue &Result;
   3972 public:
   3973   IntExprEvaluator(EvalInfo &info, APValue &result)
   3974     : ExprEvaluatorBaseTy(info), Result(result) {}
   3975 
   3976   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
   3977     assert(E->getType()->isIntegralOrEnumerationType() &&
   3978            "Invalid evaluation result.");
   3979     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
   3980            "Invalid evaluation result.");
   3981     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
   3982            "Invalid evaluation result.");
   3983     Result = APValue(SI);
   3984     return true;
   3985   }
   3986   bool Success(const llvm::APSInt &SI, const Expr *E) {
   3987     return Success(SI, E, Result);
   3988   }
   3989 
   3990   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
   3991     assert(E->getType()->isIntegralOrEnumerationType() &&
   3992            "Invalid evaluation result.");
   3993     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
   3994            "Invalid evaluation result.");
   3995     Result = APValue(APSInt(I));
   3996     Result.getInt().setIsUnsigned(
   3997                             E->getType()->isUnsignedIntegerOrEnumerationType());
   3998     return true;
   3999   }
   4000   bool Success(const llvm::APInt &I, const Expr *E) {
   4001     return Success(I, E, Result);
   4002   }
   4003 
   4004   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
   4005     assert(E->getType()->isIntegralOrEnumerationType() &&
   4006            "Invalid evaluation result.");
   4007     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
   4008     return true;
   4009   }
   4010   bool Success(uint64_t Value, const Expr *E) {
   4011     return Success(Value, E, Result);
   4012   }
   4013 
   4014   bool Success(CharUnits Size, const Expr *E) {
   4015     return Success(Size.getQuantity(), E);
   4016   }
   4017 
   4018   bool Success(const APValue &V, const Expr *E) {
   4019     if (V.isLValue() || V.isAddrLabelDiff()) {
   4020       Result = V;
   4021       return true;
   4022     }
   4023     return Success(V.getInt(), E);
   4024   }
   4025 
   4026   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
   4027 
   4028   //===--------------------------------------------------------------------===//
   4029   //                            Visitor Methods
   4030   //===--------------------------------------------------------------------===//
   4031 
   4032   bool VisitIntegerLiteral(const IntegerLiteral *E) {
   4033     return Success(E->getValue(), E);
   4034   }
   4035   bool VisitCharacterLiteral(const CharacterLiteral *E) {
   4036     return Success(E->getValue(), E);
   4037   }
   4038 
   4039   bool CheckReferencedDecl(const Expr *E, const Decl *D);
   4040   bool VisitDeclRefExpr(const DeclRefExpr *E) {
   4041     if (CheckReferencedDecl(E, E->getDecl()))
   4042       return true;
   4043 
   4044     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
   4045   }
   4046   bool VisitMemberExpr(const MemberExpr *E) {
   4047     if (CheckReferencedDecl(E, E->getMemberDecl())) {
   4048       VisitIgnoredValue(E->getBase());
   4049       return true;
   4050     }
   4051 
   4052     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
   4053   }
   4054 
   4055   bool VisitCallExpr(const CallExpr *E);
   4056   bool VisitBinaryOperator(const BinaryOperator *E);
   4057   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
   4058   bool VisitUnaryOperator(const UnaryOperator *E);
   4059 
   4060   bool VisitCastExpr(const CastExpr* E);
   4061   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
   4062 
   4063   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
   4064     return Success(E->getValue(), E);
   4065   }
   4066 
   4067   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
   4068     return Success(E->getValue(), E);
   4069   }
   4070 
   4071   // Note, GNU defines __null as an integer, not a pointer.
   4072   bool VisitGNUNullExpr(const GNUNullExpr *E) {
   4073     return ZeroInitialization(E);
   4074   }
   4075 
   4076   bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
   4077     return Success(E->getValue(), E);
   4078   }
   4079 
   4080   bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
   4081     return Success(E->getValue(), E);
   4082   }
   4083 
   4084   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
   4085     return Success(E->getValue(), E);
   4086   }
   4087 
   4088   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
   4089     return Success(E->getValue(), E);
   4090   }
   4091 
   4092   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
   4093     return Success(E->getValue(), E);
   4094   }
   4095 
   4096   bool VisitUnaryReal(const UnaryOperator *E);
   4097   bool VisitUnaryImag(const UnaryOperator *E);
   4098 
   4099   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
   4100   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
   4101 
   4102 private:
   4103   CharUnits GetAlignOfExpr(const Expr *E);
   4104   CharUnits GetAlignOfType(QualType T);
   4105   static QualType GetObjectType(APValue::LValueBase B);
   4106   bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
   4107   // FIXME: Missing: array subscript of vector, member of vector
   4108 };
   4109 } // end anonymous namespace
   4110 
   4111 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
   4112 /// produce either the integer value or a pointer.
   4113 ///
   4114 /// GCC has a heinous extension which folds casts between pointer types and
   4115 /// pointer-sized integral types. We support this by allowing the evaluation of
   4116 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
   4117 /// Some simple arithmetic on such values is supported (they are treated much
   4118 /// like char*).
   4119 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
   4120                                     EvalInfo &Info) {
   4121   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
   4122   return IntExprEvaluator(Info, Result).Visit(E);
   4123 }
   4124 
   4125 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
   4126   APValue Val;
   4127   if (!EvaluateIntegerOrLValue(E, Val, Info))
   4128     return false;
   4129   if (!Val.isInt()) {
   4130     // FIXME: It would be better to produce the diagnostic for casting
   4131     //        a pointer to an integer.
   4132     Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
   4133     return false;
   4134   }
   4135   Result = Val.getInt();
   4136   return true;
   4137 }
   4138 
   4139 /// Check whether the given declaration can be directly converted to an integral
   4140 /// rvalue. If not, no diagnostic is produced; there are other things we can
   4141 /// try.
   4142 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
   4143   // Enums are integer constant exprs.
   4144   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
   4145     // Check for signedness/width mismatches between E type and ECD value.
   4146     bool SameSign = (ECD->getInitVal().isSigned()
   4147                      == E->getType()->isSignedIntegerOrEnumerationType());
   4148     bool SameWidth = (ECD->getInitVal().getBitWidth()
   4149                       == Info.Ctx.getIntWidth(E->getType()));
   4150     if (SameSign && SameWidth)
   4151       return Success(ECD->getInitVal(), E);
   4152     else {
   4153       // Get rid of mismatch (otherwise Success assertions will fail)
   4154       // by computing a new value matching the type of E.
   4155       llvm::APSInt Val = ECD->getInitVal();
   4156       if (!SameSign)
   4157         Val.setIsSigned(!ECD->getInitVal().isSigned());
   4158       if (!SameWidth)
   4159         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
   4160       return Success(Val, E);
   4161     }
   4162   }
   4163   return false;
   4164 }
   4165 
   4166 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
   4167 /// as GCC.
   4168 static int EvaluateBuiltinClassifyType(const CallExpr *E) {
   4169   // The following enum mimics the values returned by GCC.
   4170   // FIXME: Does GCC differ between lvalue and rvalue references here?
   4171   enum gcc_type_class {
   4172     no_type_class = -1,
   4173     void_type_class, integer_type_class, char_type_class,
   4174     enumeral_type_class, boolean_type_class,
   4175     pointer_type_class, reference_type_class, offset_type_class,
   4176     real_type_class, complex_type_class,
   4177     function_type_class, method_type_class,
   4178     record_type_class, union_type_class,
   4179     array_type_class, string_type_class,
   4180     lang_type_class
   4181   };
   4182 
   4183   // If no argument was supplied, default to "no_type_class". This isn't
   4184   // ideal, however it is what gcc does.
   4185   if (E->getNumArgs() == 0)
   4186     return no_type_class;
   4187 
   4188   QualType ArgTy = E->getArg(0)->getType();
   4189   if (ArgTy->isVoidType())
   4190     return void_type_class;
   4191   else if (ArgTy->isEnumeralType())
   4192     return enumeral_type_class;
   4193   else if (ArgTy->isBooleanType())
   4194     return boolean_type_class;
   4195   else if (ArgTy->isCharType())
   4196     return string_type_class; // gcc doesn't appear to use char_type_class
   4197   else if (ArgTy->isIntegerType())
   4198     return integer_type_class;
   4199   else if (ArgTy->isPointerType())
   4200     return pointer_type_class;
   4201   else if (ArgTy->isReferenceType())
   4202     return reference_type_class;
   4203   else if (ArgTy->isRealType())
   4204     return real_type_class;
   4205   else if (ArgTy->isComplexType())
   4206     return complex_type_class;
   4207   else if (ArgTy->isFunctionType())
   4208     return function_type_class;
   4209   else if (ArgTy->isStructureOrClassType())
   4210     return record_type_class;
   4211   else if (ArgTy->isUnionType())
   4212     return union_type_class;
   4213   else if (ArgTy->isArrayType())
   4214     return array_type_class;
   4215   else if (ArgTy->isUnionType())
   4216     return union_type_class;
   4217   else  // FIXME: offset_type_class, method_type_class, & lang_type_class?
   4218     llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
   4219 }
   4220 
   4221 /// EvaluateBuiltinConstantPForLValue - Determine the result of
   4222 /// __builtin_constant_p when applied to the given lvalue.
   4223 ///
   4224 /// An lvalue is only "constant" if it is a pointer or reference to the first
   4225 /// character of a string literal.
   4226 template<typename LValue>
   4227 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
   4228   const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
   4229   return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
   4230 }
   4231 
   4232 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
   4233 /// GCC as we can manage.
   4234 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
   4235   QualType ArgType = Arg->getType();
   4236 
   4237   // __builtin_constant_p always has one operand. The rules which gcc follows
   4238   // are not precisely documented, but are as follows:
   4239   //
   4240   //  - If the operand is of integral, floating, complex or enumeration type,
   4241   //    and can be folded to a known value of that type, it returns 1.
   4242   //  - If the operand and can be folded to a pointer to the first character
   4243   //    of a string literal (or such a pointer cast to an integral type), it
   4244   //    returns 1.
   4245   //
   4246   // Otherwise, it returns 0.
   4247   //
   4248   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
   4249   // its support for this does not currently work.
   4250   if (ArgType->isIntegralOrEnumerationType()) {
   4251     Expr::EvalResult Result;
   4252     if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
   4253       return false;
   4254 
   4255     APValue &V = Result.Val;
   4256     if (V.getKind() == APValue::Int)
   4257       return true;
   4258 
   4259     return EvaluateBuiltinConstantPForLValue(V);
   4260   } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
   4261     return Arg->isEvaluatable(Ctx);
   4262   } else if (ArgType->isPointerType() || Arg->isGLValue()) {
   4263     LValue LV;
   4264     Expr::EvalStatus Status;
   4265     EvalInfo Info(Ctx, Status);
   4266     if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
   4267                           : EvaluatePointer(Arg, LV, Info)) &&
   4268         !Status.HasSideEffects)
   4269       return EvaluateBuiltinConstantPForLValue(LV);
   4270   }
   4271 
   4272   // Anything else isn't considered to be sufficiently constant.
   4273   return false;
   4274 }
   4275 
   4276 /// Retrieves the "underlying object type" of the given expression,
   4277 /// as used by __builtin_object_size.
   4278 QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
   4279   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
   4280     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
   4281       return VD->getType();
   4282   } else if (const Expr *E = B.get<const Expr*>()) {
   4283     if (isa<CompoundLiteralExpr>(E))
   4284       return E->getType();
   4285   }
   4286 
   4287   return QualType();
   4288 }
   4289 
   4290 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
   4291   // TODO: Perhaps we should let LLVM lower this?
   4292   LValue Base;
   4293   if (!EvaluatePointer(E->getArg(0), Base, Info))
   4294     return false;
   4295 
   4296   // If we can prove the base is null, lower to zero now.
   4297   if (!Base.getLValueBase()) return Success(0, E);
   4298 
   4299   QualType T = GetObjectType(Base.getLValueBase());
   4300   if (T.isNull() ||
   4301       T->isIncompleteType() ||
   4302       T->isFunctionType() ||
   4303       T->isVariablyModifiedType() ||
   4304       T->isDependentType())
   4305     return Error(E);
   4306 
   4307   CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
   4308   CharUnits Offset = Base.getLValueOffset();
   4309 
   4310   if (!Offset.isNegative() && Offset <= Size)
   4311     Size -= Offset;
   4312   else
   4313     Size = CharUnits::Zero();
   4314   return Success(Size, E);
   4315 }
   4316 
   4317 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
   4318   switch (unsigned BuiltinOp = E->isBuiltinCall()) {
   4319   default:
   4320     return ExprEvaluatorBaseTy::VisitCallExpr(E);
   4321 
   4322   case Builtin::BI__builtin_object_size: {
   4323     if (TryEvaluateBuiltinObjectSize(E))
   4324       return true;
   4325 
   4326     // If evaluating the argument has side-effects we can't determine
   4327     // the size of the object and lower it to unknown now.
   4328     if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
   4329       if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
   4330         return Success(-1ULL, E);
   4331       return Success(0, E);
   4332     }
   4333 
   4334     return Error(E);
   4335   }
   4336 
   4337   case Builtin::BI__builtin_classify_type:
   4338     return Success(EvaluateBuiltinClassifyType(E), E);
   4339 
   4340   case Builtin::BI__builtin_constant_p:
   4341     return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
   4342 
   4343   case Builtin::BI__builtin_eh_return_data_regno: {
   4344     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
   4345     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
   4346     return Success(Operand, E);
   4347   }
   4348 
   4349   case Builtin::BI__builtin_expect:
   4350     return Visit(E->getArg(0));
   4351 
   4352   case Builtin::BIstrlen:
   4353     // A call to strlen is not a constant expression.
   4354     if (Info.getLangOpts().CPlusPlus0x)
   4355       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
   4356         << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
   4357     else
   4358       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
   4359     // Fall through.
   4360   case Builtin::BI__builtin_strlen:
   4361     // As an extension, we support strlen() and __builtin_strlen() as constant
   4362     // expressions when the argument is a string literal.
   4363     if (const StringLiteral *S
   4364                = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
   4365       // The string literal may have embedded null characters. Find the first
   4366       // one and truncate there.
   4367       StringRef Str = S->getString();
   4368       StringRef::size_type Pos = Str.find(0);
   4369       if (Pos != StringRef::npos)
   4370         Str = Str.substr(0, Pos);
   4371 
   4372       return Success(Str.size(), E);
   4373     }
   4374 
   4375     return Error(E);
   4376 
   4377   case Builtin::BI__atomic_always_lock_free:
   4378   case Builtin::BI__atomic_is_lock_free:
   4379   case Builtin::BI__c11_atomic_is_lock_free: {
   4380     APSInt SizeVal;
   4381     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
   4382       return false;
   4383 
   4384     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
   4385     // of two less than the maximum inline atomic width, we know it is
   4386     // lock-free.  If the size isn't a power of two, or greater than the
   4387     // maximum alignment where we promote atomics, we know it is not lock-free
   4388     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
   4389     // the answer can only be determined at runtime; for example, 16-byte
   4390     // atomics have lock-free implementations on some, but not all,
   4391     // x86-64 processors.
   4392 
   4393     // Check power-of-two.
   4394     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
   4395     if (Size.isPowerOfTwo()) {
   4396       // Check against inlining width.
   4397       unsigned InlineWidthBits =
   4398           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
   4399       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
   4400         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
   4401             Size == CharUnits::One() ||
   4402             E->getArg(1)->isNullPointerConstant(Info.Ctx,
   4403                                                 Expr::NPC_NeverValueDependent))
   4404           // OK, we will inline appropriately-aligned operations of this size,
   4405           // and _Atomic(T) is appropriately-aligned.
   4406           return Success(1, E);
   4407 
   4408         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
   4409           castAs<PointerType>()->getPointeeType();
   4410         if (!PointeeType->isIncompleteType() &&
   4411             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
   4412           // OK, we will inline operations on this object.
   4413           return Success(1, E);
   4414         }
   4415       }
   4416     }
   4417 
   4418     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
   4419         Success(0, E) : Error(E);
   4420   }
   4421   }
   4422 }
   4423 
   4424 static bool HasSameBase(const LValue &A, const LValue &B) {
   4425   if (!A.getLValueBase())
   4426     return !B.getLValueBase();
   4427   if (!B.getLValueBase())
   4428     return false;
   4429 
   4430   if (A.getLValueBase().getOpaqueValue() !=
   4431       B.getLValueBase().getOpaqueValue()) {
   4432     const Decl *ADecl = GetLValueBaseDecl(A);
   4433     if (!ADecl)
   4434       return false;
   4435     const Decl *BDecl = GetLValueBaseDecl(B);
   4436     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
   4437       return false;
   4438   }
   4439 
   4440   return IsGlobalLValue(A.getLValueBase()) ||
   4441          A.getLValueCallIndex() == B.getLValueCallIndex();
   4442 }
   4443 
   4444 /// Perform the given integer operation, which is known to need at most BitWidth
   4445 /// bits, and check for overflow in the original type (if that type was not an
   4446 /// unsigned type).
   4447 template<typename Operation>
   4448 static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
   4449                                    const APSInt &LHS, const APSInt &RHS,
   4450                                    unsigned BitWidth, Operation Op) {
   4451   if (LHS.isUnsigned())
   4452     return Op(LHS, RHS);
   4453 
   4454   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
   4455   APSInt Result = Value.trunc(LHS.getBitWidth());
   4456   if (Result.extend(BitWidth) != Value)
   4457     HandleOverflow(Info, E, Value, E->getType());
   4458   return Result;
   4459 }
   4460 
   4461 namespace {
   4462 
   4463 /// \brief Data recursive integer evaluator of certain binary operators.
   4464 ///
   4465 /// We use a data recursive algorithm for binary operators so that we are able
   4466 /// to handle extreme cases of chained binary operators without causing stack
   4467 /// overflow.
   4468 class DataRecursiveIntBinOpEvaluator {
   4469   struct EvalResult {
   4470     APValue Val;
   4471     bool Failed;
   4472 
   4473     EvalResult() : Failed(false) { }
   4474 
   4475     void swap(EvalResult &RHS) {
   4476       Val.swap(RHS.Val);
   4477       Failed = RHS.Failed;
   4478       RHS.Failed = false;
   4479     }
   4480   };
   4481 
   4482   struct Job {
   4483     const Expr *E;
   4484     EvalResult LHSResult; // meaningful only for binary operator expression.
   4485     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
   4486 
   4487     Job() : StoredInfo(0) { }
   4488     void startSpeculativeEval(EvalInfo &Info) {
   4489       OldEvalStatus = Info.EvalStatus;
   4490       Info.EvalStatus.Diag = 0;
   4491       StoredInfo = &Info;
   4492     }
   4493     ~Job() {
   4494       if (StoredInfo) {
   4495         StoredInfo->EvalStatus = OldEvalStatus;
   4496       }
   4497     }
   4498   private:
   4499     EvalInfo *StoredInfo; // non-null if status changed.
   4500     Expr::EvalStatus OldEvalStatus;
   4501   };
   4502 
   4503   SmallVector<Job, 16> Queue;
   4504 
   4505   IntExprEvaluator &IntEval;
   4506   EvalInfo &Info;
   4507   APValue &FinalResult;
   4508 
   4509 public:
   4510   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
   4511     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
   4512 
   4513   /// \brief True if \param E is a binary operator that we are going to handle
   4514   /// data recursively.
   4515   /// We handle binary operators that are comma, logical, or that have operands
   4516   /// with integral or enumeration type.
   4517   static bool shouldEnqueue(const BinaryOperator *E) {
   4518     return E->getOpcode() == BO_Comma ||
   4519            E->isLogicalOp() ||
   4520            (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
   4521             E->getRHS()->getType()->isIntegralOrEnumerationType());
   4522   }
   4523 
   4524   bool Traverse(const BinaryOperator *E) {
   4525     enqueue(E);
   4526     EvalResult PrevResult;
   4527     while (!Queue.empty())
   4528       process(PrevResult);
   4529 
   4530     if (PrevResult.Failed) return false;
   4531 
   4532     FinalResult.swap(PrevResult.Val);
   4533     return true;
   4534   }
   4535 
   4536 private:
   4537   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
   4538     return IntEval.Success(Value, E, Result);
   4539   }
   4540   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
   4541     return IntEval.Success(Value, E, Result);
   4542   }
   4543   bool Error(const Expr *E) {
   4544     return IntEval.Error(E);
   4545   }
   4546   bool Error(const Expr *E, diag::kind D) {
   4547     return IntEval.Error(E, D);
   4548   }
   4549 
   4550   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
   4551     return Info.CCEDiag(E, D);
   4552   }
   4553 
   4554   // \brief Returns true if visiting the RHS is necessary, false otherwise.
   4555   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
   4556                          bool &SuppressRHSDiags);
   4557 
   4558   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
   4559                   const BinaryOperator *E, APValue &Result);
   4560 
   4561   void EvaluateExpr(const Expr *E, EvalResult &Result) {
   4562     Result.Failed = !Evaluate(Result.Val, Info, E);
   4563     if (Result.Failed)
   4564       Result.Val = APValue();
   4565   }
   4566 
   4567   void process(EvalResult &Result);
   4568 
   4569   void enqueue(const Expr *E) {
   4570     E = E->IgnoreParens();
   4571     Queue.resize(Queue.size()+1);
   4572     Queue.back().E = E;
   4573     Queue.back().Kind = Job::AnyExprKind;
   4574   }
   4575 };
   4576 
   4577 }
   4578 
   4579 bool DataRecursiveIntBinOpEvaluator::
   4580        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
   4581                          bool &SuppressRHSDiags) {
   4582   if (E->getOpcode() == BO_Comma) {
   4583     // Ignore LHS but note if we could not evaluate it.
   4584     if (LHSResult.Failed)
   4585       Info.EvalStatus.HasSideEffects = true;
   4586     return true;
   4587   }
   4588 
   4589   if (E->isLogicalOp()) {
   4590     bool lhsResult;
   4591     if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
   4592       // We were able to evaluate the LHS, see if we can get away with not
   4593       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
   4594       if (lhsResult == (E->getOpcode() == BO_LOr)) {
   4595         Success(lhsResult, E, LHSResult.Val);
   4596         return false; // Ignore RHS
   4597       }
   4598     } else {
   4599       // Since we weren't able to evaluate the left hand side, it
   4600       // must have had side effects.
   4601       Info.EvalStatus.HasSideEffects = true;
   4602 
   4603       // We can't evaluate the LHS; however, sometimes the result
   4604       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
   4605       // Don't ignore RHS and suppress diagnostics from this arm.
   4606       SuppressRHSDiags = true;
   4607     }
   4608 
   4609     return true;
   4610   }
   4611 
   4612   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
   4613          E->getRHS()->getType()->isIntegralOrEnumerationType());
   4614 
   4615   if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
   4616     return false; // Ignore RHS;
   4617 
   4618   return true;
   4619 }
   4620 
   4621 bool DataRecursiveIntBinOpEvaluator::
   4622        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
   4623                   const BinaryOperator *E, APValue &Result) {
   4624   if (E->getOpcode() == BO_Comma) {
   4625     if (RHSResult.Failed)
   4626       return false;
   4627     Result = RHSResult.Val;
   4628     return true;
   4629   }
   4630 
   4631   if (E->isLogicalOp()) {
   4632     bool lhsResult, rhsResult;
   4633     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
   4634     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
   4635 
   4636     if (LHSIsOK) {
   4637       if (RHSIsOK) {
   4638         if (E->getOpcode() == BO_LOr)
   4639           return Success(lhsResult || rhsResult, E, Result);
   4640         else
   4641           return Success(lhsResult && rhsResult, E, Result);
   4642       }
   4643     } else {
   4644       if (RHSIsOK) {
   4645         // We can't evaluate the LHS; however, sometimes the result
   4646         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
   4647         if (rhsResult == (E->getOpcode() == BO_LOr))
   4648           return Success(rhsResult, E, Result);
   4649       }
   4650     }
   4651 
   4652     return false;
   4653   }
   4654 
   4655   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
   4656          E->getRHS()->getType()->isIntegralOrEnumerationType());
   4657 
   4658   if (LHSResult.Failed || RHSResult.Failed)
   4659     return false;
   4660 
   4661   const APValue &LHSVal = LHSResult.Val;
   4662   const APValue &RHSVal = RHSResult.Val;
   4663 
   4664   // Handle cases like (unsigned long)&a + 4.
   4665   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
   4666     Result = LHSVal;
   4667     CharUnits AdditionalOffset = CharUnits::fromQuantity(
   4668                                                          RHSVal.getInt().getZExtValue());
   4669     if (E->getOpcode() == BO_Add)
   4670       Result.getLValueOffset() += AdditionalOffset;
   4671     else
   4672       Result.getLValueOffset() -= AdditionalOffset;
   4673     return true;
   4674   }
   4675 
   4676   // Handle cases like 4 + (unsigned long)&a
   4677   if (E->getOpcode() == BO_Add &&
   4678       RHSVal.isLValue() && LHSVal.isInt()) {
   4679     Result = RHSVal;
   4680     Result.getLValueOffset() += CharUnits::fromQuantity(
   4681                                                         LHSVal.getInt().getZExtValue());
   4682     return true;
   4683   }
   4684 
   4685   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
   4686     // Handle (intptr_t)&&A - (intptr_t)&&B.
   4687     if (!LHSVal.getLValueOffset().isZero() ||
   4688         !RHSVal.getLValueOffset().isZero())
   4689       return false;
   4690     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
   4691     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
   4692     if (!LHSExpr || !RHSExpr)
   4693       return false;
   4694     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
   4695     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
   4696     if (!LHSAddrExpr || !RHSAddrExpr)
   4697       return false;
   4698     // Make sure both labels come from the same function.
   4699     if (LHSAddrExpr->getLabel()->getDeclContext() !=
   4700         RHSAddrExpr->getLabel()->getDeclContext())
   4701       return false;
   4702     Result = APValue(LHSAddrExpr, RHSAddrExpr);
   4703     return true;
   4704   }
   4705 
   4706   // All the following cases expect both operands to be an integer
   4707   if (!LHSVal.isInt() || !RHSVal.isInt())
   4708     return Error(E);
   4709 
   4710   const APSInt &LHS = LHSVal.getInt();
   4711   APSInt RHS = RHSVal.getInt();
   4712 
   4713   switch (E->getOpcode()) {
   4714     default:
   4715       return Error(E);
   4716     case BO_Mul:
   4717       return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
   4718                                           LHS.getBitWidth() * 2,
   4719                                           std::multiplies<APSInt>()), E,
   4720                      Result);
   4721     case BO_Add:
   4722       return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
   4723                                           LHS.getBitWidth() + 1,
   4724                                           std::plus<APSInt>()), E, Result);
   4725     case BO_Sub:
   4726       return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
   4727                                           LHS.getBitWidth() + 1,
   4728                                           std::minus<APSInt>()), E, Result);
   4729     case BO_And: return Success(LHS & RHS, E, Result);
   4730     case BO_Xor: return Success(LHS ^ RHS, E, Result);
   4731     case BO_Or:  return Success(LHS | RHS, E, Result);
   4732     case BO_Div:
   4733     case BO_Rem:
   4734       if (RHS == 0)
   4735         return Error(E, diag::note_expr_divide_by_zero);
   4736       // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
   4737       // not actually undefined behavior in C++11 due to a language defect.
   4738       if (RHS.isNegative() && RHS.isAllOnesValue() &&
   4739           LHS.isSigned() && LHS.isMinSignedValue())
   4740         HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
   4741       return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
   4742                      Result);
   4743     case BO_Shl: {
   4744       // During constant-folding, a negative shift is an opposite shift. Such
   4745       // a shift is not a constant expression.
   4746       if (RHS.isSigned() && RHS.isNegative()) {
   4747         CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
   4748         RHS = -RHS;
   4749         goto shift_right;
   4750       }
   4751 
   4752     shift_left:
   4753       // C++11 [expr.shift]p1: Shift width must be less than the bit width of
   4754       // the shifted type.
   4755       unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
   4756       if (SA != RHS) {
   4757         CCEDiag(E, diag::note_constexpr_large_shift)
   4758         << RHS << E->getType() << LHS.getBitWidth();
   4759       } else if (LHS.isSigned()) {
   4760         // C++11 [expr.shift]p2: A signed left shift must have a non-negative
   4761         // operand, and must not overflow the corresponding unsigned type.
   4762         if (LHS.isNegative())
   4763           CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
   4764         else if (LHS.countLeadingZeros() < SA)
   4765           CCEDiag(E, diag::note_constexpr_lshift_discards);
   4766       }
   4767 
   4768       return Success(LHS << SA, E, Result);
   4769     }
   4770     case BO_Shr: {
   4771       // During constant-folding, a negative shift is an opposite shift. Such a
   4772       // shift is not a constant expression.
   4773       if (RHS.isSigned() && RHS.isNegative()) {
   4774         CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
   4775         RHS = -RHS;
   4776         goto shift_left;
   4777       }
   4778 
   4779     shift_right:
   4780       // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
   4781       // shifted type.
   4782       unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
   4783       if (SA != RHS)
   4784         CCEDiag(E, diag::note_constexpr_large_shift)
   4785         << RHS << E->getType() << LHS.getBitWidth();
   4786 
   4787       return Success(LHS >> SA, E, Result);
   4788     }
   4789 
   4790     case BO_LT: return Success(LHS < RHS, E, Result);
   4791     case BO_GT: return Success(LHS > RHS, E, Result);
   4792     case BO_LE: return Success(LHS <= RHS, E, Result);
   4793     case BO_GE: return Success(LHS >= RHS, E, Result);
   4794     case BO_EQ: return Success(LHS == RHS, E, Result);
   4795     case BO_NE: return Success(LHS != RHS, E, Result);
   4796   }
   4797 }
   4798 
   4799 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
   4800   Job &job = Queue.back();
   4801 
   4802   switch (job.Kind) {
   4803     case Job::AnyExprKind: {
   4804       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
   4805         if (shouldEnqueue(Bop)) {
   4806           job.Kind = Job::BinOpKind;
   4807           enqueue(Bop->getLHS());
   4808           return;
   4809         }
   4810       }
   4811 
   4812       EvaluateExpr(job.E, Result);
   4813       Queue.pop_back();
   4814       return;
   4815     }
   4816 
   4817     case Job::BinOpKind: {
   4818       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
   4819       bool SuppressRHSDiags = false;
   4820       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
   4821         Queue.pop_back();
   4822         return;
   4823       }
   4824       if (SuppressRHSDiags)
   4825         job.startSpeculativeEval(Info);
   4826       job.LHSResult.swap(Result);
   4827       job.Kind = Job::BinOpVisitedLHSKind;
   4828       enqueue(Bop->getRHS());
   4829       return;
   4830     }
   4831 
   4832     case Job::BinOpVisitedLHSKind: {
   4833       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
   4834       EvalResult RHS;
   4835       RHS.swap(Result);
   4836       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
   4837       Queue.pop_back();
   4838       return;
   4839     }
   4840   }
   4841 
   4842   llvm_unreachable("Invalid Job::Kind!");
   4843 }
   4844 
   4845 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
   4846   if (E->isAssignmentOp())
   4847     return Error(E);
   4848 
   4849   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
   4850     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
   4851 
   4852   QualType LHSTy = E->getLHS()->getType();
   4853   QualType RHSTy = E->getRHS()->getType();
   4854 
   4855   if (LHSTy->isAnyComplexType()) {
   4856     assert(RHSTy->isAnyComplexType() && "Invalid comparison");
   4857     ComplexValue LHS, RHS;
   4858 
   4859     bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
   4860     if (!LHSOK && !Info.keepEvaluatingAfterFailure())
   4861       return false;
   4862 
   4863     if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
   4864       return false;
   4865 
   4866     if (LHS.isComplexFloat()) {
   4867       APFloat::cmpResult CR_r =
   4868         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
   4869       APFloat::cmpResult CR_i =
   4870         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
   4871 
   4872       if (E->getOpcode() == BO_EQ)
   4873         return Success((CR_r == APFloat::cmpEqual &&
   4874                         CR_i == APFloat::cmpEqual), E);
   4875       else {
   4876         assert(E->getOpcode() == BO_NE &&
   4877                "Invalid complex comparison.");
   4878         return Success(((CR_r == APFloat::cmpGreaterThan ||
   4879                          CR_r == APFloat::cmpLessThan ||
   4880                          CR_r == APFloat::cmpUnordered) ||
   4881                         (CR_i == APFloat::cmpGreaterThan ||
   4882                          CR_i == APFloat::cmpLessThan ||
   4883                          CR_i == APFloat::cmpUnordered)), E);
   4884       }
   4885     } else {
   4886       if (E->getOpcode() == BO_EQ)
   4887         return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
   4888                         LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
   4889       else {
   4890         assert(E->getOpcode() == BO_NE &&
   4891                "Invalid compex comparison.");
   4892         return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
   4893                         LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
   4894       }
   4895     }
   4896   }
   4897 
   4898   if (LHSTy->isRealFloatingType() &&
   4899       RHSTy->isRealFloatingType()) {
   4900     APFloat RHS(0.0), LHS(0.0);
   4901 
   4902     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
   4903     if (!LHSOK && !Info.keepEvaluatingAfterFailure())
   4904       return false;
   4905 
   4906     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
   4907       return false;
   4908 
   4909     APFloat::cmpResult CR = LHS.compare(RHS);
   4910 
   4911     switch (E->getOpcode()) {
   4912     default:
   4913       llvm_unreachable("Invalid binary operator!");
   4914     case BO_LT:
   4915       return Success(CR == APFloat::cmpLessThan, E);
   4916     case BO_GT:
   4917       return Success(CR == APFloat::cmpGreaterThan, E);
   4918     case BO_LE:
   4919       return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
   4920     case BO_GE:
   4921       return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
   4922                      E);
   4923     case BO_EQ:
   4924       return Success(CR == APFloat::cmpEqual, E);
   4925     case BO_NE:
   4926       return Success(CR == APFloat::cmpGreaterThan
   4927                      || CR == APFloat::cmpLessThan
   4928                      || CR == APFloat::cmpUnordered, E);
   4929     }
   4930   }
   4931 
   4932   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
   4933     if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
   4934       LValue LHSValue, RHSValue;
   4935 
   4936       bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
   4937       if (!LHSOK && Info.keepEvaluatingAfterFailure())
   4938         return false;
   4939 
   4940       if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
   4941         return false;
   4942 
   4943       // Reject differing bases from the normal codepath; we special-case
   4944       // comparisons to null.
   4945       if (!HasSameBase(LHSValue, RHSValue)) {
   4946         if (E->getOpcode() == BO_Sub) {
   4947           // Handle &&A - &&B.
   4948           if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
   4949             return false;
   4950           const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
   4951           const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
   4952           if (!LHSExpr || !RHSExpr)
   4953             return false;
   4954           const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
   4955           const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
   4956           if (!LHSAddrExpr || !RHSAddrExpr)
   4957             return false;
   4958           // Make sure both labels come from the same function.
   4959           if (LHSAddrExpr->getLabel()->getDeclContext() !=
   4960               RHSAddrExpr->getLabel()->getDeclContext())
   4961             return false;
   4962           Result = APValue(LHSAddrExpr, RHSAddrExpr);
   4963           return true;
   4964         }
   4965         // Inequalities and subtractions between unrelated pointers have
   4966         // unspecified or undefined behavior.
   4967         if (!E->isEqualityOp())
   4968           return Error(E);
   4969         // A constant address may compare equal to the address of a symbol.
   4970         // The one exception is that address of an object cannot compare equal
   4971         // to a null pointer constant.
   4972         if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
   4973             (!RHSValue.Base && !RHSValue.Offset.isZero()))
   4974           return Error(E);
   4975         // It's implementation-defined whether distinct literals will have
   4976         // distinct addresses. In clang, the result of such a comparison is
   4977         // unspecified, so it is not a constant expression. However, we do know
   4978         // that the address of a literal will be non-null.
   4979         if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
   4980             LHSValue.Base && RHSValue.Base)
   4981           return Error(E);
   4982         // We can't tell whether weak symbols will end up pointing to the same
   4983         // object.
   4984         if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
   4985           return Error(E);
   4986         // Pointers with different bases cannot represent the same object.
   4987         // (Note that clang defaults to -fmerge-all-constants, which can
   4988         // lead to inconsistent results for comparisons involving the address
   4989         // of a constant; this generally doesn't matter in practice.)
   4990         return Success(E->getOpcode() == BO_NE, E);
   4991       }
   4992 
   4993       const CharUnits &LHSOffset = LHSValue.getLValueOffset();
   4994       const CharUnits &RHSOffset = RHSValue.getLValueOffset();
   4995 
   4996       SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
   4997       SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
   4998 
   4999       if (E->getOpcode() == BO_Sub) {
   5000         // C++11 [expr.add]p6:
   5001         //   Unless both pointers point to elements of the same array object, or
   5002         //   one past the last element of the array object, the behavior is
   5003         //   undefined.
   5004         if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
   5005             !AreElementsOfSameArray(getType(LHSValue.Base),
   5006                                     LHSDesignator, RHSDesignator))
   5007           CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
   5008 
   5009         QualType Type = E->getLHS()->getType();
   5010         QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
   5011 
   5012         CharUnits ElementSize;
   5013         if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
   5014           return false;
   5015 
   5016         // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
   5017         // and produce incorrect results when it overflows. Such behavior
   5018         // appears to be non-conforming, but is common, so perhaps we should
   5019         // assume the standard intended for such cases to be undefined behavior
   5020         // and check for them.
   5021 
   5022         // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
   5023         // overflow in the final conversion to ptrdiff_t.
   5024         APSInt LHS(
   5025           llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
   5026         APSInt RHS(
   5027           llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
   5028         APSInt ElemSize(
   5029           llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
   5030         APSInt TrueResult = (LHS - RHS) / ElemSize;
   5031         APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
   5032 
   5033         if (Result.extend(65) != TrueResult)
   5034           HandleOverflow(Info, E, TrueResult, E->getType());
   5035         return Success(Result, E);
   5036       }
   5037 
   5038       // C++11 [expr.rel]p3:
   5039       //   Pointers to void (after pointer conversions) can be compared, with a
   5040       //   result defined as follows: If both pointers represent the same
   5041       //   address or are both the null pointer value, the result is true if the
   5042       //   operator is <= or >= and false otherwise; otherwise the result is
   5043       //   unspecified.
   5044       // We interpret this as applying to pointers to *cv* void.
   5045       if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
   5046           E->isRelationalOp())
   5047         CCEDiag(E, diag::note_constexpr_void_comparison);
   5048 
   5049       // C++11 [expr.rel]p2:
   5050       // - If two pointers point to non-static data members of the same object,
   5051       //   or to subobjects or array elements fo such members, recursively, the
   5052       //   pointer to the later declared member compares greater provided the
   5053       //   two members have the same access control and provided their class is
   5054       //   not a union.
   5055       //   [...]
   5056       // - Otherwise pointer comparisons are unspecified.
   5057       if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
   5058           E->isRelationalOp()) {
   5059         bool WasArrayIndex;
   5060         unsigned Mismatch =
   5061           FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
   5062                                  RHSDesignator, WasArrayIndex);
   5063         // At the point where the designators diverge, the comparison has a
   5064         // specified value if:
   5065         //  - we are comparing array indices
   5066         //  - we are comparing fields of a union, or fields with the same access
   5067         // Otherwise, the result is unspecified and thus the comparison is not a
   5068         // constant expression.
   5069         if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
   5070             Mismatch < RHSDesignator.Entries.size()) {
   5071           const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
   5072           const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
   5073           if (!LF && !RF)
   5074             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
   5075           else if (!LF)
   5076             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
   5077               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
   5078               << RF->getParent() << RF;
   5079           else if (!RF)
   5080             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
   5081               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
   5082               << LF->getParent() << LF;
   5083           else if (!LF->getParent()->isUnion() &&
   5084                    LF->getAccess() != RF->getAccess())
   5085             CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
   5086               << LF << LF->getAccess() << RF << RF->getAccess()
   5087               << LF->getParent();
   5088         }
   5089       }
   5090 
   5091       // The comparison here must be unsigned, and performed with the same
   5092       // width as the pointer.
   5093       unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
   5094       uint64_t CompareLHS = LHSOffset.getQuantity();
   5095       uint64_t CompareRHS = RHSOffset.getQuantity();
   5096       assert(PtrSize <= 64 && "Unexpected pointer width");
   5097       uint64_t Mask = ~0ULL >> (64 - PtrSize);
   5098       CompareLHS &= Mask;
   5099       CompareRHS &= Mask;
   5100 
   5101       // If there is a base and this is a relational operator, we can only
   5102       // compare pointers within the object in question; otherwise, the result
   5103       // depends on where the object is located in memory.
   5104       if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
   5105         QualType BaseTy = getType(LHSValue.Base);
   5106         if (BaseTy->isIncompleteType())
   5107           return Error(E);
   5108         CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
   5109         uint64_t OffsetLimit = Size.getQuantity();
   5110         if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
   5111           return Error(E);
   5112       }
   5113 
   5114       switch (E->getOpcode()) {
   5115       default: llvm_unreachable("missing comparison operator");
   5116       case BO_LT: return Success(CompareLHS < CompareRHS, E);
   5117       case BO_GT: return Success(CompareLHS > CompareRHS, E);
   5118       case BO_LE: return Success(CompareLHS <= CompareRHS, E);
   5119       case BO_GE: return Success(CompareLHS >= CompareRHS, E);
   5120       case BO_EQ: return Success(CompareLHS == CompareRHS, E);
   5121       case BO_NE: return Success(CompareLHS != CompareRHS, E);
   5122       }
   5123     }
   5124   }
   5125 
   5126   if (LHSTy->isMemberPointerType()) {
   5127     assert(E->isEqualityOp() && "unexpected member pointer operation");
   5128     assert(RHSTy->isMemberPointerType() && "invalid comparison");
   5129 
   5130     MemberPtr LHSValue, RHSValue;
   5131 
   5132     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
   5133     if (!LHSOK && Info.keepEvaluatingAfterFailure())
   5134       return false;
   5135 
   5136     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
   5137       return false;
   5138 
   5139     // C++11 [expr.eq]p2:
   5140     //   If both operands are null, they compare equal. Otherwise if only one is
   5141     //   null, they compare unequal.
   5142     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
   5143       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
   5144       return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
   5145     }
   5146 
   5147     //   Otherwise if either is a pointer to a virtual member function, the
   5148     //   result is unspecified.
   5149     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
   5150       if (MD->isVirtual())
   5151         CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
   5152     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
   5153       if (MD->isVirtual())
   5154         CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
   5155 
   5156     //   Otherwise they compare equal if and only if they would refer to the
   5157     //   same member of the same most derived object or the same subobject if
   5158     //   they were dereferenced with a hypothetical object of the associated
   5159     //   class type.
   5160     bool Equal = LHSValue == RHSValue;
   5161     return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
   5162   }
   5163 
   5164   if (LHSTy->isNullPtrType()) {
   5165     assert(E->isComparisonOp() && "unexpected nullptr operation");
   5166     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
   5167     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
   5168     // are compared, the result is true of the operator is <=, >= or ==, and
   5169     // false otherwise.
   5170     BinaryOperator::Opcode Opcode = E->getOpcode();
   5171     return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
   5172   }
   5173 
   5174   assert((!LHSTy->isIntegralOrEnumerationType() ||
   5175           !RHSTy->isIntegralOrEnumerationType()) &&
   5176          "DataRecursiveIntBinOpEvaluator should have handled integral types");
   5177   // We can't continue from here for non-integral types.
   5178   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
   5179 }
   5180 
   5181 CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
   5182   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
   5183   //   result shall be the alignment of the referenced type."
   5184   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
   5185     T = Ref->getPointeeType();
   5186 
   5187   // __alignof is defined to return the preferred alignment.
   5188   return Info.Ctx.toCharUnitsFromBits(
   5189     Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
   5190 }
   5191 
   5192 CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
   5193   E = E->IgnoreParens();
   5194 
   5195   // alignof decl is always accepted, even if it doesn't make sense: we default
   5196   // to 1 in those cases.
   5197   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
   5198     return Info.Ctx.getDeclAlign(DRE->getDecl(),
   5199                                  /*RefAsPointee*/true);
   5200 
   5201   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
   5202     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
   5203                                  /*RefAsPointee*/true);
   5204 
   5205   return GetAlignOfType(E->getType());
   5206 }
   5207 
   5208 
   5209 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
   5210 /// a result as the expression's type.
   5211 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
   5212                                     const UnaryExprOrTypeTraitExpr *E) {
   5213   switch(E->getKind()) {
   5214   case UETT_AlignOf: {
   5215     if (E->isArgumentType())
   5216       return Success(GetAlignOfType(E->getArgumentType()), E);
   5217     else
   5218       return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
   5219   }
   5220 
   5221   case UETT_VecStep: {
   5222     QualType Ty = E->getTypeOfArgument();
   5223 
   5224     if (Ty->isVectorType()) {
   5225       unsigned n = Ty->getAs<VectorType>()->getNumElements();
   5226 
   5227       // The vec_step built-in functions that take a 3-component
   5228       // vector return 4. (OpenCL 1.1 spec 6.11.12)
   5229       if (n == 3)
   5230         n = 4;
   5231 
   5232       return Success(n, E);
   5233     } else
   5234       return Success(1, E);
   5235   }
   5236 
   5237   case UETT_SizeOf: {
   5238     QualType SrcTy = E->getTypeOfArgument();
   5239     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
   5240     //   the result is the size of the referenced type."
   5241     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
   5242       SrcTy = Ref->getPointeeType();
   5243 
   5244     CharUnits Sizeof;
   5245     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
   5246       return false;
   5247     return Success(Sizeof, E);
   5248   }
   5249   }
   5250 
   5251   llvm_unreachable("unknown expr/type trait");
   5252 }
   5253 
   5254 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
   5255   CharUnits Result;
   5256   unsigned n = OOE->getNumComponents();
   5257   if (n == 0)
   5258     return Error(OOE);
   5259   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
   5260   for (unsigned i = 0; i != n; ++i) {
   5261     OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
   5262     switch (ON.getKind()) {
   5263     case OffsetOfExpr::OffsetOfNode::Array: {
   5264       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
   5265       APSInt IdxResult;
   5266       if (!EvaluateInteger(Idx, IdxResult, Info))
   5267         return false;
   5268       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
   5269       if (!AT)
   5270         return Error(OOE);
   5271       CurrentType = AT->getElementType();
   5272       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
   5273       Result += IdxResult.getSExtValue() * ElementSize;
   5274         break;
   5275     }
   5276 
   5277     case OffsetOfExpr::OffsetOfNode::Field: {
   5278       FieldDecl *MemberDecl = ON.getField();
   5279       const RecordType *RT = CurrentType->getAs<RecordType>();
   5280       if (!RT)
   5281         return Error(OOE);
   5282       RecordDecl *RD = RT->getDecl();
   5283       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
   5284       unsigned i = MemberDecl->getFieldIndex();
   5285       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
   5286       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
   5287       CurrentType = MemberDecl->getType().getNonReferenceType();
   5288       break;
   5289     }
   5290 
   5291     case OffsetOfExpr::OffsetOfNode::Identifier:
   5292       llvm_unreachable("dependent __builtin_offsetof");
   5293 
   5294     case OffsetOfExpr::OffsetOfNode::Base: {
   5295       CXXBaseSpecifier *BaseSpec = ON.getBase();
   5296       if (BaseSpec->isVirtual())
   5297         return Error(OOE);
   5298 
   5299       // Find the layout of the class whose base we are looking into.
   5300       const RecordType *RT = CurrentType->getAs<RecordType>();
   5301       if (!RT)
   5302         return Error(OOE);
   5303       RecordDecl *RD = RT->getDecl();
   5304       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
   5305 
   5306       // Find the base class itself.
   5307       CurrentType = BaseSpec->getType();
   5308       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
   5309       if (!BaseRT)
   5310         return Error(OOE);
   5311 
   5312       // Add the offset to the base.
   5313       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
   5314       break;
   5315     }
   5316     }
   5317   }
   5318   return Success(Result, OOE);
   5319 }
   5320 
   5321 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
   5322   switch (E->getOpcode()) {
   5323   default:
   5324     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
   5325     // See C99 6.6p3.
   5326     return Error(E);
   5327   case UO_Extension:
   5328     // FIXME: Should extension allow i-c-e extension expressions in its scope?
   5329     // If so, we could clear the diagnostic ID.
   5330     return Visit(E->getSubExpr());
   5331   case UO_Plus:
   5332     // The result is just the value.
   5333     return Visit(E->getSubExpr());
   5334   case UO_Minus: {
   5335     if (!Visit(E->getSubExpr()))
   5336       return false;
   5337     if (!Result.isInt()) return Error(E);
   5338     const APSInt &Value = Result.getInt();
   5339     if (Value.isSigned() && Value.isMinSignedValue())
   5340       HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
   5341                      E->getType());
   5342     return Success(-Value, E);
   5343   }
   5344   case UO_Not: {
   5345     if (!Visit(E->getSubExpr()))
   5346       return false;
   5347     if (!Result.isInt()) return Error(E);
   5348     return Success(~Result.getInt(), E);
   5349   }
   5350   case UO_LNot: {
   5351     bool bres;
   5352     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
   5353       return false;
   5354     return Success(!bres, E);
   5355   }
   5356   }
   5357 }
   5358 
   5359 /// HandleCast - This is used to evaluate implicit or explicit casts where the
   5360 /// result type is integer.
   5361 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
   5362   const Expr *SubExpr = E->getSubExpr();
   5363   QualType DestType = E->getType();
   5364   QualType SrcType = SubExpr->getType();
   5365 
   5366   switch (E->getCastKind()) {
   5367   case CK_BaseToDerived:
   5368   case CK_DerivedToBase:
   5369   case CK_UncheckedDerivedToBase:
   5370   case CK_Dynamic:
   5371   case CK_ToUnion:
   5372   case CK_ArrayToPointerDecay:
   5373   case CK_FunctionToPointerDecay:
   5374   case CK_NullToPointer:
   5375   case CK_NullToMemberPointer:
   5376   case CK_BaseToDerivedMemberPointer:
   5377   case CK_DerivedToBaseMemberPointer:
   5378   case CK_ReinterpretMemberPointer:
   5379   case CK_ConstructorConversion:
   5380   case CK_IntegralToPointer:
   5381   case CK_ToVoid:
   5382   case CK_VectorSplat:
   5383   case CK_IntegralToFloating:
   5384   case CK_FloatingCast:
   5385   case CK_CPointerToObjCPointerCast:
   5386   case CK_BlockPointerToObjCPointerCast:
   5387   case CK_AnyPointerToBlockPointerCast:
   5388   case CK_ObjCObjectLValueCast:
   5389   case CK_FloatingRealToComplex:
   5390   case CK_FloatingComplexToReal:
   5391   case CK_FloatingComplexCast:
   5392   case CK_FloatingComplexToIntegralComplex:
   5393   case CK_IntegralRealToComplex:
   5394   case CK_IntegralComplexCast:
   5395   case CK_IntegralComplexToFloatingComplex:
   5396     llvm_unreachable("invalid cast kind for integral value");
   5397 
   5398   case CK_BitCast:
   5399   case CK_Dependent:
   5400   case CK_LValueBitCast:
   5401   case CK_ARCProduceObject:
   5402   case CK_ARCConsumeObject:
   5403   case CK_ARCReclaimReturnedObject:
   5404   case CK_ARCExtendBlockObject:
   5405   case CK_CopyAndAutoreleaseBlockObject:
   5406     return Error(E);
   5407 
   5408   case CK_UserDefinedConversion:
   5409   case CK_LValueToRValue:
   5410   case CK_AtomicToNonAtomic:
   5411   case CK_NonAtomicToAtomic:
   5412   case CK_NoOp:
   5413     return ExprEvaluatorBaseTy::VisitCastExpr(E);
   5414 
   5415   case CK_MemberPointerToBoolean:
   5416   case CK_PointerToBoolean:
   5417   case CK_IntegralToBoolean:
   5418   case CK_FloatingToBoolean:
   5419   case CK_FloatingComplexToBoolean:
   5420   case CK_IntegralComplexToBoolean: {
   5421     bool BoolResult;
   5422     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
   5423       return false;
   5424     return Success(BoolResult, E);
   5425   }
   5426 
   5427   case CK_IntegralCast: {
   5428     if (!Visit(SubExpr))
   5429       return false;
   5430 
   5431     if (!Result.isInt()) {
   5432       // Allow casts of address-of-label differences if they are no-ops
   5433       // or narrowing.  (The narrowing case isn't actually guaranteed to
   5434       // be constant-evaluatable except in some narrow cases which are hard
   5435       // to detect here.  We let it through on the assumption the user knows
   5436       // what they are doing.)
   5437       if (Result.isAddrLabelDiff())
   5438         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
   5439       // Only allow casts of lvalues if they are lossless.
   5440       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
   5441     }
   5442 
   5443     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
   5444                                       Result.getInt()), E);
   5445   }
   5446 
   5447   case CK_PointerToIntegral: {
   5448     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
   5449 
   5450     LValue LV;
   5451     if (!EvaluatePointer(SubExpr, LV, Info))
   5452       return false;
   5453 
   5454     if (LV.getLValueBase()) {
   5455       // Only allow based lvalue casts if they are lossless.
   5456       // FIXME: Allow a larger integer size than the pointer size, and allow
   5457       // narrowing back down to pointer width in subsequent integral casts.
   5458       // FIXME: Check integer type's active bits, not its type size.
   5459       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
   5460         return Error(E);
   5461 
   5462       LV.Designator.setInvalid();
   5463       LV.moveInto(Result);
   5464       return true;
   5465     }
   5466 
   5467     APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
   5468                                          SrcType);
   5469     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
   5470   }
   5471 
   5472   case CK_IntegralComplexToReal: {
   5473     ComplexValue C;
   5474     if (!EvaluateComplex(SubExpr, C, Info))
   5475       return false;
   5476     return Success(C.getComplexIntReal(), E);
   5477   }
   5478 
   5479   case CK_FloatingToIntegral: {
   5480     APFloat F(0.0);
   5481     if (!EvaluateFloat(SubExpr, F, Info))
   5482       return false;
   5483 
   5484     APSInt Value;
   5485     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
   5486       return false;
   5487     return Success(Value, E);
   5488   }
   5489   }
   5490 
   5491   llvm_unreachable("unknown cast resulting in integral value");
   5492 }
   5493 
   5494 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
   5495   if (E->getSubExpr()->getType()->isAnyComplexType()) {
   5496     ComplexValue LV;
   5497     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
   5498       return false;
   5499     if (!LV.isComplexInt())
   5500       return Error(E);
   5501     return Success(LV.getComplexIntReal(), E);
   5502   }
   5503 
   5504   return Visit(E->getSubExpr());
   5505 }
   5506 
   5507 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
   5508   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
   5509     ComplexValue LV;
   5510     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
   5511       return false;
   5512     if (!LV.isComplexInt())
   5513       return Error(E);
   5514     return Success(LV.getComplexIntImag(), E);
   5515   }
   5516 
   5517   VisitIgnoredValue(E->getSubExpr());
   5518   return Success(0, E);
   5519 }
   5520 
   5521 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
   5522   return Success(E->getPackLength(), E);
   5523 }
   5524 
   5525 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
   5526   return Success(E->getValue(), E);
   5527 }
   5528 
   5529 //===----------------------------------------------------------------------===//
   5530 // Float Evaluation
   5531 //===----------------------------------------------------------------------===//
   5532 
   5533 namespace {
   5534 class FloatExprEvaluator
   5535   : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
   5536   APFloat &Result;
   5537 public:
   5538   FloatExprEvaluator(EvalInfo &info, APFloat &result)
   5539     : ExprEvaluatorBaseTy(info), Result(result) {}
   5540 
   5541   bool Success(const APValue &V, const Expr *e) {
   5542     Result = V.getFloat();
   5543     return true;
   5544   }
   5545 
   5546   bool ZeroInitialization(const Expr *E) {
   5547     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
   5548     return true;
   5549   }
   5550 
   5551   bool VisitCallExpr(const CallExpr *E);
   5552 
   5553   bool VisitUnaryOperator(const UnaryOperator *E);
   5554   bool VisitBinaryOperator(const BinaryOperator *E);
   5555   bool VisitFloatingLiteral(const FloatingLiteral *E);
   5556   bool VisitCastExpr(const CastExpr *E);
   5557 
   5558   bool VisitUnaryReal(const UnaryOperator *E);
   5559   bool VisitUnaryImag(const UnaryOperator *E);
   5560 
   5561   // FIXME: Missing: array subscript of vector, member of vector
   5562 };
   5563 } // end anonymous namespace
   5564 
   5565 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
   5566   assert(E->isRValue() && E->getType()->isRealFloatingType());
   5567   return FloatExprEvaluator(Info, Result).Visit(E);
   5568 }
   5569 
   5570 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
   5571                                   QualType ResultTy,
   5572                                   const Expr *Arg,
   5573                                   bool SNaN,
   5574                                   llvm::APFloat &Result) {
   5575   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
   5576   if (!S) return false;
   5577 
   5578   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
   5579 
   5580   llvm::APInt fill;
   5581 
   5582   // Treat empty strings as if they were zero.
   5583   if (S->getString().empty())
   5584     fill = llvm::APInt(32, 0);
   5585   else if (S->getString().getAsInteger(0, fill))
   5586     return false;
   5587 
   5588   if (SNaN)
   5589     Result = llvm::APFloat::getSNaN(Sem, false, &fill);
   5590   else
   5591     Result = llvm::APFloat::getQNaN(Sem, false, &fill);
   5592   return true;
   5593 }
   5594 
   5595 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
   5596   switch (E->isBuiltinCall()) {
   5597   default:
   5598     return ExprEvaluatorBaseTy::VisitCallExpr(E);
   5599 
   5600   case Builtin::BI__builtin_huge_val:
   5601   case Builtin::BI__builtin_huge_valf:
   5602   case Builtin::BI__builtin_huge_vall:
   5603   case Builtin::BI__builtin_inf:
   5604   case Builtin::BI__builtin_inff:
   5605   case Builtin::BI__builtin_infl: {
   5606     const llvm::fltSemantics &Sem =
   5607       Info.Ctx.getFloatTypeSemantics(E->getType());
   5608     Result = llvm::APFloat::getInf(Sem);
   5609     return true;
   5610   }
   5611 
   5612   case Builtin::BI__builtin_nans:
   5613   case Builtin::BI__builtin_nansf:
   5614   case Builtin::BI__builtin_nansl:
   5615     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
   5616                                true, Result))
   5617       return Error(E);
   5618     return true;
   5619 
   5620   case Builtin::BI__builtin_nan:
   5621   case Builtin::BI__builtin_nanf:
   5622   case Builtin::BI__builtin_nanl:
   5623     // If this is __builtin_nan() turn this into a nan, otherwise we
   5624     // can't constant fold it.
   5625     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
   5626                                false, Result))
   5627       return Error(E);
   5628     return true;
   5629 
   5630   case Builtin::BI__builtin_fabs:
   5631   case Builtin::BI__builtin_fabsf:
   5632   case Builtin::BI__builtin_fabsl:
   5633     if (!EvaluateFloat(E->getArg(0), Result, Info))
   5634       return false;
   5635 
   5636     if (Result.isNegative())
   5637       Result.changeSign();
   5638     return true;
   5639 
   5640   case Builtin::BI__builtin_copysign:
   5641   case Builtin::BI__builtin_copysignf:
   5642   case Builtin::BI__builtin_copysignl: {
   5643     APFloat RHS(0.);
   5644     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
   5645         !EvaluateFloat(E->getArg(1), RHS, Info))
   5646       return false;
   5647     Result.copySign(RHS);
   5648     return true;
   5649   }
   5650   }
   5651 }
   5652 
   5653 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
   5654   if (E->getSubExpr()->getType()->isAnyComplexType()) {
   5655     ComplexValue CV;
   5656     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
   5657       return false;
   5658     Result = CV.FloatReal;
   5659     return true;
   5660   }
   5661 
   5662   return Visit(E->getSubExpr());
   5663 }
   5664 
   5665 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
   5666   if (E->getSubExpr()->getType()->isAnyComplexType()) {
   5667     ComplexValue CV;
   5668     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
   5669       return false;
   5670     Result = CV.FloatImag;
   5671     return true;
   5672   }
   5673 
   5674   VisitIgnoredValue(E->getSubExpr());
   5675   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
   5676   Result = llvm::APFloat::getZero(Sem);
   5677   return true;
   5678 }
   5679 
   5680 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
   5681   switch (E->getOpcode()) {
   5682   default: return Error(E);
   5683   case UO_Plus:
   5684     return EvaluateFloat(E->getSubExpr(), Result, Info);
   5685   case UO_Minus:
   5686     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
   5687       return false;
   5688     Result.changeSign();
   5689     return true;
   5690   }
   5691 }
   5692 
   5693 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
   5694   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
   5695     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
   5696 
   5697   APFloat RHS(0.0);
   5698   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
   5699   if (!LHSOK && !Info.keepEvaluatingAfterFailure())
   5700     return false;
   5701   if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
   5702     return false;
   5703 
   5704   switch (E->getOpcode()) {
   5705   default: return Error(E);
   5706   case BO_Mul:
   5707     Result.multiply(RHS, APFloat::rmNearestTiesToEven);
   5708     break;
   5709   case BO_Add:
   5710     Result.add(RHS, APFloat::rmNearestTiesToEven);
   5711     break;
   5712   case BO_Sub:
   5713     Result.subtract(RHS, APFloat::rmNearestTiesToEven);
   5714     break;
   5715   case BO_Div:
   5716     Result.divide(RHS, APFloat::rmNearestTiesToEven);
   5717     break;
   5718   }
   5719 
   5720   if (Result.isInfinity() || Result.isNaN())
   5721     CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
   5722   return true;
   5723 }
   5724 
   5725 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
   5726   Result = E->getValue();
   5727   return true;
   5728 }
   5729 
   5730 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
   5731   const Expr* SubExpr = E->getSubExpr();
   5732 
   5733   switch (E->getCastKind()) {
   5734   default:
   5735     return ExprEvaluatorBaseTy::VisitCastExpr(E);
   5736 
   5737   case CK_IntegralToFloating: {
   5738     APSInt IntResult;
   5739     return EvaluateInteger(SubExpr, IntResult, Info) &&
   5740            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
   5741                                 E->getType(), Result);
   5742   }
   5743 
   5744   case CK_FloatingCast: {
   5745     if (!Visit(SubExpr))
   5746       return false;
   5747     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
   5748                                   Result);
   5749   }
   5750 
   5751   case CK_FloatingComplexToReal: {
   5752     ComplexValue V;
   5753     if (!EvaluateComplex(SubExpr, V, Info))
   5754       return false;
   5755     Result = V.getComplexFloatReal();
   5756     return true;
   5757   }
   5758   }
   5759 }
   5760 
   5761 //===----------------------------------------------------------------------===//
   5762 // Complex Evaluation (for float and integer)
   5763 //===----------------------------------------------------------------------===//
   5764 
   5765 namespace {
   5766 class ComplexExprEvaluator
   5767   : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
   5768   ComplexValue &Result;
   5769 
   5770 public:
   5771   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
   5772     : ExprEvaluatorBaseTy(info), Result(Result) {}
   5773 
   5774   bool Success(const APValue &V, const Expr *e) {
   5775     Result.setFrom(V);
   5776     return true;
   5777   }
   5778 
   5779   bool ZeroInitialization(const Expr *E);
   5780 
   5781   //===--------------------------------------------------------------------===//
   5782   //                            Visitor Methods
   5783   //===--------------------------------------------------------------------===//
   5784 
   5785   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
   5786   bool VisitCastExpr(const CastExpr *E);
   5787   bool VisitBinaryOperator(const BinaryOperator *E);
   5788   bool VisitUnaryOperator(const UnaryOperator *E);
   5789   bool VisitInitListExpr(const InitListExpr *E);
   5790 };
   5791 } // end anonymous namespace
   5792 
   5793 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
   5794                             EvalInfo &Info) {
   5795   assert(E->isRValue() && E->getType()->isAnyComplexType());
   5796   return ComplexExprEvaluator(Info, Result).Visit(E);
   5797 }
   5798 
   5799 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
   5800   QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
   5801   if (ElemTy->isRealFloatingType()) {
   5802     Result.makeComplexFloat();
   5803     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
   5804     Result.FloatReal = Zero;
   5805     Result.FloatImag = Zero;
   5806   } else {
   5807     Result.makeComplexInt();
   5808     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
   5809     Result.IntReal = Zero;
   5810     Result.IntImag = Zero;
   5811   }
   5812   return true;
   5813 }
   5814 
   5815 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
   5816   const Expr* SubExpr = E->getSubExpr();
   5817 
   5818   if (SubExpr->getType()->isRealFloatingType()) {
   5819     Result.makeComplexFloat();
   5820     APFloat &Imag = Result.FloatImag;
   5821     if (!EvaluateFloat(SubExpr, Imag, Info))
   5822       return false;
   5823 
   5824     Result.FloatReal = APFloat(Imag.getSemantics());
   5825     return true;
   5826   } else {
   5827     assert(SubExpr->getType()->isIntegerType() &&
   5828            "Unexpected imaginary literal.");
   5829 
   5830     Result.makeComplexInt();
   5831     APSInt &Imag = Result.IntImag;
   5832     if (!EvaluateInteger(SubExpr, Imag, Info))
   5833       return false;
   5834 
   5835     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
   5836     return true;
   5837   }
   5838 }
   5839 
   5840 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
   5841 
   5842   switch (E->getCastKind()) {
   5843   case CK_BitCast:
   5844   case CK_BaseToDerived:
   5845   case CK_DerivedToBase:
   5846   case CK_UncheckedDerivedToBase:
   5847   case CK_Dynamic:
   5848   case CK_ToUnion:
   5849   case CK_ArrayToPointerDecay:
   5850   case CK_FunctionToPointerDecay:
   5851   case CK_NullToPointer:
   5852   case CK_NullToMemberPointer:
   5853   case CK_BaseToDerivedMemberPointer:
   5854   case CK_DerivedToBaseMemberPointer:
   5855   case CK_MemberPointerToBoolean:
   5856   case CK_ReinterpretMemberPointer:
   5857   case CK_ConstructorConversion:
   5858   case CK_IntegralToPointer:
   5859   case CK_PointerToIntegral:
   5860   case CK_PointerToBoolean:
   5861   case CK_ToVoid:
   5862   case CK_VectorSplat:
   5863   case CK_IntegralCast:
   5864   case CK_IntegralToBoolean:
   5865   case CK_IntegralToFloating:
   5866   case CK_FloatingToIntegral:
   5867   case CK_FloatingToBoolean:
   5868   case CK_FloatingCast:
   5869   case CK_CPointerToObjCPointerCast:
   5870   case CK_BlockPointerToObjCPointerCast:
   5871   case CK_AnyPointerToBlockPointerCast:
   5872   case CK_ObjCObjectLValueCast:
   5873   case CK_FloatingComplexToReal:
   5874   case CK_FloatingComplexToBoolean:
   5875   case CK_IntegralComplexToReal:
   5876   case CK_IntegralComplexToBoolean:
   5877   case CK_ARCProduceObject:
   5878   case CK_ARCConsumeObject:
   5879   case CK_ARCReclaimReturnedObject:
   5880   case CK_ARCExtendBlockObject:
   5881   case CK_CopyAndAutoreleaseBlockObject:
   5882     llvm_unreachable("invalid cast kind for complex value");
   5883 
   5884   case CK_LValueToRValue:
   5885   case CK_AtomicToNonAtomic:
   5886   case CK_NonAtomicToAtomic:
   5887   case CK_NoOp:
   5888     return ExprEvaluatorBaseTy::VisitCastExpr(E);
   5889 
   5890   case CK_Dependent:
   5891   case CK_LValueBitCast:
   5892   case CK_UserDefinedConversion:
   5893     return Error(E);
   5894 
   5895   case CK_FloatingRealToComplex: {
   5896     APFloat &Real = Result.FloatReal;
   5897     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
   5898       return false;
   5899 
   5900     Result.makeComplexFloat();
   5901     Result.FloatImag = APFloat(Real.getSemantics());
   5902     return true;
   5903   }
   5904 
   5905   case CK_FloatingComplexCast: {
   5906     if (!Visit(E->getSubExpr()))
   5907       return false;
   5908 
   5909     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
   5910     QualType From
   5911       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
   5912 
   5913     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
   5914            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
   5915   }
   5916 
   5917   case CK_FloatingComplexToIntegralComplex: {
   5918     if (!Visit(E->getSubExpr()))
   5919       return false;
   5920 
   5921     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
   5922     QualType From
   5923       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
   5924     Result.makeComplexInt();
   5925     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
   5926                                 To, Result.IntReal) &&
   5927            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
   5928                                 To, Result.IntImag);
   5929   }
   5930 
   5931   case CK_IntegralRealToComplex: {
   5932     APSInt &Real = Result.IntReal;
   5933     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
   5934       return false;
   5935 
   5936     Result.makeComplexInt();
   5937     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
   5938     return true;
   5939   }
   5940 
   5941   case CK_IntegralComplexCast: {
   5942     if (!Visit(E->getSubExpr()))
   5943       return false;
   5944 
   5945     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
   5946     QualType From
   5947       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
   5948 
   5949     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
   5950     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
   5951     return true;
   5952   }
   5953 
   5954   case CK_IntegralComplexToFloatingComplex: {
   5955     if (!Visit(E->getSubExpr()))
   5956       return false;
   5957 
   5958     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
   5959     QualType From
   5960       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
   5961     Result.makeComplexFloat();
   5962     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
   5963                                 To, Result.FloatReal) &&
   5964            HandleIntToFloatCast(Info, E, From, Result.IntImag,
   5965                                 To, Result.FloatImag);
   5966   }
   5967   }
   5968 
   5969   llvm_unreachable("unknown cast resulting in complex value");
   5970 }
   5971 
   5972 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
   5973   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
   5974     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
   5975 
   5976   bool LHSOK = Visit(E->getLHS());
   5977   if (!LHSOK && !Info.keepEvaluatingAfterFailure())
   5978     return false;
   5979 
   5980   ComplexValue RHS;
   5981   if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
   5982     return false;
   5983 
   5984   assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
   5985          "Invalid operands to binary operator.");
   5986   switch (E->getOpcode()) {
   5987   default: return Error(E);
   5988   case BO_Add:
   5989     if (Result.isComplexFloat()) {
   5990       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
   5991                                        APFloat::rmNearestTiesToEven);
   5992       Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
   5993                                        APFloat::rmNearestTiesToEven);
   5994     } else {
   5995       Result.getComplexIntReal() += RHS.getComplexIntReal();
   5996       Result.getComplexIntImag() += RHS.getComplexIntImag();
   5997     }
   5998     break;
   5999   case BO_Sub:
   6000     if (Result.isComplexFloat()) {
   6001       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
   6002                                             APFloat::rmNearestTiesToEven);
   6003       Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
   6004                                             APFloat::rmNearestTiesToEven);
   6005     } else {
   6006       Result.getComplexIntReal() -= RHS.getComplexIntReal();
   6007       Result.getComplexIntImag() -= RHS.getComplexIntImag();
   6008     }
   6009     break;
   6010   case BO_Mul:
   6011     if (Result.isComplexFloat()) {
   6012       ComplexValue LHS = Result;
   6013       APFloat &LHS_r = LHS.getComplexFloatReal();
   6014       APFloat &LHS_i = LHS.getComplexFloatImag();
   6015       APFloat &RHS_r = RHS.getComplexFloatReal();
   6016       APFloat &RHS_i = RHS.getComplexFloatImag();
   6017 
   6018       APFloat Tmp = LHS_r;
   6019       Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
   6020       Result.getComplexFloatReal() = Tmp;
   6021       Tmp = LHS_i;
   6022       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
   6023       Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
   6024 
   6025       Tmp = LHS_r;
   6026       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
   6027       Result.getComplexFloatImag() = Tmp;
   6028       Tmp = LHS_i;
   6029       Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
   6030       Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
   6031     } else {
   6032       ComplexValue LHS = Result;
   6033       Result.getComplexIntReal() =
   6034         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
   6035          LHS.getComplexIntImag() * RHS.getComplexIntImag());
   6036       Result.getComplexIntImag() =
   6037         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
   6038          LHS.getComplexIntImag() * RHS.getComplexIntReal());
   6039     }
   6040     break;
   6041   case BO_Div:
   6042     if (Result.isComplexFloat()) {
   6043       ComplexValue LHS = Result;
   6044       APFloat &LHS_r = LHS.getComplexFloatReal();
   6045       APFloat &LHS_i = LHS.getComplexFloatImag();
   6046       APFloat &RHS_r = RHS.getComplexFloatReal();
   6047       APFloat &RHS_i = RHS.getComplexFloatImag();
   6048       APFloat &Res_r = Result.getComplexFloatReal();
   6049       APFloat &Res_i = Result.getComplexFloatImag();
   6050 
   6051       APFloat Den = RHS_r;
   6052       Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
   6053       APFloat Tmp = RHS_i;
   6054       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
   6055       Den.add(Tmp, APFloat::rmNearestTiesToEven);
   6056 
   6057       Res_r = LHS_r;
   6058       Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
   6059       Tmp = LHS_i;
   6060       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
   6061       Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
   6062       Res_r.divide(Den, APFloat::rmNearestTiesToEven);
   6063 
   6064       Res_i = LHS_i;
   6065       Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
   6066       Tmp = LHS_r;
   6067       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
   6068       Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
   6069       Res_i.divide(Den, APFloat::rmNearestTiesToEven);
   6070     } else {
   6071       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
   6072         return Error(E, diag::note_expr_divide_by_zero);
   6073 
   6074       ComplexValue LHS = Result;
   6075       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
   6076         RHS.getComplexIntImag() * RHS.getComplexIntImag();
   6077       Result.getComplexIntReal() =
   6078         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
   6079          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
   6080       Result.getComplexIntImag() =
   6081         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
   6082          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
   6083     }
   6084     break;
   6085   }
   6086 
   6087   return true;
   6088 }
   6089 
   6090 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
   6091   // Get the operand value into 'Result'.
   6092   if (!Visit(E->getSubExpr()))
   6093     return false;
   6094 
   6095   switch (E->getOpcode()) {
   6096   default:
   6097     return Error(E);
   6098   case UO_Extension:
   6099     return true;
   6100   case UO_Plus:
   6101     // The result is always just the subexpr.
   6102     return true;
   6103   case UO_Minus:
   6104     if (Result.isComplexFloat()) {
   6105       Result.getComplexFloatReal().changeSign();
   6106       Result.getComplexFloatImag().changeSign();
   6107     }
   6108     else {
   6109       Result.getComplexIntReal() = -Result.getComplexIntReal();
   6110       Result.getComplexIntImag() = -Result.getComplexIntImag();
   6111     }
   6112     return true;
   6113   case UO_Not:
   6114     if (Result.isComplexFloat())
   6115       Result.getComplexFloatImag().changeSign();
   6116     else
   6117       Result.getComplexIntImag() = -Result.getComplexIntImag();
   6118     return true;
   6119   }
   6120 }
   6121 
   6122 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
   6123   if (E->getNumInits() == 2) {
   6124     if (E->getType()->isComplexType()) {
   6125       Result.makeComplexFloat();
   6126       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
   6127         return false;
   6128       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
   6129         return false;
   6130     } else {
   6131       Result.makeComplexInt();
   6132       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
   6133         return false;
   6134       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
   6135         return false;
   6136     }
   6137     return true;
   6138   }
   6139   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
   6140 }
   6141 
   6142 //===----------------------------------------------------------------------===//
   6143 // Void expression evaluation, primarily for a cast to void on the LHS of a
   6144 // comma operator
   6145 //===----------------------------------------------------------------------===//
   6146 
   6147 namespace {
   6148 class VoidExprEvaluator
   6149   : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
   6150 public:
   6151   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
   6152 
   6153   bool Success(const APValue &V, const Expr *e) { return true; }
   6154 
   6155   bool VisitCastExpr(const CastExpr *E) {
   6156     switch (E->getCastKind()) {
   6157     default:
   6158       return ExprEvaluatorBaseTy::VisitCastExpr(E);
   6159     case CK_ToVoid:
   6160       VisitIgnoredValue(E->getSubExpr());
   6161       return true;
   6162     }
   6163   }
   6164 };
   6165 } // end anonymous namespace
   6166 
   6167 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
   6168   assert(E->isRValue() && E->getType()->isVoidType());
   6169   return VoidExprEvaluator(Info).Visit(E);
   6170 }
   6171 
   6172 //===----------------------------------------------------------------------===//
   6173 // Top level Expr::EvaluateAsRValue method.
   6174 //===----------------------------------------------------------------------===//
   6175 
   6176 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
   6177   // In C, function designators are not lvalues, but we evaluate them as if they
   6178   // are.
   6179   if (E->isGLValue() || E->getType()->isFunctionType()) {
   6180     LValue LV;
   6181     if (!EvaluateLValue(E, LV, Info))
   6182       return false;
   6183     LV.moveInto(Result);
   6184   } else if (E->getType()->isVectorType()) {
   6185     if (!EvaluateVector(E, Result, Info))
   6186       return false;
   6187   } else if (E->getType()->isIntegralOrEnumerationType()) {
   6188     if (!IntExprEvaluator(Info, Result).Visit(E))
   6189       return false;
   6190   } else if (E->getType()->hasPointerRepresentation()) {
   6191     LValue LV;
   6192     if (!EvaluatePointer(E, LV, Info))
   6193       return false;
   6194     LV.moveInto(Result);
   6195   } else if (E->getType()->isRealFloatingType()) {
   6196     llvm::APFloat F(0.0);
   6197     if (!EvaluateFloat(E, F, Info))
   6198       return false;
   6199     Result = APValue(F);
   6200   } else if (E->getType()->isAnyComplexType()) {
   6201     ComplexValue C;
   6202     if (!EvaluateComplex(E, C, Info))
   6203       return false;
   6204     C.moveInto(Result);
   6205   } else if (E->getType()->isMemberPointerType()) {
   6206     MemberPtr P;
   6207     if (!EvaluateMemberPointer(E, P, Info))
   6208       return false;
   6209     P.moveInto(Result);
   6210     return true;
   6211   } else if (E->getType()->isArrayType()) {
   6212     LValue LV;
   6213     LV.set(E, Info.CurrentCall->Index);
   6214     if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
   6215       return false;
   6216     Result = Info.CurrentCall->Temporaries[E];
   6217   } else if (E->getType()->isRecordType()) {
   6218     LValue LV;
   6219     LV.set(E, Info.CurrentCall->Index);
   6220     if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
   6221       return false;
   6222     Result = Info.CurrentCall->Temporaries[E];
   6223   } else if (E->getType()->isVoidType()) {
   6224     if (Info.getLangOpts().CPlusPlus0x)
   6225       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
   6226         << E->getType();
   6227     else
   6228       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
   6229     if (!EvaluateVoid(E, Info))
   6230       return false;
   6231   } else if (Info.getLangOpts().CPlusPlus0x) {
   6232     Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
   6233     return false;
   6234   } else {
   6235     Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
   6236     return false;
   6237   }
   6238 
   6239   return true;
   6240 }
   6241 
   6242 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
   6243 /// cases, the in-place evaluation is essential, since later initializers for
   6244 /// an object can indirectly refer to subobjects which were initialized earlier.
   6245 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
   6246                             const Expr *E, CheckConstantExpressionKind CCEK,
   6247                             bool AllowNonLiteralTypes) {
   6248   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
   6249     return false;
   6250 
   6251   if (E->isRValue()) {
   6252     // Evaluate arrays and record types in-place, so that later initializers can
   6253     // refer to earlier-initialized members of the object.
   6254     if (E->getType()->isArrayType())
   6255       return EvaluateArray(E, This, Result, Info);
   6256     else if (E->getType()->isRecordType())
   6257       return EvaluateRecord(E, This, Result, Info);
   6258   }
   6259 
   6260   // For any other type, in-place evaluation is unimportant.
   6261   return Evaluate(Result, Info, E);
   6262 }
   6263 
   6264 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
   6265 /// lvalue-to-rvalue cast if it is an lvalue.
   6266 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
   6267   if (!CheckLiteralType(Info, E))
   6268     return false;
   6269 
   6270   if (!::Evaluate(Result, Info, E))
   6271     return false;
   6272 
   6273   if (E->isGLValue()) {
   6274     LValue LV;
   6275     LV.setFrom(Info.Ctx, Result);
   6276     if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
   6277       return false;
   6278   }
   6279 
   6280   // Check this core constant expression is a constant expression.
   6281   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
   6282 }
   6283 
   6284 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
   6285 /// any crazy technique (that has nothing to do with language standards) that
   6286 /// we want to.  If this function returns true, it returns the folded constant
   6287 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
   6288 /// will be applied to the result.
   6289 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
   6290   // Fast-path evaluations of integer literals, since we sometimes see files
   6291   // containing vast quantities of these.
   6292   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
   6293     Result.Val = APValue(APSInt(L->getValue(),
   6294                                 L->getType()->isUnsignedIntegerType()));
   6295     return true;
   6296   }
   6297 
   6298   // FIXME: Evaluating values of large array and record types can cause
   6299   // performance problems. Only do so in C++11 for now.
   6300   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
   6301       !Ctx.getLangOpts().CPlusPlus0x)
   6302     return false;
   6303 
   6304   EvalInfo Info(Ctx, Result);
   6305   return ::EvaluateAsRValue(Info, this, Result.Val);
   6306 }
   6307 
   6308 bool Expr::EvaluateAsBooleanCondition(bool &Result,
   6309                                       const ASTContext &Ctx) const {
   6310   EvalResult Scratch;
   6311   return EvaluateAsRValue(Scratch, Ctx) &&
   6312          HandleConversionToBool(Scratch.Val, Result);
   6313 }
   6314 
   6315 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
   6316                          SideEffectsKind AllowSideEffects) const {
   6317   if (!getType()->isIntegralOrEnumerationType())
   6318     return false;
   6319 
   6320   EvalResult ExprResult;
   6321   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
   6322       (!AllowSideEffects && ExprResult.HasSideEffects))
   6323     return false;
   6324 
   6325   Result = ExprResult.Val.getInt();
   6326   return true;
   6327 }
   6328 
   6329 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
   6330   EvalInfo Info(Ctx, Result);
   6331 
   6332   LValue LV;
   6333   if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
   6334       !CheckLValueConstantExpression(Info, getExprLoc(),
   6335                                      Ctx.getLValueReferenceType(getType()), LV))
   6336     return false;
   6337 
   6338   LV.moveInto(Result.Val);
   6339   return true;
   6340 }
   6341 
   6342 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
   6343                                  const VarDecl *VD,
   6344                       llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
   6345   // FIXME: Evaluating initializers for large array and record types can cause
   6346   // performance problems. Only do so in C++11 for now.
   6347   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
   6348       !Ctx.getLangOpts().CPlusPlus0x)
   6349     return false;
   6350 
   6351   Expr::EvalStatus EStatus;
   6352   EStatus.Diag = &Notes;
   6353 
   6354   EvalInfo InitInfo(Ctx, EStatus);
   6355   InitInfo.setEvaluatingDecl(VD, Value);
   6356 
   6357   LValue LVal;
   6358   LVal.set(VD);
   6359 
   6360   // C++11 [basic.start.init]p2:
   6361   //  Variables with static storage duration or thread storage duration shall be
   6362   //  zero-initialized before any other initialization takes place.
   6363   // This behavior is not present in C.
   6364   if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
   6365       !VD->getType()->isReferenceType()) {
   6366     ImplicitValueInitExpr VIE(VD->getType());
   6367     if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
   6368                          /*AllowNonLiteralTypes=*/true))
   6369       return false;
   6370   }
   6371 
   6372   if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
   6373                          /*AllowNonLiteralTypes=*/true) ||
   6374       EStatus.HasSideEffects)
   6375     return false;
   6376 
   6377   return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
   6378                                  Value);
   6379 }
   6380 
   6381 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
   6382 /// constant folded, but discard the result.
   6383 bool Expr::isEvaluatable(const ASTContext &Ctx) const {
   6384   EvalResult Result;
   6385   return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
   6386 }
   6387 
   6388 bool Expr::HasSideEffects(const ASTContext &Ctx) const {
   6389   return HasSideEffect(Ctx).Visit(this);
   6390 }
   6391 
   6392 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
   6393   EvalResult EvalResult;
   6394   bool Result = EvaluateAsRValue(EvalResult, Ctx);
   6395   (void)Result;
   6396   assert(Result && "Could not evaluate expression");
   6397   assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
   6398 
   6399   return EvalResult.Val.getInt();
   6400 }
   6401 
   6402  bool Expr::EvalResult::isGlobalLValue() const {
   6403    assert(Val.isLValue());
   6404    return IsGlobalLValue(Val.getLValueBase());
   6405  }
   6406 
   6407 
   6408 /// isIntegerConstantExpr - this recursive routine will test if an expression is
   6409 /// an integer constant expression.
   6410 
   6411 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
   6412 /// comma, etc
   6413 ///
   6414 /// FIXME: Handle offsetof.  Two things to do:  Handle GCC's __builtin_offsetof
   6415 /// to support gcc 4.0+  and handle the idiom GCC recognizes with a null pointer
   6416 /// cast+dereference.
   6417 
   6418 // CheckICE - This function does the fundamental ICE checking: the returned
   6419 // ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
   6420 // Note that to reduce code duplication, this helper does no evaluation
   6421 // itself; the caller checks whether the expression is evaluatable, and
   6422 // in the rare cases where CheckICE actually cares about the evaluated
   6423 // value, it calls into Evalute.
   6424 //
   6425 // Meanings of Val:
   6426 // 0: This expression is an ICE.
   6427 // 1: This expression is not an ICE, but if it isn't evaluated, it's
   6428 //    a legal subexpression for an ICE. This return value is used to handle
   6429 //    the comma operator in C99 mode.
   6430 // 2: This expression is not an ICE, and is not a legal subexpression for one.
   6431 
   6432 namespace {
   6433 
   6434 struct ICEDiag {
   6435   unsigned Val;
   6436   SourceLocation Loc;
   6437 
   6438   public:
   6439   ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
   6440   ICEDiag() : Val(0) {}
   6441 };
   6442 
   6443 }
   6444 
   6445 static ICEDiag NoDiag() { return ICEDiag(); }
   6446 
   6447 static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
   6448   Expr::EvalResult EVResult;
   6449   if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
   6450       !EVResult.Val.isInt()) {
   6451     return ICEDiag(2, E->getLocStart());
   6452   }
   6453   return NoDiag();
   6454 }
   6455 
   6456 static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
   6457   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
   6458   if (!E->getType()->isIntegralOrEnumerationType()) {
   6459     return ICEDiag(2, E->getLocStart());
   6460   }
   6461 
   6462   switch (E->getStmtClass()) {
   6463 #define ABSTRACT_STMT(Node)
   6464 #define STMT(Node, Base) case Expr::Node##Class:
   6465 #define EXPR(Node, Base)
   6466 #include "clang/AST/StmtNodes.inc"
   6467   case Expr::PredefinedExprClass:
   6468   case Expr::FloatingLiteralClass:
   6469   case Expr::ImaginaryLiteralClass:
   6470   case Expr::StringLiteralClass:
   6471   case Expr::ArraySubscriptExprClass:
   6472   case Expr::MemberExprClass:
   6473   case Expr::CompoundAssignOperatorClass:
   6474   case Expr::CompoundLiteralExprClass:
   6475   case Expr::ExtVectorElementExprClass:
   6476   case Expr::DesignatedInitExprClass:
   6477   case Expr::ImplicitValueInitExprClass:
   6478   case Expr::ParenListExprClass:
   6479   case Expr::VAArgExprClass:
   6480   case Expr::AddrLabelExprClass:
   6481   case Expr::StmtExprClass:
   6482   case Expr::CXXMemberCallExprClass:
   6483   case Expr::CUDAKernelCallExprClass:
   6484   case Expr::CXXDynamicCastExprClass:
   6485   case Expr::CXXTypeidExprClass:
   6486   case Expr::CXXUuidofExprClass:
   6487   case Expr::CXXNullPtrLiteralExprClass:
   6488   case Expr::UserDefinedLiteralClass:
   6489   case Expr::CXXThisExprClass:
   6490   case Expr::CXXThrowExprClass:
   6491   case Expr::CXXNewExprClass:
   6492   case Expr::CXXDeleteExprClass:
   6493   case Expr::CXXPseudoDestructorExprClass:
   6494   case Expr::UnresolvedLookupExprClass:
   6495   case Expr::DependentScopeDeclRefExprClass:
   6496   case Expr::CXXConstructExprClass:
   6497   case Expr::CXXBindTemporaryExprClass:
   6498   case Expr::ExprWithCleanupsClass:
   6499   case Expr::CXXTemporaryObjectExprClass:
   6500   case Expr::CXXUnresolvedConstructExprClass:
   6501   case Expr::CXXDependentScopeMemberExprClass:
   6502   case Expr::UnresolvedMemberExprClass:
   6503   case Expr::ObjCStringLiteralClass:
   6504   case Expr::ObjCBoxedExprClass:
   6505   case Expr::ObjCArrayLiteralClass:
   6506   case Expr::ObjCDictionaryLiteralClass:
   6507   case Expr::ObjCEncodeExprClass:
   6508   case Expr::ObjCMessageExprClass:
   6509   case Expr::ObjCSelectorExprClass:
   6510   case Expr::ObjCProtocolExprClass:
   6511   case Expr::ObjCIvarRefExprClass:
   6512   case Expr::ObjCPropertyRefExprClass:
   6513   case Expr::ObjCSubscriptRefExprClass:
   6514   case Expr::ObjCIsaExprClass:
   6515   case Expr::ShuffleVectorExprClass:
   6516   case Expr::BlockExprClass:
   6517   case Expr::NoStmtClass:
   6518   case Expr::OpaqueValueExprClass:
   6519   case Expr::PackExpansionExprClass:
   6520   case Expr::SubstNonTypeTemplateParmPackExprClass:
   6521   case Expr::AsTypeExprClass:
   6522   case Expr::ObjCIndirectCopyRestoreExprClass:
   6523   case Expr::MaterializeTemporaryExprClass:
   6524   case Expr::PseudoObjectExprClass:
   6525   case Expr::AtomicExprClass:
   6526   case Expr::InitListExprClass:
   6527   case Expr::LambdaExprClass:
   6528     return ICEDiag(2, E->getLocStart());
   6529 
   6530   case Expr::SizeOfPackExprClass:
   6531   case Expr::GNUNullExprClass:
   6532     // GCC considers the GNU __null value to be an integral constant expression.
   6533     return NoDiag();
   6534 
   6535   case Expr::SubstNonTypeTemplateParmExprClass:
   6536     return
   6537       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
   6538 
   6539   case Expr::ParenExprClass:
   6540     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
   6541   case Expr::GenericSelectionExprClass:
   6542     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
   6543   case Expr::IntegerLiteralClass:
   6544   case Expr::CharacterLiteralClass:
   6545   case Expr::ObjCBoolLiteralExprClass:
   6546   case Expr::CXXBoolLiteralExprClass:
   6547   case Expr::CXXScalarValueInitExprClass:
   6548   case Expr::UnaryTypeTraitExprClass:
   6549   case Expr::BinaryTypeTraitExprClass:
   6550   case Expr::TypeTraitExprClass:
   6551   case Expr::ArrayTypeTraitExprClass:
   6552   case Expr::ExpressionTraitExprClass:
   6553   case Expr::CXXNoexceptExprClass:
   6554     return NoDiag();
   6555   case Expr::CallExprClass:
   6556   case Expr::CXXOperatorCallExprClass: {
   6557     // C99 6.6/3 allows function calls within unevaluated subexpressions of
   6558     // constant expressions, but they can never be ICEs because an ICE cannot
   6559     // contain an operand of (pointer to) function type.
   6560     const CallExpr *CE = cast<CallExpr>(E);
   6561     if (CE->isBuiltinCall())
   6562       return CheckEvalInICE(E, Ctx);
   6563     return ICEDiag(2, E->getLocStart());
   6564   }
   6565   case Expr::DeclRefExprClass: {
   6566     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
   6567       return NoDiag();
   6568     const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
   6569     if (Ctx.getLangOpts().CPlusPlus &&
   6570         D && IsConstNonVolatile(D->getType())) {
   6571       // Parameter variables are never constants.  Without this check,
   6572       // getAnyInitializer() can find a default argument, which leads
   6573       // to chaos.
   6574       if (isa<ParmVarDecl>(D))
   6575         return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
   6576 
   6577       // C++ 7.1.5.1p2
   6578       //   A variable of non-volatile const-qualified integral or enumeration
   6579       //   type initialized by an ICE can be used in ICEs.
   6580       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
   6581         if (!Dcl->getType()->isIntegralOrEnumerationType())
   6582           return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
   6583 
   6584         const VarDecl *VD;
   6585         // Look for a declaration of this variable that has an initializer, and
   6586         // check whether it is an ICE.
   6587         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
   6588           return NoDiag();
   6589         else
   6590           return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
   6591       }
   6592     }
   6593     return ICEDiag(2, E->getLocStart());
   6594   }
   6595   case Expr::UnaryOperatorClass: {
   6596     const UnaryOperator *Exp = cast<UnaryOperator>(E);
   6597     switch (Exp->getOpcode()) {
   6598     case UO_PostInc:
   6599     case UO_PostDec:
   6600     case UO_PreInc:
   6601     case UO_PreDec:
   6602     case UO_AddrOf:
   6603     case UO_Deref:
   6604       // C99 6.6/3 allows increment and decrement within unevaluated
   6605       // subexpressions of constant expressions, but they can never be ICEs
   6606       // because an ICE cannot contain an lvalue operand.
   6607       return ICEDiag(2, E->getLocStart());
   6608     case UO_Extension:
   6609     case UO_LNot:
   6610     case UO_Plus:
   6611     case UO_Minus:
   6612     case UO_Not:
   6613     case UO_Real:
   6614     case UO_Imag:
   6615       return CheckICE(Exp->getSubExpr(), Ctx);
   6616     }
   6617 
   6618     // OffsetOf falls through here.
   6619   }
   6620   case Expr::OffsetOfExprClass: {
   6621       // Note that per C99, offsetof must be an ICE. And AFAIK, using
   6622       // EvaluateAsRValue matches the proposed gcc behavior for cases like
   6623       // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
   6624       // compliance: we should warn earlier for offsetof expressions with
   6625       // array subscripts that aren't ICEs, and if the array subscripts
   6626       // are ICEs, the value of the offsetof must be an integer constant.
   6627       return CheckEvalInICE(E, Ctx);
   6628   }
   6629   case Expr::UnaryExprOrTypeTraitExprClass: {
   6630     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
   6631     if ((Exp->getKind() ==  UETT_SizeOf) &&
   6632         Exp->getTypeOfArgument()->isVariableArrayType())
   6633       return ICEDiag(2, E->getLocStart());
   6634     return NoDiag();
   6635   }
   6636   case Expr::BinaryOperatorClass: {
   6637     const BinaryOperator *Exp = cast<BinaryOperator>(E);
   6638     switch (Exp->getOpcode()) {
   6639     case BO_PtrMemD:
   6640     case BO_PtrMemI:
   6641     case BO_Assign:
   6642     case BO_MulAssign:
   6643     case BO_DivAssign:
   6644     case BO_RemAssign:
   6645     case BO_AddAssign:
   6646     case BO_SubAssign:
   6647     case BO_ShlAssign:
   6648     case BO_ShrAssign:
   6649     case BO_AndAssign:
   6650     case BO_XorAssign:
   6651     case BO_OrAssign:
   6652       // C99 6.6/3 allows assignments within unevaluated subexpressions of
   6653       // constant expressions, but they can never be ICEs because an ICE cannot
   6654       // contain an lvalue operand.
   6655       return ICEDiag(2, E->getLocStart());
   6656 
   6657     case BO_Mul:
   6658     case BO_Div:
   6659     case BO_Rem:
   6660     case BO_Add:
   6661     case BO_Sub:
   6662     case BO_Shl:
   6663     case BO_Shr:
   6664     case BO_LT:
   6665     case BO_GT:
   6666     case BO_LE:
   6667     case BO_GE:
   6668     case BO_EQ:
   6669     case BO_NE:
   6670     case BO_And:
   6671     case BO_Xor:
   6672     case BO_Or:
   6673     case BO_Comma: {
   6674       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
   6675       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
   6676       if (Exp->getOpcode() == BO_Div ||
   6677           Exp->getOpcode() == BO_Rem) {
   6678         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
   6679         // we don't evaluate one.
   6680         if (LHSResult.Val == 0 && RHSResult.Val == 0) {
   6681           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
   6682           if (REval == 0)
   6683             return ICEDiag(1, E->getLocStart());
   6684           if (REval.isSigned() && REval.isAllOnesValue()) {
   6685             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
   6686             if (LEval.isMinSignedValue())
   6687               return ICEDiag(1, E->getLocStart());
   6688           }
   6689         }
   6690       }
   6691       if (Exp->getOpcode() == BO_Comma) {
   6692         if (Ctx.getLangOpts().C99) {
   6693           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
   6694           // if it isn't evaluated.
   6695           if (LHSResult.Val == 0 && RHSResult.Val == 0)
   6696             return ICEDiag(1, E->getLocStart());
   6697         } else {
   6698           // In both C89 and C++, commas in ICEs are illegal.
   6699           return ICEDiag(2, E->getLocStart());
   6700         }
   6701       }
   6702       if (LHSResult.Val >= RHSResult.Val)
   6703         return LHSResult;
   6704       return RHSResult;
   6705     }
   6706     case BO_LAnd:
   6707     case BO_LOr: {
   6708       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
   6709       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
   6710       if (LHSResult.Val == 0 && RHSResult.Val == 1) {
   6711         // Rare case where the RHS has a comma "side-effect"; we need
   6712         // to actually check the condition to see whether the side
   6713         // with the comma is evaluated.
   6714         if ((Exp->getOpcode() == BO_LAnd) !=
   6715             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
   6716           return RHSResult;
   6717         return NoDiag();
   6718       }
   6719 
   6720       if (LHSResult.Val >= RHSResult.Val)
   6721         return LHSResult;
   6722       return RHSResult;
   6723     }
   6724     }
   6725   }
   6726   case Expr::ImplicitCastExprClass:
   6727   case Expr::CStyleCastExprClass:
   6728   case Expr::CXXFunctionalCastExprClass:
   6729   case Expr::CXXStaticCastExprClass:
   6730   case Expr::CXXReinterpretCastExprClass:
   6731   case Expr::CXXConstCastExprClass:
   6732   case Expr::ObjCBridgedCastExprClass: {
   6733     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
   6734     if (isa<ExplicitCastExpr>(E)) {
   6735       if (const FloatingLiteral *FL
   6736             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
   6737         unsigned DestWidth = Ctx.getIntWidth(E->getType());
   6738         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
   6739         APSInt IgnoredVal(DestWidth, !DestSigned);
   6740         bool Ignored;
   6741         // If the value does not fit in the destination type, the behavior is
   6742         // undefined, so we are not required to treat it as a constant
   6743         // expression.
   6744         if (FL->getValue().convertToInteger(IgnoredVal,
   6745                                             llvm::APFloat::rmTowardZero,
   6746                                             &Ignored) & APFloat::opInvalidOp)
   6747           return ICEDiag(2, E->getLocStart());
   6748         return NoDiag();
   6749       }
   6750     }
   6751     switch (cast<CastExpr>(E)->getCastKind()) {
   6752     case CK_LValueToRValue:
   6753     case CK_AtomicToNonAtomic:
   6754     case CK_NonAtomicToAtomic:
   6755     case CK_NoOp:
   6756     case CK_IntegralToBoolean:
   6757     case CK_IntegralCast:
   6758       return CheckICE(SubExpr, Ctx);
   6759     default:
   6760       return ICEDiag(2, E->getLocStart());
   6761     }
   6762   }
   6763   case Expr::BinaryConditionalOperatorClass: {
   6764     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
   6765     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
   6766     if (CommonResult.Val == 2) return CommonResult;
   6767     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
   6768     if (FalseResult.Val == 2) return FalseResult;
   6769     if (CommonResult.Val == 1) return CommonResult;
   6770     if (FalseResult.Val == 1 &&
   6771         Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
   6772     return FalseResult;
   6773   }
   6774   case Expr::ConditionalOperatorClass: {
   6775     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
   6776     // If the condition (ignoring parens) is a __builtin_constant_p call,
   6777     // then only the true side is actually considered in an integer constant
   6778     // expression, and it is fully evaluated.  This is an important GNU
   6779     // extension.  See GCC PR38377 for discussion.
   6780     if (const CallExpr *CallCE
   6781         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
   6782       if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
   6783         return CheckEvalInICE(E, Ctx);
   6784     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
   6785     if (CondResult.Val == 2)
   6786       return CondResult;
   6787 
   6788     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
   6789     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
   6790 
   6791     if (TrueResult.Val == 2)
   6792       return TrueResult;
   6793     if (FalseResult.Val == 2)
   6794       return FalseResult;
   6795     if (CondResult.Val == 1)
   6796       return CondResult;
   6797     if (TrueResult.Val == 0 && FalseResult.Val == 0)
   6798       return NoDiag();
   6799     // Rare case where the diagnostics depend on which side is evaluated
   6800     // Note that if we get here, CondResult is 0, and at least one of
   6801     // TrueResult and FalseResult is non-zero.
   6802     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
   6803       return FalseResult;
   6804     }
   6805     return TrueResult;
   6806   }
   6807   case Expr::CXXDefaultArgExprClass:
   6808     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
   6809   case Expr::ChooseExprClass: {
   6810     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
   6811   }
   6812   }
   6813 
   6814   llvm_unreachable("Invalid StmtClass!");
   6815 }
   6816 
   6817 /// Evaluate an expression as a C++11 integral constant expression.
   6818 static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
   6819                                                     const Expr *E,
   6820                                                     llvm::APSInt *Value,
   6821                                                     SourceLocation *Loc) {
   6822   if (!E->getType()->isIntegralOrEnumerationType()) {
   6823     if (Loc) *Loc = E->getExprLoc();
   6824     return false;
   6825   }
   6826 
   6827   APValue Result;
   6828   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
   6829     return false;
   6830 
   6831   assert(Result.isInt() && "pointer cast to int is not an ICE");
   6832   if (Value) *Value = Result.getInt();
   6833   return true;
   6834 }
   6835 
   6836 bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
   6837   if (Ctx.getLangOpts().CPlusPlus0x)
   6838     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
   6839 
   6840   ICEDiag d = CheckICE(this, Ctx);
   6841   if (d.Val != 0) {
   6842     if (Loc) *Loc = d.Loc;
   6843     return false;
   6844   }
   6845   return true;
   6846 }
   6847 
   6848 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
   6849                                  SourceLocation *Loc, bool isEvaluated) const {
   6850   if (Ctx.getLangOpts().CPlusPlus0x)
   6851     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
   6852 
   6853   if (!isIntegerConstantExpr(Ctx, Loc))
   6854     return false;
   6855   if (!EvaluateAsInt(Value, Ctx))
   6856     llvm_unreachable("ICE cannot be evaluated!");
   6857   return true;
   6858 }
   6859 
   6860 bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
   6861   return CheckICE(this, Ctx).Val == 0;
   6862 }
   6863 
   6864 bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
   6865                                SourceLocation *Loc) const {
   6866   // We support this checking in C++98 mode in order to diagnose compatibility
   6867   // issues.
   6868   assert(Ctx.getLangOpts().CPlusPlus);
   6869 
   6870   // Build evaluation settings.
   6871   Expr::EvalStatus Status;
   6872   llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
   6873   Status.Diag = &Diags;
   6874   EvalInfo Info(Ctx, Status);
   6875 
   6876   APValue Scratch;
   6877   bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
   6878 
   6879   if (!Diags.empty()) {
   6880     IsConstExpr = false;
   6881     if (Loc) *Loc = Diags[0].first;
   6882   } else if (!IsConstExpr) {
   6883     // FIXME: This shouldn't happen.
   6884     if (Loc) *Loc = getExprLoc();
   6885   }
   6886 
   6887   return IsConstExpr;
   6888 }
   6889 
   6890 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
   6891                                    llvm::SmallVectorImpl<
   6892                                      PartialDiagnosticAt> &Diags) {
   6893   // FIXME: It would be useful to check constexpr function templates, but at the
   6894   // moment the constant expression evaluator cannot cope with the non-rigorous
   6895   // ASTs which we build for dependent expressions.
   6896   if (FD->isDependentContext())
   6897     return true;
   6898 
   6899   Expr::EvalStatus Status;
   6900   Status.Diag = &Diags;
   6901 
   6902   EvalInfo Info(FD->getASTContext(), Status);
   6903   Info.CheckingPotentialConstantExpression = true;
   6904 
   6905   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
   6906   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
   6907 
   6908   // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
   6909   // is a temporary being used as the 'this' pointer.
   6910   LValue This;
   6911   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
   6912   This.set(&VIE, Info.CurrentCall->Index);
   6913 
   6914   ArrayRef<const Expr*> Args;
   6915 
   6916   SourceLocation Loc = FD->getLocation();
   6917 
   6918   APValue Scratch;
   6919   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
   6920     HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
   6921   else
   6922     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
   6923                        Args, FD->getBody(), Info, Scratch);
   6924 
   6925   return Diags.empty();
   6926 }
   6927