1//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12// Constant expression evaluation produces four main results:
13//
14//  * A success/failure flag indicating whether constant folding was successful.
15//    This is the 'bool' return value used by most of the code in this file. A
16//    'false' return value indicates that constant folding has failed, and any
17//    appropriate diagnostic has already been produced.
18//
19//  * An evaluated result, valid only if constant folding has not failed.
20//
21//  * A flag indicating if evaluation encountered (unevaluated) side-effects.
22//    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23//    where it is possible to determine the evaluated result regardless.
24//
25//  * A set of notes indicating why the evaluation was not a constant expression
26//    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27//    too, why the expression could not be folded.
28//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
34//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
38#include "clang/AST/ASTDiagnostic.h"
39#include "clang/AST/CharUnits.h"
40#include "clang/AST/Expr.h"
41#include "clang/AST/RecordLayout.h"
42#include "clang/AST/StmtVisitor.h"
43#include "clang/AST/TypeLoc.h"
44#include "clang/Basic/Builtins.h"
45#include "clang/Basic/TargetInfo.h"
46#include "llvm/ADT/SmallString.h"
47#include "llvm/Support/raw_ostream.h"
48#include <cstring>
49#include <functional>
50
51using namespace clang;
52using llvm::APSInt;
53using llvm::APFloat;
54
55static bool IsGlobalLValue(APValue::LValueBase B);
56
57namespace {
58  struct LValue;
59  struct CallStackFrame;
60  struct EvalInfo;
61
62  static QualType getType(APValue::LValueBase B) {
63    if (!B) return QualType();
64    if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65      return D->getType();
66
67    const Expr *Base = B.get<const Expr*>();
68
69    // For a materialized temporary, the type of the temporary we materialized
70    // may not be the type of the expression.
71    if (const MaterializeTemporaryExpr *MTE =
72            dyn_cast<MaterializeTemporaryExpr>(Base)) {
73      SmallVector<const Expr *, 2> CommaLHSs;
74      SmallVector<SubobjectAdjustment, 2> Adjustments;
75      const Expr *Temp = MTE->GetTemporaryExpr();
76      const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77                                                               Adjustments);
78      // Keep any cv-qualifiers from the reference if we generated a temporary
79      // for it.
80      if (Inner != Temp)
81        return Inner->getType();
82    }
83
84    return Base->getType();
85  }
86
87  /// Get an LValue path entry, which is known to not be an array index, as a
88  /// field or base class.
89  static
90  APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
91    APValue::BaseOrMemberType Value;
92    Value.setFromOpaqueValue(E.BaseOrMember);
93    return Value;
94  }
95
96  /// Get an LValue path entry, which is known to not be an array index, as a
97  /// field declaration.
98  static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
99    return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
100  }
101  /// Get an LValue path entry, which is known to not be an array index, as a
102  /// base class declaration.
103  static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
104    return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
105  }
106  /// Determine whether this LValue path entry for a base class names a virtual
107  /// base class.
108  static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
109    return getAsBaseOrMember(E).getInt();
110  }
111
112  /// Find the path length and type of the most-derived subobject in the given
113  /// path, and find the size of the containing array, if any.
114  static
115  unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
116                                    ArrayRef<APValue::LValuePathEntry> Path,
117                                    uint64_t &ArraySize, QualType &Type) {
118    unsigned MostDerivedLength = 0;
119    Type = Base;
120    for (unsigned I = 0, N = Path.size(); I != N; ++I) {
121      if (Type->isArrayType()) {
122        const ConstantArrayType *CAT =
123          cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
124        Type = CAT->getElementType();
125        ArraySize = CAT->getSize().getZExtValue();
126        MostDerivedLength = I + 1;
127      } else if (Type->isAnyComplexType()) {
128        const ComplexType *CT = Type->castAs<ComplexType>();
129        Type = CT->getElementType();
130        ArraySize = 2;
131        MostDerivedLength = I + 1;
132      } else if (const FieldDecl *FD = getAsField(Path[I])) {
133        Type = FD->getType();
134        ArraySize = 0;
135        MostDerivedLength = I + 1;
136      } else {
137        // Path[I] describes a base class.
138        ArraySize = 0;
139      }
140    }
141    return MostDerivedLength;
142  }
143
144  // The order of this enum is important for diagnostics.
145  enum CheckSubobjectKind {
146    CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
147    CSK_This, CSK_Real, CSK_Imag
148  };
149
150  /// A path from a glvalue to a subobject of that glvalue.
151  struct SubobjectDesignator {
152    /// True if the subobject was named in a manner not supported by C++11. Such
153    /// lvalues can still be folded, but they are not core constant expressions
154    /// and we cannot perform lvalue-to-rvalue conversions on them.
155    bool Invalid : 1;
156
157    /// Is this a pointer one past the end of an object?
158    bool IsOnePastTheEnd : 1;
159
160    /// The length of the path to the most-derived object of which this is a
161    /// subobject.
162    unsigned MostDerivedPathLength : 30;
163
164    /// The size of the array of which the most-derived object is an element, or
165    /// 0 if the most-derived object is not an array element.
166    uint64_t MostDerivedArraySize;
167
168    /// The type of the most derived object referred to by this address.
169    QualType MostDerivedType;
170
171    typedef APValue::LValuePathEntry PathEntry;
172
173    /// The entries on the path from the glvalue to the designated subobject.
174    SmallVector<PathEntry, 8> Entries;
175
176    SubobjectDesignator() : Invalid(true) {}
177
178    explicit SubobjectDesignator(QualType T)
179      : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
180        MostDerivedArraySize(0), MostDerivedType(T) {}
181
182    SubobjectDesignator(ASTContext &Ctx, const APValue &V)
183      : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
184        MostDerivedPathLength(0), MostDerivedArraySize(0) {
185      if (!Invalid) {
186        IsOnePastTheEnd = V.isLValueOnePastTheEnd();
187        ArrayRef<PathEntry> VEntries = V.getLValuePath();
188        Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
189        if (V.getLValueBase())
190          MostDerivedPathLength =
191              findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
192                                       V.getLValuePath(), MostDerivedArraySize,
193                                       MostDerivedType);
194      }
195    }
196
197    void setInvalid() {
198      Invalid = true;
199      Entries.clear();
200    }
201
202    /// Determine whether this is a one-past-the-end pointer.
203    bool isOnePastTheEnd() const {
204      if (IsOnePastTheEnd)
205        return true;
206      if (MostDerivedArraySize &&
207          Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
208        return true;
209      return false;
210    }
211
212    /// Check that this refers to a valid subobject.
213    bool isValidSubobject() const {
214      if (Invalid)
215        return false;
216      return !isOnePastTheEnd();
217    }
218    /// Check that this refers to a valid subobject, and if not, produce a
219    /// relevant diagnostic and set the designator as invalid.
220    bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
221
222    /// Update this designator to refer to the first element within this array.
223    void addArrayUnchecked(const ConstantArrayType *CAT) {
224      PathEntry Entry;
225      Entry.ArrayIndex = 0;
226      Entries.push_back(Entry);
227
228      // This is a most-derived object.
229      MostDerivedType = CAT->getElementType();
230      MostDerivedArraySize = CAT->getSize().getZExtValue();
231      MostDerivedPathLength = Entries.size();
232    }
233    /// Update this designator to refer to the given base or member of this
234    /// object.
235    void addDeclUnchecked(const Decl *D, bool Virtual = false) {
236      PathEntry Entry;
237      APValue::BaseOrMemberType Value(D, Virtual);
238      Entry.BaseOrMember = Value.getOpaqueValue();
239      Entries.push_back(Entry);
240
241      // If this isn't a base class, it's a new most-derived object.
242      if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
243        MostDerivedType = FD->getType();
244        MostDerivedArraySize = 0;
245        MostDerivedPathLength = Entries.size();
246      }
247    }
248    /// Update this designator to refer to the given complex component.
249    void addComplexUnchecked(QualType EltTy, bool Imag) {
250      PathEntry Entry;
251      Entry.ArrayIndex = Imag;
252      Entries.push_back(Entry);
253
254      // This is technically a most-derived object, though in practice this
255      // is unlikely to matter.
256      MostDerivedType = EltTy;
257      MostDerivedArraySize = 2;
258      MostDerivedPathLength = Entries.size();
259    }
260    void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
261    /// Add N to the address of this subobject.
262    void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
263      if (Invalid) return;
264      if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
265        Entries.back().ArrayIndex += N;
266        if (Entries.back().ArrayIndex > MostDerivedArraySize) {
267          diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
268          setInvalid();
269        }
270        return;
271      }
272      // [expr.add]p4: For the purposes of these operators, a pointer to a
273      // nonarray object behaves the same as a pointer to the first element of
274      // an array of length one with the type of the object as its element type.
275      if (IsOnePastTheEnd && N == (uint64_t)-1)
276        IsOnePastTheEnd = false;
277      else if (!IsOnePastTheEnd && N == 1)
278        IsOnePastTheEnd = true;
279      else if (N != 0) {
280        diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
281        setInvalid();
282      }
283    }
284  };
285
286  /// A stack frame in the constexpr call stack.
287  struct CallStackFrame {
288    EvalInfo &Info;
289
290    /// Parent - The caller of this stack frame.
291    CallStackFrame *Caller;
292
293    /// CallLoc - The location of the call expression for this call.
294    SourceLocation CallLoc;
295
296    /// Callee - The function which was called.
297    const FunctionDecl *Callee;
298
299    /// Index - The call index of this call.
300    unsigned Index;
301
302    /// This - The binding for the this pointer in this call, if any.
303    const LValue *This;
304
305    /// Arguments - Parameter bindings for this function call, indexed by
306    /// parameters' function scope indices.
307    APValue *Arguments;
308
309    // Note that we intentionally use std::map here so that references to
310    // values are stable.
311    typedef std::map<const void*, APValue> MapTy;
312    typedef MapTy::const_iterator temp_iterator;
313    /// Temporaries - Temporary lvalues materialized within this stack frame.
314    MapTy Temporaries;
315
316    CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
317                   const FunctionDecl *Callee, const LValue *This,
318                   APValue *Arguments);
319    ~CallStackFrame();
320
321    APValue *getTemporary(const void *Key) {
322      MapTy::iterator I = Temporaries.find(Key);
323      return I == Temporaries.end() ? nullptr : &I->second;
324    }
325    APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
326  };
327
328  /// Temporarily override 'this'.
329  class ThisOverrideRAII {
330  public:
331    ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
332        : Frame(Frame), OldThis(Frame.This) {
333      if (Enable)
334        Frame.This = NewThis;
335    }
336    ~ThisOverrideRAII() {
337      Frame.This = OldThis;
338    }
339  private:
340    CallStackFrame &Frame;
341    const LValue *OldThis;
342  };
343
344  /// A partial diagnostic which we might know in advance that we are not going
345  /// to emit.
346  class OptionalDiagnostic {
347    PartialDiagnostic *Diag;
348
349  public:
350    explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
351      : Diag(Diag) {}
352
353    template<typename T>
354    OptionalDiagnostic &operator<<(const T &v) {
355      if (Diag)
356        *Diag << v;
357      return *this;
358    }
359
360    OptionalDiagnostic &operator<<(const APSInt &I) {
361      if (Diag) {
362        SmallVector<char, 32> Buffer;
363        I.toString(Buffer);
364        *Diag << StringRef(Buffer.data(), Buffer.size());
365      }
366      return *this;
367    }
368
369    OptionalDiagnostic &operator<<(const APFloat &F) {
370      if (Diag) {
371        // FIXME: Force the precision of the source value down so we don't
372        // print digits which are usually useless (we don't really care here if
373        // we truncate a digit by accident in edge cases).  Ideally,
374        // APFloat::toString would automatically print the shortest
375        // representation which rounds to the correct value, but it's a bit
376        // tricky to implement.
377        unsigned precision =
378            llvm::APFloat::semanticsPrecision(F.getSemantics());
379        precision = (precision * 59 + 195) / 196;
380        SmallVector<char, 32> Buffer;
381        F.toString(Buffer, precision);
382        *Diag << StringRef(Buffer.data(), Buffer.size());
383      }
384      return *this;
385    }
386  };
387
388  /// A cleanup, and a flag indicating whether it is lifetime-extended.
389  class Cleanup {
390    llvm::PointerIntPair<APValue*, 1, bool> Value;
391
392  public:
393    Cleanup(APValue *Val, bool IsLifetimeExtended)
394        : Value(Val, IsLifetimeExtended) {}
395
396    bool isLifetimeExtended() const { return Value.getInt(); }
397    void endLifetime() {
398      *Value.getPointer() = APValue();
399    }
400  };
401
402  /// EvalInfo - This is a private struct used by the evaluator to capture
403  /// information about a subexpression as it is folded.  It retains information
404  /// about the AST context, but also maintains information about the folded
405  /// expression.
406  ///
407  /// If an expression could be evaluated, it is still possible it is not a C
408  /// "integer constant expression" or constant expression.  If not, this struct
409  /// captures information about how and why not.
410  ///
411  /// One bit of information passed *into* the request for constant folding
412  /// indicates whether the subexpression is "evaluated" or not according to C
413  /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
414  /// evaluate the expression regardless of what the RHS is, but C only allows
415  /// certain things in certain situations.
416  struct EvalInfo {
417    ASTContext &Ctx;
418
419    /// EvalStatus - Contains information about the evaluation.
420    Expr::EvalStatus &EvalStatus;
421
422    /// CurrentCall - The top of the constexpr call stack.
423    CallStackFrame *CurrentCall;
424
425    /// CallStackDepth - The number of calls in the call stack right now.
426    unsigned CallStackDepth;
427
428    /// NextCallIndex - The next call index to assign.
429    unsigned NextCallIndex;
430
431    /// StepsLeft - The remaining number of evaluation steps we're permitted
432    /// to perform. This is essentially a limit for the number of statements
433    /// we will evaluate.
434    unsigned StepsLeft;
435
436    /// BottomFrame - The frame in which evaluation started. This must be
437    /// initialized after CurrentCall and CallStackDepth.
438    CallStackFrame BottomFrame;
439
440    /// A stack of values whose lifetimes end at the end of some surrounding
441    /// evaluation frame.
442    llvm::SmallVector<Cleanup, 16> CleanupStack;
443
444    /// EvaluatingDecl - This is the declaration whose initializer is being
445    /// evaluated, if any.
446    APValue::LValueBase EvaluatingDecl;
447
448    /// EvaluatingDeclValue - This is the value being constructed for the
449    /// declaration whose initializer is being evaluated, if any.
450    APValue *EvaluatingDeclValue;
451
452    /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
453    /// notes attached to it will also be stored, otherwise they will not be.
454    bool HasActiveDiagnostic;
455
456    enum EvaluationMode {
457      /// Evaluate as a constant expression. Stop if we find that the expression
458      /// is not a constant expression.
459      EM_ConstantExpression,
460
461      /// Evaluate as a potential constant expression. Keep going if we hit a
462      /// construct that we can't evaluate yet (because we don't yet know the
463      /// value of something) but stop if we hit something that could never be
464      /// a constant expression.
465      EM_PotentialConstantExpression,
466
467      /// Fold the expression to a constant. Stop if we hit a side-effect that
468      /// we can't model.
469      EM_ConstantFold,
470
471      /// Evaluate the expression looking for integer overflow and similar
472      /// issues. Don't worry about side-effects, and try to visit all
473      /// subexpressions.
474      EM_EvaluateForOverflow,
475
476      /// Evaluate in any way we know how. Don't worry about side-effects that
477      /// can't be modeled.
478      EM_IgnoreSideEffects,
479
480      /// Evaluate as a constant expression. Stop if we find that the expression
481      /// is not a constant expression. Some expressions can be retried in the
482      /// optimizer if we don't constant fold them here, but in an unevaluated
483      /// context we try to fold them immediately since the optimizer never
484      /// gets a chance to look at it.
485      EM_ConstantExpressionUnevaluated,
486
487      /// Evaluate as a potential constant expression. Keep going if we hit a
488      /// construct that we can't evaluate yet (because we don't yet know the
489      /// value of something) but stop if we hit something that could never be
490      /// a constant expression. Some expressions can be retried in the
491      /// optimizer if we don't constant fold them here, but in an unevaluated
492      /// context we try to fold them immediately since the optimizer never
493      /// gets a chance to look at it.
494      EM_PotentialConstantExpressionUnevaluated
495    } EvalMode;
496
497    /// Are we checking whether the expression is a potential constant
498    /// expression?
499    bool checkingPotentialConstantExpression() const {
500      return EvalMode == EM_PotentialConstantExpression ||
501             EvalMode == EM_PotentialConstantExpressionUnevaluated;
502    }
503
504    /// Are we checking an expression for overflow?
505    // FIXME: We should check for any kind of undefined or suspicious behavior
506    // in such constructs, not just overflow.
507    bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
508
509    EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
510      : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
511        CallStackDepth(0), NextCallIndex(1),
512        StepsLeft(getLangOpts().ConstexprStepLimit),
513        BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
514        EvaluatingDecl((const ValueDecl *)nullptr),
515        EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
516        EvalMode(Mode) {}
517
518    void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
519      EvaluatingDecl = Base;
520      EvaluatingDeclValue = &Value;
521    }
522
523    const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
524
525    bool CheckCallLimit(SourceLocation Loc) {
526      // Don't perform any constexpr calls (other than the call we're checking)
527      // when checking a potential constant expression.
528      if (checkingPotentialConstantExpression() && CallStackDepth > 1)
529        return false;
530      if (NextCallIndex == 0) {
531        // NextCallIndex has wrapped around.
532        Diag(Loc, diag::note_constexpr_call_limit_exceeded);
533        return false;
534      }
535      if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
536        return true;
537      Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
538        << getLangOpts().ConstexprCallDepth;
539      return false;
540    }
541
542    CallStackFrame *getCallFrame(unsigned CallIndex) {
543      assert(CallIndex && "no call index in getCallFrame");
544      // We will eventually hit BottomFrame, which has Index 1, so Frame can't
545      // be null in this loop.
546      CallStackFrame *Frame = CurrentCall;
547      while (Frame->Index > CallIndex)
548        Frame = Frame->Caller;
549      return (Frame->Index == CallIndex) ? Frame : nullptr;
550    }
551
552    bool nextStep(const Stmt *S) {
553      if (!StepsLeft) {
554        Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
555        return false;
556      }
557      --StepsLeft;
558      return true;
559    }
560
561  private:
562    /// Add a diagnostic to the diagnostics list.
563    PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
564      PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
565      EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
566      return EvalStatus.Diag->back().second;
567    }
568
569    /// Add notes containing a call stack to the current point of evaluation.
570    void addCallStack(unsigned Limit);
571
572  public:
573    /// Diagnose that the evaluation cannot be folded.
574    OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
575                              = diag::note_invalid_subexpr_in_const_expr,
576                            unsigned ExtraNotes = 0) {
577      if (EvalStatus.Diag) {
578        // If we have a prior diagnostic, it will be noting that the expression
579        // isn't a constant expression. This diagnostic is more important,
580        // unless we require this evaluation to produce a constant expression.
581        //
582        // FIXME: We might want to show both diagnostics to the user in
583        // EM_ConstantFold mode.
584        if (!EvalStatus.Diag->empty()) {
585          switch (EvalMode) {
586          case EM_ConstantFold:
587          case EM_IgnoreSideEffects:
588          case EM_EvaluateForOverflow:
589            if (!EvalStatus.HasSideEffects)
590              break;
591            // We've had side-effects; we want the diagnostic from them, not
592            // some later problem.
593          case EM_ConstantExpression:
594          case EM_PotentialConstantExpression:
595          case EM_ConstantExpressionUnevaluated:
596          case EM_PotentialConstantExpressionUnevaluated:
597            HasActiveDiagnostic = false;
598            return OptionalDiagnostic();
599          }
600        }
601
602        unsigned CallStackNotes = CallStackDepth - 1;
603        unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
604        if (Limit)
605          CallStackNotes = std::min(CallStackNotes, Limit + 1);
606        if (checkingPotentialConstantExpression())
607          CallStackNotes = 0;
608
609        HasActiveDiagnostic = true;
610        EvalStatus.Diag->clear();
611        EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
612        addDiag(Loc, DiagId);
613        if (!checkingPotentialConstantExpression())
614          addCallStack(Limit);
615        return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
616      }
617      HasActiveDiagnostic = false;
618      return OptionalDiagnostic();
619    }
620
621    OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
622                              = diag::note_invalid_subexpr_in_const_expr,
623                            unsigned ExtraNotes = 0) {
624      if (EvalStatus.Diag)
625        return Diag(E->getExprLoc(), DiagId, ExtraNotes);
626      HasActiveDiagnostic = false;
627      return OptionalDiagnostic();
628    }
629
630    /// Diagnose that the evaluation does not produce a C++11 core constant
631    /// expression.
632    ///
633    /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
634    /// EM_PotentialConstantExpression mode and we produce one of these.
635    template<typename LocArg>
636    OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
637                                 = diag::note_invalid_subexpr_in_const_expr,
638                               unsigned ExtraNotes = 0) {
639      // Don't override a previous diagnostic. Don't bother collecting
640      // diagnostics if we're evaluating for overflow.
641      if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
642        HasActiveDiagnostic = false;
643        return OptionalDiagnostic();
644      }
645      return Diag(Loc, DiagId, ExtraNotes);
646    }
647
648    /// Add a note to a prior diagnostic.
649    OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
650      if (!HasActiveDiagnostic)
651        return OptionalDiagnostic();
652      return OptionalDiagnostic(&addDiag(Loc, DiagId));
653    }
654
655    /// Add a stack of notes to a prior diagnostic.
656    void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
657      if (HasActiveDiagnostic) {
658        EvalStatus.Diag->insert(EvalStatus.Diag->end(),
659                                Diags.begin(), Diags.end());
660      }
661    }
662
663    /// Should we continue evaluation after encountering a side-effect that we
664    /// couldn't model?
665    bool keepEvaluatingAfterSideEffect() {
666      switch (EvalMode) {
667      case EM_PotentialConstantExpression:
668      case EM_PotentialConstantExpressionUnevaluated:
669      case EM_EvaluateForOverflow:
670      case EM_IgnoreSideEffects:
671        return true;
672
673      case EM_ConstantExpression:
674      case EM_ConstantExpressionUnevaluated:
675      case EM_ConstantFold:
676        return false;
677      }
678      llvm_unreachable("Missed EvalMode case");
679    }
680
681    /// Note that we have had a side-effect, and determine whether we should
682    /// keep evaluating.
683    bool noteSideEffect() {
684      EvalStatus.HasSideEffects = true;
685      return keepEvaluatingAfterSideEffect();
686    }
687
688    /// Should we continue evaluation as much as possible after encountering a
689    /// construct which can't be reduced to a value?
690    bool keepEvaluatingAfterFailure() {
691      if (!StepsLeft)
692        return false;
693
694      switch (EvalMode) {
695      case EM_PotentialConstantExpression:
696      case EM_PotentialConstantExpressionUnevaluated:
697      case EM_EvaluateForOverflow:
698        return true;
699
700      case EM_ConstantExpression:
701      case EM_ConstantExpressionUnevaluated:
702      case EM_ConstantFold:
703      case EM_IgnoreSideEffects:
704        return false;
705      }
706      llvm_unreachable("Missed EvalMode case");
707    }
708  };
709
710  /// Object used to treat all foldable expressions as constant expressions.
711  struct FoldConstant {
712    EvalInfo &Info;
713    bool Enabled;
714    bool HadNoPriorDiags;
715    EvalInfo::EvaluationMode OldMode;
716
717    explicit FoldConstant(EvalInfo &Info, bool Enabled)
718      : Info(Info),
719        Enabled(Enabled),
720        HadNoPriorDiags(Info.EvalStatus.Diag &&
721                        Info.EvalStatus.Diag->empty() &&
722                        !Info.EvalStatus.HasSideEffects),
723        OldMode(Info.EvalMode) {
724      if (Enabled &&
725          (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
726           Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
727        Info.EvalMode = EvalInfo::EM_ConstantFold;
728    }
729    void keepDiagnostics() { Enabled = false; }
730    ~FoldConstant() {
731      if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
732          !Info.EvalStatus.HasSideEffects)
733        Info.EvalStatus.Diag->clear();
734      Info.EvalMode = OldMode;
735    }
736  };
737
738  /// RAII object used to suppress diagnostics and side-effects from a
739  /// speculative evaluation.
740  class SpeculativeEvaluationRAII {
741    EvalInfo &Info;
742    Expr::EvalStatus Old;
743
744  public:
745    SpeculativeEvaluationRAII(EvalInfo &Info,
746                        SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
747      : Info(Info), Old(Info.EvalStatus) {
748      Info.EvalStatus.Diag = NewDiag;
749      // If we're speculatively evaluating, we may have skipped over some
750      // evaluations and missed out a side effect.
751      Info.EvalStatus.HasSideEffects = true;
752    }
753    ~SpeculativeEvaluationRAII() {
754      Info.EvalStatus = Old;
755    }
756  };
757
758  /// RAII object wrapping a full-expression or block scope, and handling
759  /// the ending of the lifetime of temporaries created within it.
760  template<bool IsFullExpression>
761  class ScopeRAII {
762    EvalInfo &Info;
763    unsigned OldStackSize;
764  public:
765    ScopeRAII(EvalInfo &Info)
766        : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
767    ~ScopeRAII() {
768      // Body moved to a static method to encourage the compiler to inline away
769      // instances of this class.
770      cleanup(Info, OldStackSize);
771    }
772  private:
773    static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
774      unsigned NewEnd = OldStackSize;
775      for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
776           I != N; ++I) {
777        if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
778          // Full-expression cleanup of a lifetime-extended temporary: nothing
779          // to do, just move this cleanup to the right place in the stack.
780          std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
781          ++NewEnd;
782        } else {
783          // End the lifetime of the object.
784          Info.CleanupStack[I].endLifetime();
785        }
786      }
787      Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
788                              Info.CleanupStack.end());
789    }
790  };
791  typedef ScopeRAII<false> BlockScopeRAII;
792  typedef ScopeRAII<true> FullExpressionRAII;
793}
794
795bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
796                                         CheckSubobjectKind CSK) {
797  if (Invalid)
798    return false;
799  if (isOnePastTheEnd()) {
800    Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
801      << CSK;
802    setInvalid();
803    return false;
804  }
805  return true;
806}
807
808void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
809                                                    const Expr *E, uint64_t N) {
810  if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
811    Info.CCEDiag(E, diag::note_constexpr_array_index)
812      << static_cast<int>(N) << /*array*/ 0
813      << static_cast<unsigned>(MostDerivedArraySize);
814  else
815    Info.CCEDiag(E, diag::note_constexpr_array_index)
816      << static_cast<int>(N) << /*non-array*/ 1;
817  setInvalid();
818}
819
820CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
821                               const FunctionDecl *Callee, const LValue *This,
822                               APValue *Arguments)
823    : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
824      Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
825  Info.CurrentCall = this;
826  ++Info.CallStackDepth;
827}
828
829CallStackFrame::~CallStackFrame() {
830  assert(Info.CurrentCall == this && "calls retired out of order");
831  --Info.CallStackDepth;
832  Info.CurrentCall = Caller;
833}
834
835APValue &CallStackFrame::createTemporary(const void *Key,
836                                         bool IsLifetimeExtended) {
837  APValue &Result = Temporaries[Key];
838  assert(Result.isUninit() && "temporary created multiple times");
839  Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
840  return Result;
841}
842
843static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
844
845void EvalInfo::addCallStack(unsigned Limit) {
846  // Determine which calls to skip, if any.
847  unsigned ActiveCalls = CallStackDepth - 1;
848  unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
849  if (Limit && Limit < ActiveCalls) {
850    SkipStart = Limit / 2 + Limit % 2;
851    SkipEnd = ActiveCalls - Limit / 2;
852  }
853
854  // Walk the call stack and add the diagnostics.
855  unsigned CallIdx = 0;
856  for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
857       Frame = Frame->Caller, ++CallIdx) {
858    // Skip this call?
859    if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
860      if (CallIdx == SkipStart) {
861        // Note that we're skipping calls.
862        addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
863          << unsigned(ActiveCalls - Limit);
864      }
865      continue;
866    }
867
868    SmallVector<char, 128> Buffer;
869    llvm::raw_svector_ostream Out(Buffer);
870    describeCall(Frame, Out);
871    addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
872  }
873}
874
875namespace {
876  struct ComplexValue {
877  private:
878    bool IsInt;
879
880  public:
881    APSInt IntReal, IntImag;
882    APFloat FloatReal, FloatImag;
883
884    ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
885
886    void makeComplexFloat() { IsInt = false; }
887    bool isComplexFloat() const { return !IsInt; }
888    APFloat &getComplexFloatReal() { return FloatReal; }
889    APFloat &getComplexFloatImag() { return FloatImag; }
890
891    void makeComplexInt() { IsInt = true; }
892    bool isComplexInt() const { return IsInt; }
893    APSInt &getComplexIntReal() { return IntReal; }
894    APSInt &getComplexIntImag() { return IntImag; }
895
896    void moveInto(APValue &v) const {
897      if (isComplexFloat())
898        v = APValue(FloatReal, FloatImag);
899      else
900        v = APValue(IntReal, IntImag);
901    }
902    void setFrom(const APValue &v) {
903      assert(v.isComplexFloat() || v.isComplexInt());
904      if (v.isComplexFloat()) {
905        makeComplexFloat();
906        FloatReal = v.getComplexFloatReal();
907        FloatImag = v.getComplexFloatImag();
908      } else {
909        makeComplexInt();
910        IntReal = v.getComplexIntReal();
911        IntImag = v.getComplexIntImag();
912      }
913    }
914  };
915
916  struct LValue {
917    APValue::LValueBase Base;
918    CharUnits Offset;
919    unsigned CallIndex;
920    SubobjectDesignator Designator;
921
922    const APValue::LValueBase getLValueBase() const { return Base; }
923    CharUnits &getLValueOffset() { return Offset; }
924    const CharUnits &getLValueOffset() const { return Offset; }
925    unsigned getLValueCallIndex() const { return CallIndex; }
926    SubobjectDesignator &getLValueDesignator() { return Designator; }
927    const SubobjectDesignator &getLValueDesignator() const { return Designator;}
928
929    void moveInto(APValue &V) const {
930      if (Designator.Invalid)
931        V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
932      else
933        V = APValue(Base, Offset, Designator.Entries,
934                    Designator.IsOnePastTheEnd, CallIndex);
935    }
936    void setFrom(ASTContext &Ctx, const APValue &V) {
937      assert(V.isLValue());
938      Base = V.getLValueBase();
939      Offset = V.getLValueOffset();
940      CallIndex = V.getLValueCallIndex();
941      Designator = SubobjectDesignator(Ctx, V);
942    }
943
944    void set(APValue::LValueBase B, unsigned I = 0) {
945      Base = B;
946      Offset = CharUnits::Zero();
947      CallIndex = I;
948      Designator = SubobjectDesignator(getType(B));
949    }
950
951    // Check that this LValue is not based on a null pointer. If it is, produce
952    // a diagnostic and mark the designator as invalid.
953    bool checkNullPointer(EvalInfo &Info, const Expr *E,
954                          CheckSubobjectKind CSK) {
955      if (Designator.Invalid)
956        return false;
957      if (!Base) {
958        Info.CCEDiag(E, diag::note_constexpr_null_subobject)
959          << CSK;
960        Designator.setInvalid();
961        return false;
962      }
963      return true;
964    }
965
966    // Check this LValue refers to an object. If not, set the designator to be
967    // invalid and emit a diagnostic.
968    bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
969      // Outside C++11, do not build a designator referring to a subobject of
970      // any object: we won't use such a designator for anything.
971      if (!Info.getLangOpts().CPlusPlus11)
972        Designator.setInvalid();
973      return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
974             Designator.checkSubobject(Info, E, CSK);
975    }
976
977    void addDecl(EvalInfo &Info, const Expr *E,
978                 const Decl *D, bool Virtual = false) {
979      if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
980        Designator.addDeclUnchecked(D, Virtual);
981    }
982    void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
983      if (checkSubobject(Info, E, CSK_ArrayToPointer))
984        Designator.addArrayUnchecked(CAT);
985    }
986    void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
987      if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
988        Designator.addComplexUnchecked(EltTy, Imag);
989    }
990    void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
991      if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
992        Designator.adjustIndex(Info, E, N);
993    }
994  };
995
996  struct MemberPtr {
997    MemberPtr() {}
998    explicit MemberPtr(const ValueDecl *Decl) :
999      DeclAndIsDerivedMember(Decl, false), Path() {}
1000
1001    /// The member or (direct or indirect) field referred to by this member
1002    /// pointer, or 0 if this is a null member pointer.
1003    const ValueDecl *getDecl() const {
1004      return DeclAndIsDerivedMember.getPointer();
1005    }
1006    /// Is this actually a member of some type derived from the relevant class?
1007    bool isDerivedMember() const {
1008      return DeclAndIsDerivedMember.getInt();
1009    }
1010    /// Get the class which the declaration actually lives in.
1011    const CXXRecordDecl *getContainingRecord() const {
1012      return cast<CXXRecordDecl>(
1013          DeclAndIsDerivedMember.getPointer()->getDeclContext());
1014    }
1015
1016    void moveInto(APValue &V) const {
1017      V = APValue(getDecl(), isDerivedMember(), Path);
1018    }
1019    void setFrom(const APValue &V) {
1020      assert(V.isMemberPointer());
1021      DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1022      DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1023      Path.clear();
1024      ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1025      Path.insert(Path.end(), P.begin(), P.end());
1026    }
1027
1028    /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1029    /// whether the member is a member of some class derived from the class type
1030    /// of the member pointer.
1031    llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1032    /// Path - The path of base/derived classes from the member declaration's
1033    /// class (exclusive) to the class type of the member pointer (inclusive).
1034    SmallVector<const CXXRecordDecl*, 4> Path;
1035
1036    /// Perform a cast towards the class of the Decl (either up or down the
1037    /// hierarchy).
1038    bool castBack(const CXXRecordDecl *Class) {
1039      assert(!Path.empty());
1040      const CXXRecordDecl *Expected;
1041      if (Path.size() >= 2)
1042        Expected = Path[Path.size() - 2];
1043      else
1044        Expected = getContainingRecord();
1045      if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1046        // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1047        // if B does not contain the original member and is not a base or
1048        // derived class of the class containing the original member, the result
1049        // of the cast is undefined.
1050        // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1051        // (D::*). We consider that to be a language defect.
1052        return false;
1053      }
1054      Path.pop_back();
1055      return true;
1056    }
1057    /// Perform a base-to-derived member pointer cast.
1058    bool castToDerived(const CXXRecordDecl *Derived) {
1059      if (!getDecl())
1060        return true;
1061      if (!isDerivedMember()) {
1062        Path.push_back(Derived);
1063        return true;
1064      }
1065      if (!castBack(Derived))
1066        return false;
1067      if (Path.empty())
1068        DeclAndIsDerivedMember.setInt(false);
1069      return true;
1070    }
1071    /// Perform a derived-to-base member pointer cast.
1072    bool castToBase(const CXXRecordDecl *Base) {
1073      if (!getDecl())
1074        return true;
1075      if (Path.empty())
1076        DeclAndIsDerivedMember.setInt(true);
1077      if (isDerivedMember()) {
1078        Path.push_back(Base);
1079        return true;
1080      }
1081      return castBack(Base);
1082    }
1083  };
1084
1085  /// Compare two member pointers, which are assumed to be of the same type.
1086  static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1087    if (!LHS.getDecl() || !RHS.getDecl())
1088      return !LHS.getDecl() && !RHS.getDecl();
1089    if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1090      return false;
1091    return LHS.Path == RHS.Path;
1092  }
1093}
1094
1095static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1096static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1097                            const LValue &This, const Expr *E,
1098                            bool AllowNonLiteralTypes = false);
1099static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1100static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
1101static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1102                                  EvalInfo &Info);
1103static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1104static bool EvaluateInteger(const Expr *E, APSInt  &Result, EvalInfo &Info);
1105static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1106                                    EvalInfo &Info);
1107static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1108static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1109static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
1110
1111//===----------------------------------------------------------------------===//
1112// Misc utilities
1113//===----------------------------------------------------------------------===//
1114
1115/// Produce a string describing the given constexpr call.
1116static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1117  unsigned ArgIndex = 0;
1118  bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1119                      !isa<CXXConstructorDecl>(Frame->Callee) &&
1120                      cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1121
1122  if (!IsMemberCall)
1123    Out << *Frame->Callee << '(';
1124
1125  if (Frame->This && IsMemberCall) {
1126    APValue Val;
1127    Frame->This->moveInto(Val);
1128    Val.printPretty(Out, Frame->Info.Ctx,
1129                    Frame->This->Designator.MostDerivedType);
1130    // FIXME: Add parens around Val if needed.
1131    Out << "->" << *Frame->Callee << '(';
1132    IsMemberCall = false;
1133  }
1134
1135  for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1136       E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1137    if (ArgIndex > (unsigned)IsMemberCall)
1138      Out << ", ";
1139
1140    const ParmVarDecl *Param = *I;
1141    const APValue &Arg = Frame->Arguments[ArgIndex];
1142    Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1143
1144    if (ArgIndex == 0 && IsMemberCall)
1145      Out << "->" << *Frame->Callee << '(';
1146  }
1147
1148  Out << ')';
1149}
1150
1151/// Evaluate an expression to see if it had side-effects, and discard its
1152/// result.
1153/// \return \c true if the caller should keep evaluating.
1154static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1155  APValue Scratch;
1156  if (!Evaluate(Scratch, Info, E))
1157    // We don't need the value, but we might have skipped a side effect here.
1158    return Info.noteSideEffect();
1159  return true;
1160}
1161
1162/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1163/// return its existing value.
1164static int64_t getExtValue(const APSInt &Value) {
1165  return Value.isSigned() ? Value.getSExtValue()
1166                          : static_cast<int64_t>(Value.getZExtValue());
1167}
1168
1169/// Should this call expression be treated as a string literal?
1170static bool IsStringLiteralCall(const CallExpr *E) {
1171  unsigned Builtin = E->getBuiltinCallee();
1172  return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1173          Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1174}
1175
1176static bool IsGlobalLValue(APValue::LValueBase B) {
1177  // C++11 [expr.const]p3 An address constant expression is a prvalue core
1178  // constant expression of pointer type that evaluates to...
1179
1180  // ... a null pointer value, or a prvalue core constant expression of type
1181  // std::nullptr_t.
1182  if (!B) return true;
1183
1184  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1185    // ... the address of an object with static storage duration,
1186    if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1187      return VD->hasGlobalStorage();
1188    // ... the address of a function,
1189    return isa<FunctionDecl>(D);
1190  }
1191
1192  const Expr *E = B.get<const Expr*>();
1193  switch (E->getStmtClass()) {
1194  default:
1195    return false;
1196  case Expr::CompoundLiteralExprClass: {
1197    const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1198    return CLE->isFileScope() && CLE->isLValue();
1199  }
1200  case Expr::MaterializeTemporaryExprClass:
1201    // A materialized temporary might have been lifetime-extended to static
1202    // storage duration.
1203    return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1204  // A string literal has static storage duration.
1205  case Expr::StringLiteralClass:
1206  case Expr::PredefinedExprClass:
1207  case Expr::ObjCStringLiteralClass:
1208  case Expr::ObjCEncodeExprClass:
1209  case Expr::CXXTypeidExprClass:
1210  case Expr::CXXUuidofExprClass:
1211    return true;
1212  case Expr::CallExprClass:
1213    return IsStringLiteralCall(cast<CallExpr>(E));
1214  // For GCC compatibility, &&label has static storage duration.
1215  case Expr::AddrLabelExprClass:
1216    return true;
1217  // A Block literal expression may be used as the initialization value for
1218  // Block variables at global or local static scope.
1219  case Expr::BlockExprClass:
1220    return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1221  case Expr::ImplicitValueInitExprClass:
1222    // FIXME:
1223    // We can never form an lvalue with an implicit value initialization as its
1224    // base through expression evaluation, so these only appear in one case: the
1225    // implicit variable declaration we invent when checking whether a constexpr
1226    // constructor can produce a constant expression. We must assume that such
1227    // an expression might be a global lvalue.
1228    return true;
1229  }
1230}
1231
1232static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1233  assert(Base && "no location for a null lvalue");
1234  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1235  if (VD)
1236    Info.Note(VD->getLocation(), diag::note_declared_at);
1237  else
1238    Info.Note(Base.get<const Expr*>()->getExprLoc(),
1239              diag::note_constexpr_temporary_here);
1240}
1241
1242/// Check that this reference or pointer core constant expression is a valid
1243/// value for an address or reference constant expression. Return true if we
1244/// can fold this expression, whether or not it's a constant expression.
1245static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1246                                          QualType Type, const LValue &LVal) {
1247  bool IsReferenceType = Type->isReferenceType();
1248
1249  APValue::LValueBase Base = LVal.getLValueBase();
1250  const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1251
1252  // Check that the object is a global. Note that the fake 'this' object we
1253  // manufacture when checking potential constant expressions is conservatively
1254  // assumed to be global here.
1255  if (!IsGlobalLValue(Base)) {
1256    if (Info.getLangOpts().CPlusPlus11) {
1257      const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1258      Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1259        << IsReferenceType << !Designator.Entries.empty()
1260        << !!VD << VD;
1261      NoteLValueLocation(Info, Base);
1262    } else {
1263      Info.Diag(Loc);
1264    }
1265    // Don't allow references to temporaries to escape.
1266    return false;
1267  }
1268  assert((Info.checkingPotentialConstantExpression() ||
1269          LVal.getLValueCallIndex() == 0) &&
1270         "have call index for global lvalue");
1271
1272  if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1273    if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1274      // Check if this is a thread-local variable.
1275      if (Var->getTLSKind())
1276        return false;
1277
1278      // A dllimport variable never acts like a constant.
1279      if (Var->hasAttr<DLLImportAttr>())
1280        return false;
1281    }
1282    if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1283      // __declspec(dllimport) must be handled very carefully:
1284      // We must never initialize an expression with the thunk in C++.
1285      // Doing otherwise would allow the same id-expression to yield
1286      // different addresses for the same function in different translation
1287      // units.  However, this means that we must dynamically initialize the
1288      // expression with the contents of the import address table at runtime.
1289      //
1290      // The C language has no notion of ODR; furthermore, it has no notion of
1291      // dynamic initialization.  This means that we are permitted to
1292      // perform initialization with the address of the thunk.
1293      if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
1294        return false;
1295    }
1296  }
1297
1298  // Allow address constant expressions to be past-the-end pointers. This is
1299  // an extension: the standard requires them to point to an object.
1300  if (!IsReferenceType)
1301    return true;
1302
1303  // A reference constant expression must refer to an object.
1304  if (!Base) {
1305    // FIXME: diagnostic
1306    Info.CCEDiag(Loc);
1307    return true;
1308  }
1309
1310  // Does this refer one past the end of some object?
1311  if (Designator.isOnePastTheEnd()) {
1312    const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1313    Info.Diag(Loc, diag::note_constexpr_past_end, 1)
1314      << !Designator.Entries.empty() << !!VD << VD;
1315    NoteLValueLocation(Info, Base);
1316  }
1317
1318  return true;
1319}
1320
1321/// Check that this core constant expression is of literal type, and if not,
1322/// produce an appropriate diagnostic.
1323static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1324                             const LValue *This = nullptr) {
1325  if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1326    return true;
1327
1328  // C++1y: A constant initializer for an object o [...] may also invoke
1329  // constexpr constructors for o and its subobjects even if those objects
1330  // are of non-literal class types.
1331  if (Info.getLangOpts().CPlusPlus1y && This &&
1332      Info.EvaluatingDecl == This->getLValueBase())
1333    return true;
1334
1335  // Prvalue constant expressions must be of literal types.
1336  if (Info.getLangOpts().CPlusPlus11)
1337    Info.Diag(E, diag::note_constexpr_nonliteral)
1338      << E->getType();
1339  else
1340    Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1341  return false;
1342}
1343
1344/// Check that this core constant expression value is a valid value for a
1345/// constant expression. If not, report an appropriate diagnostic. Does not
1346/// check that the expression is of literal type.
1347static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1348                                    QualType Type, const APValue &Value) {
1349  if (Value.isUninit()) {
1350    Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1351      << true << Type;
1352    return false;
1353  }
1354
1355  // Core issue 1454: For a literal constant expression of array or class type,
1356  // each subobject of its value shall have been initialized by a constant
1357  // expression.
1358  if (Value.isArray()) {
1359    QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1360    for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1361      if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1362                                   Value.getArrayInitializedElt(I)))
1363        return false;
1364    }
1365    if (!Value.hasArrayFiller())
1366      return true;
1367    return CheckConstantExpression(Info, DiagLoc, EltTy,
1368                                   Value.getArrayFiller());
1369  }
1370  if (Value.isUnion() && Value.getUnionField()) {
1371    return CheckConstantExpression(Info, DiagLoc,
1372                                   Value.getUnionField()->getType(),
1373                                   Value.getUnionValue());
1374  }
1375  if (Value.isStruct()) {
1376    RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1377    if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1378      unsigned BaseIndex = 0;
1379      for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1380             End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1381        if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1382                                     Value.getStructBase(BaseIndex)))
1383          return false;
1384      }
1385    }
1386    for (const auto *I : RD->fields()) {
1387      if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1388                                   Value.getStructField(I->getFieldIndex())))
1389        return false;
1390    }
1391  }
1392
1393  if (Value.isLValue()) {
1394    LValue LVal;
1395    LVal.setFrom(Info.Ctx, Value);
1396    return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1397  }
1398
1399  // Everything else is fine.
1400  return true;
1401}
1402
1403const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1404  return LVal.Base.dyn_cast<const ValueDecl*>();
1405}
1406
1407static bool IsLiteralLValue(const LValue &Value) {
1408  if (Value.CallIndex)
1409    return false;
1410  const Expr *E = Value.Base.dyn_cast<const Expr*>();
1411  return E && !isa<MaterializeTemporaryExpr>(E);
1412}
1413
1414static bool IsWeakLValue(const LValue &Value) {
1415  const ValueDecl *Decl = GetLValueBaseDecl(Value);
1416  return Decl && Decl->isWeak();
1417}
1418
1419static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1420  // A null base expression indicates a null pointer.  These are always
1421  // evaluatable, and they are false unless the offset is zero.
1422  if (!Value.getLValueBase()) {
1423    Result = !Value.getLValueOffset().isZero();
1424    return true;
1425  }
1426
1427  // We have a non-null base.  These are generally known to be true, but if it's
1428  // a weak declaration it can be null at runtime.
1429  Result = true;
1430  const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1431  return !Decl || !Decl->isWeak();
1432}
1433
1434static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1435  switch (Val.getKind()) {
1436  case APValue::Uninitialized:
1437    return false;
1438  case APValue::Int:
1439    Result = Val.getInt().getBoolValue();
1440    return true;
1441  case APValue::Float:
1442    Result = !Val.getFloat().isZero();
1443    return true;
1444  case APValue::ComplexInt:
1445    Result = Val.getComplexIntReal().getBoolValue() ||
1446             Val.getComplexIntImag().getBoolValue();
1447    return true;
1448  case APValue::ComplexFloat:
1449    Result = !Val.getComplexFloatReal().isZero() ||
1450             !Val.getComplexFloatImag().isZero();
1451    return true;
1452  case APValue::LValue:
1453    return EvalPointerValueAsBool(Val, Result);
1454  case APValue::MemberPointer:
1455    Result = Val.getMemberPointerDecl();
1456    return true;
1457  case APValue::Vector:
1458  case APValue::Array:
1459  case APValue::Struct:
1460  case APValue::Union:
1461  case APValue::AddrLabelDiff:
1462    return false;
1463  }
1464
1465  llvm_unreachable("unknown APValue kind");
1466}
1467
1468static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1469                                       EvalInfo &Info) {
1470  assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1471  APValue Val;
1472  if (!Evaluate(Val, Info, E))
1473    return false;
1474  return HandleConversionToBool(Val, Result);
1475}
1476
1477template<typename T>
1478static void HandleOverflow(EvalInfo &Info, const Expr *E,
1479                           const T &SrcValue, QualType DestType) {
1480  Info.CCEDiag(E, diag::note_constexpr_overflow)
1481    << SrcValue << DestType;
1482}
1483
1484static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1485                                 QualType SrcType, const APFloat &Value,
1486                                 QualType DestType, APSInt &Result) {
1487  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1488  // Determine whether we are converting to unsigned or signed.
1489  bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1490
1491  Result = APSInt(DestWidth, !DestSigned);
1492  bool ignored;
1493  if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1494      & APFloat::opInvalidOp)
1495    HandleOverflow(Info, E, Value, DestType);
1496  return true;
1497}
1498
1499static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1500                                   QualType SrcType, QualType DestType,
1501                                   APFloat &Result) {
1502  APFloat Value = Result;
1503  bool ignored;
1504  if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1505                     APFloat::rmNearestTiesToEven, &ignored)
1506      & APFloat::opOverflow)
1507    HandleOverflow(Info, E, Value, DestType);
1508  return true;
1509}
1510
1511static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1512                                 QualType DestType, QualType SrcType,
1513                                 APSInt &Value) {
1514  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1515  APSInt Result = Value;
1516  // Figure out if this is a truncate, extend or noop cast.
1517  // If the input is signed, do a sign extend, noop, or truncate.
1518  Result = Result.extOrTrunc(DestWidth);
1519  Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1520  return Result;
1521}
1522
1523static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1524                                 QualType SrcType, const APSInt &Value,
1525                                 QualType DestType, APFloat &Result) {
1526  Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1527  if (Result.convertFromAPInt(Value, Value.isSigned(),
1528                              APFloat::rmNearestTiesToEven)
1529      & APFloat::opOverflow)
1530    HandleOverflow(Info, E, Value, DestType);
1531  return true;
1532}
1533
1534static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1535                                  APValue &Value, const FieldDecl *FD) {
1536  assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1537
1538  if (!Value.isInt()) {
1539    // Trying to store a pointer-cast-to-integer into a bitfield.
1540    // FIXME: In this case, we should provide the diagnostic for casting
1541    // a pointer to an integer.
1542    assert(Value.isLValue() && "integral value neither int nor lvalue?");
1543    Info.Diag(E);
1544    return false;
1545  }
1546
1547  APSInt &Int = Value.getInt();
1548  unsigned OldBitWidth = Int.getBitWidth();
1549  unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1550  if (NewBitWidth < OldBitWidth)
1551    Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1552  return true;
1553}
1554
1555static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1556                                  llvm::APInt &Res) {
1557  APValue SVal;
1558  if (!Evaluate(SVal, Info, E))
1559    return false;
1560  if (SVal.isInt()) {
1561    Res = SVal.getInt();
1562    return true;
1563  }
1564  if (SVal.isFloat()) {
1565    Res = SVal.getFloat().bitcastToAPInt();
1566    return true;
1567  }
1568  if (SVal.isVector()) {
1569    QualType VecTy = E->getType();
1570    unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1571    QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1572    unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1573    bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1574    Res = llvm::APInt::getNullValue(VecSize);
1575    for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1576      APValue &Elt = SVal.getVectorElt(i);
1577      llvm::APInt EltAsInt;
1578      if (Elt.isInt()) {
1579        EltAsInt = Elt.getInt();
1580      } else if (Elt.isFloat()) {
1581        EltAsInt = Elt.getFloat().bitcastToAPInt();
1582      } else {
1583        // Don't try to handle vectors of anything other than int or float
1584        // (not sure if it's possible to hit this case).
1585        Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1586        return false;
1587      }
1588      unsigned BaseEltSize = EltAsInt.getBitWidth();
1589      if (BigEndian)
1590        Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1591      else
1592        Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1593    }
1594    return true;
1595  }
1596  // Give up if the input isn't an int, float, or vector.  For example, we
1597  // reject "(v4i16)(intptr_t)&a".
1598  Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1599  return false;
1600}
1601
1602/// Perform the given integer operation, which is known to need at most BitWidth
1603/// bits, and check for overflow in the original type (if that type was not an
1604/// unsigned type).
1605template<typename Operation>
1606static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1607                                   const APSInt &LHS, const APSInt &RHS,
1608                                   unsigned BitWidth, Operation Op) {
1609  if (LHS.isUnsigned())
1610    return Op(LHS, RHS);
1611
1612  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1613  APSInt Result = Value.trunc(LHS.getBitWidth());
1614  if (Result.extend(BitWidth) != Value) {
1615    if (Info.checkingForOverflow())
1616      Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1617        diag::warn_integer_constant_overflow)
1618          << Result.toString(10) << E->getType();
1619    else
1620      HandleOverflow(Info, E, Value, E->getType());
1621  }
1622  return Result;
1623}
1624
1625/// Perform the given binary integer operation.
1626static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1627                              BinaryOperatorKind Opcode, APSInt RHS,
1628                              APSInt &Result) {
1629  switch (Opcode) {
1630  default:
1631    Info.Diag(E);
1632    return false;
1633  case BO_Mul:
1634    Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1635                                  std::multiplies<APSInt>());
1636    return true;
1637  case BO_Add:
1638    Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1639                                  std::plus<APSInt>());
1640    return true;
1641  case BO_Sub:
1642    Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1643                                  std::minus<APSInt>());
1644    return true;
1645  case BO_And: Result = LHS & RHS; return true;
1646  case BO_Xor: Result = LHS ^ RHS; return true;
1647  case BO_Or:  Result = LHS | RHS; return true;
1648  case BO_Div:
1649  case BO_Rem:
1650    if (RHS == 0) {
1651      Info.Diag(E, diag::note_expr_divide_by_zero);
1652      return false;
1653    }
1654    // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1655    if (RHS.isNegative() && RHS.isAllOnesValue() &&
1656        LHS.isSigned() && LHS.isMinSignedValue())
1657      HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1658    Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1659    return true;
1660  case BO_Shl: {
1661    if (Info.getLangOpts().OpenCL)
1662      // OpenCL 6.3j: shift values are effectively % word size of LHS.
1663      RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1664                    static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1665                    RHS.isUnsigned());
1666    else if (RHS.isSigned() && RHS.isNegative()) {
1667      // During constant-folding, a negative shift is an opposite shift. Such
1668      // a shift is not a constant expression.
1669      Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1670      RHS = -RHS;
1671      goto shift_right;
1672    }
1673  shift_left:
1674    // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1675    // the shifted type.
1676    unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1677    if (SA != RHS) {
1678      Info.CCEDiag(E, diag::note_constexpr_large_shift)
1679        << RHS << E->getType() << LHS.getBitWidth();
1680    } else if (LHS.isSigned()) {
1681      // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1682      // operand, and must not overflow the corresponding unsigned type.
1683      if (LHS.isNegative())
1684        Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1685      else if (LHS.countLeadingZeros() < SA)
1686        Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1687    }
1688    Result = LHS << SA;
1689    return true;
1690  }
1691  case BO_Shr: {
1692    if (Info.getLangOpts().OpenCL)
1693      // OpenCL 6.3j: shift values are effectively % word size of LHS.
1694      RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1695                    static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1696                    RHS.isUnsigned());
1697    else if (RHS.isSigned() && RHS.isNegative()) {
1698      // During constant-folding, a negative shift is an opposite shift. Such a
1699      // shift is not a constant expression.
1700      Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1701      RHS = -RHS;
1702      goto shift_left;
1703    }
1704  shift_right:
1705    // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1706    // shifted type.
1707    unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1708    if (SA != RHS)
1709      Info.CCEDiag(E, diag::note_constexpr_large_shift)
1710        << RHS << E->getType() << LHS.getBitWidth();
1711    Result = LHS >> SA;
1712    return true;
1713  }
1714
1715  case BO_LT: Result = LHS < RHS; return true;
1716  case BO_GT: Result = LHS > RHS; return true;
1717  case BO_LE: Result = LHS <= RHS; return true;
1718  case BO_GE: Result = LHS >= RHS; return true;
1719  case BO_EQ: Result = LHS == RHS; return true;
1720  case BO_NE: Result = LHS != RHS; return true;
1721  }
1722}
1723
1724/// Perform the given binary floating-point operation, in-place, on LHS.
1725static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1726                                  APFloat &LHS, BinaryOperatorKind Opcode,
1727                                  const APFloat &RHS) {
1728  switch (Opcode) {
1729  default:
1730    Info.Diag(E);
1731    return false;
1732  case BO_Mul:
1733    LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1734    break;
1735  case BO_Add:
1736    LHS.add(RHS, APFloat::rmNearestTiesToEven);
1737    break;
1738  case BO_Sub:
1739    LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1740    break;
1741  case BO_Div:
1742    LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1743    break;
1744  }
1745
1746  if (LHS.isInfinity() || LHS.isNaN())
1747    Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1748  return true;
1749}
1750
1751/// Cast an lvalue referring to a base subobject to a derived class, by
1752/// truncating the lvalue's path to the given length.
1753static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1754                               const RecordDecl *TruncatedType,
1755                               unsigned TruncatedElements) {
1756  SubobjectDesignator &D = Result.Designator;
1757
1758  // Check we actually point to a derived class object.
1759  if (TruncatedElements == D.Entries.size())
1760    return true;
1761  assert(TruncatedElements >= D.MostDerivedPathLength &&
1762         "not casting to a derived class");
1763  if (!Result.checkSubobject(Info, E, CSK_Derived))
1764    return false;
1765
1766  // Truncate the path to the subobject, and remove any derived-to-base offsets.
1767  const RecordDecl *RD = TruncatedType;
1768  for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
1769    if (RD->isInvalidDecl()) return false;
1770    const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1771    const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
1772    if (isVirtualBaseClass(D.Entries[I]))
1773      Result.Offset -= Layout.getVBaseClassOffset(Base);
1774    else
1775      Result.Offset -= Layout.getBaseClassOffset(Base);
1776    RD = Base;
1777  }
1778  D.Entries.resize(TruncatedElements);
1779  return true;
1780}
1781
1782static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1783                                   const CXXRecordDecl *Derived,
1784                                   const CXXRecordDecl *Base,
1785                                   const ASTRecordLayout *RL = nullptr) {
1786  if (!RL) {
1787    if (Derived->isInvalidDecl()) return false;
1788    RL = &Info.Ctx.getASTRecordLayout(Derived);
1789  }
1790
1791  Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1792  Obj.addDecl(Info, E, Base, /*Virtual*/ false);
1793  return true;
1794}
1795
1796static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1797                             const CXXRecordDecl *DerivedDecl,
1798                             const CXXBaseSpecifier *Base) {
1799  const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1800
1801  if (!Base->isVirtual())
1802    return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
1803
1804  SubobjectDesignator &D = Obj.Designator;
1805  if (D.Invalid)
1806    return false;
1807
1808  // Extract most-derived object and corresponding type.
1809  DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1810  if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1811    return false;
1812
1813  // Find the virtual base class.
1814  if (DerivedDecl->isInvalidDecl()) return false;
1815  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1816  Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1817  Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
1818  return true;
1819}
1820
1821static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1822                                 QualType Type, LValue &Result) {
1823  for (CastExpr::path_const_iterator PathI = E->path_begin(),
1824                                     PathE = E->path_end();
1825       PathI != PathE; ++PathI) {
1826    if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1827                          *PathI))
1828      return false;
1829    Type = (*PathI)->getType();
1830  }
1831  return true;
1832}
1833
1834/// Update LVal to refer to the given field, which must be a member of the type
1835/// currently described by LVal.
1836static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
1837                               const FieldDecl *FD,
1838                               const ASTRecordLayout *RL = nullptr) {
1839  if (!RL) {
1840    if (FD->getParent()->isInvalidDecl()) return false;
1841    RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1842  }
1843
1844  unsigned I = FD->getFieldIndex();
1845  LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1846  LVal.addDecl(Info, E, FD);
1847  return true;
1848}
1849
1850/// Update LVal to refer to the given indirect field.
1851static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1852                                       LValue &LVal,
1853                                       const IndirectFieldDecl *IFD) {
1854  for (const auto *C : IFD->chain())
1855    if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
1856      return false;
1857  return true;
1858}
1859
1860/// Get the size of the given type in char units.
1861static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1862                         QualType Type, CharUnits &Size) {
1863  // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1864  // extension.
1865  if (Type->isVoidType() || Type->isFunctionType()) {
1866    Size = CharUnits::One();
1867    return true;
1868  }
1869
1870  if (!Type->isConstantSizeType()) {
1871    // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1872    // FIXME: Better diagnostic.
1873    Info.Diag(Loc);
1874    return false;
1875  }
1876
1877  Size = Info.Ctx.getTypeSizeInChars(Type);
1878  return true;
1879}
1880
1881/// Update a pointer value to model pointer arithmetic.
1882/// \param Info - Information about the ongoing evaluation.
1883/// \param E - The expression being evaluated, for diagnostic purposes.
1884/// \param LVal - The pointer value to be updated.
1885/// \param EltTy - The pointee type represented by LVal.
1886/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1887static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1888                                        LValue &LVal, QualType EltTy,
1889                                        int64_t Adjustment) {
1890  CharUnits SizeOfPointee;
1891  if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
1892    return false;
1893
1894  // Compute the new offset in the appropriate width.
1895  LVal.Offset += Adjustment * SizeOfPointee;
1896  LVal.adjustIndex(Info, E, Adjustment);
1897  return true;
1898}
1899
1900/// Update an lvalue to refer to a component of a complex number.
1901/// \param Info - Information about the ongoing evaluation.
1902/// \param LVal - The lvalue to be updated.
1903/// \param EltTy - The complex number's component type.
1904/// \param Imag - False for the real component, true for the imaginary.
1905static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1906                                       LValue &LVal, QualType EltTy,
1907                                       bool Imag) {
1908  if (Imag) {
1909    CharUnits SizeOfComponent;
1910    if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1911      return false;
1912    LVal.Offset += SizeOfComponent;
1913  }
1914  LVal.addComplex(Info, E, EltTy, Imag);
1915  return true;
1916}
1917
1918/// Try to evaluate the initializer for a variable declaration.
1919///
1920/// \param Info   Information about the ongoing evaluation.
1921/// \param E      An expression to be used when printing diagnostics.
1922/// \param VD     The variable whose initializer should be obtained.
1923/// \param Frame  The frame in which the variable was created. Must be null
1924///               if this variable is not local to the evaluation.
1925/// \param Result Filled in with a pointer to the value of the variable.
1926static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1927                                const VarDecl *VD, CallStackFrame *Frame,
1928                                APValue *&Result) {
1929  // If this is a parameter to an active constexpr function call, perform
1930  // argument substitution.
1931  if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
1932    // Assume arguments of a potential constant expression are unknown
1933    // constant expressions.
1934    if (Info.checkingPotentialConstantExpression())
1935      return false;
1936    if (!Frame || !Frame->Arguments) {
1937      Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1938      return false;
1939    }
1940    Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
1941    return true;
1942  }
1943
1944  // If this is a local variable, dig out its value.
1945  if (Frame) {
1946    Result = Frame->getTemporary(VD);
1947    assert(Result && "missing value for local variable");
1948    return true;
1949  }
1950
1951  // Dig out the initializer, and use the declaration which it's attached to.
1952  const Expr *Init = VD->getAnyInitializer(VD);
1953  if (!Init || Init->isValueDependent()) {
1954    // If we're checking a potential constant expression, the variable could be
1955    // initialized later.
1956    if (!Info.checkingPotentialConstantExpression())
1957      Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1958    return false;
1959  }
1960
1961  // If we're currently evaluating the initializer of this declaration, use that
1962  // in-flight value.
1963  if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
1964    Result = Info.EvaluatingDeclValue;
1965    return true;
1966  }
1967
1968  // Never evaluate the initializer of a weak variable. We can't be sure that
1969  // this is the definition which will be used.
1970  if (VD->isWeak()) {
1971    Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1972    return false;
1973  }
1974
1975  // Check that we can fold the initializer. In C++, we will have already done
1976  // this in the cases where it matters for conformance.
1977  SmallVector<PartialDiagnosticAt, 8> Notes;
1978  if (!VD->evaluateValue(Notes)) {
1979    Info.Diag(E, diag::note_constexpr_var_init_non_constant,
1980              Notes.size() + 1) << VD;
1981    Info.Note(VD->getLocation(), diag::note_declared_at);
1982    Info.addNotes(Notes);
1983    return false;
1984  } else if (!VD->checkInitIsICE()) {
1985    Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
1986                 Notes.size() + 1) << VD;
1987    Info.Note(VD->getLocation(), diag::note_declared_at);
1988    Info.addNotes(Notes);
1989  }
1990
1991  Result = VD->getEvaluatedValue();
1992  return true;
1993}
1994
1995static bool IsConstNonVolatile(QualType T) {
1996  Qualifiers Quals = T.getQualifiers();
1997  return Quals.hasConst() && !Quals.hasVolatile();
1998}
1999
2000/// Get the base index of the given base class within an APValue representing
2001/// the given derived class.
2002static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2003                             const CXXRecordDecl *Base) {
2004  Base = Base->getCanonicalDecl();
2005  unsigned Index = 0;
2006  for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2007         E = Derived->bases_end(); I != E; ++I, ++Index) {
2008    if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2009      return Index;
2010  }
2011
2012  llvm_unreachable("base class missing from derived class's bases list");
2013}
2014
2015/// Extract the value of a character from a string literal.
2016static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2017                                            uint64_t Index) {
2018  // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2019  const StringLiteral *S = cast<StringLiteral>(Lit);
2020  const ConstantArrayType *CAT =
2021      Info.Ctx.getAsConstantArrayType(S->getType());
2022  assert(CAT && "string literal isn't an array");
2023  QualType CharType = CAT->getElementType();
2024  assert(CharType->isIntegerType() && "unexpected character type");
2025
2026  APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2027               CharType->isUnsignedIntegerType());
2028  if (Index < S->getLength())
2029    Value = S->getCodeUnit(Index);
2030  return Value;
2031}
2032
2033// Expand a string literal into an array of characters.
2034static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2035                                APValue &Result) {
2036  const StringLiteral *S = cast<StringLiteral>(Lit);
2037  const ConstantArrayType *CAT =
2038      Info.Ctx.getAsConstantArrayType(S->getType());
2039  assert(CAT && "string literal isn't an array");
2040  QualType CharType = CAT->getElementType();
2041  assert(CharType->isIntegerType() && "unexpected character type");
2042
2043  unsigned Elts = CAT->getSize().getZExtValue();
2044  Result = APValue(APValue::UninitArray(),
2045                   std::min(S->getLength(), Elts), Elts);
2046  APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2047               CharType->isUnsignedIntegerType());
2048  if (Result.hasArrayFiller())
2049    Result.getArrayFiller() = APValue(Value);
2050  for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2051    Value = S->getCodeUnit(I);
2052    Result.getArrayInitializedElt(I) = APValue(Value);
2053  }
2054}
2055
2056// Expand an array so that it has more than Index filled elements.
2057static void expandArray(APValue &Array, unsigned Index) {
2058  unsigned Size = Array.getArraySize();
2059  assert(Index < Size);
2060
2061  // Always at least double the number of elements for which we store a value.
2062  unsigned OldElts = Array.getArrayInitializedElts();
2063  unsigned NewElts = std::max(Index+1, OldElts * 2);
2064  NewElts = std::min(Size, std::max(NewElts, 8u));
2065
2066  // Copy the data across.
2067  APValue NewValue(APValue::UninitArray(), NewElts, Size);
2068  for (unsigned I = 0; I != OldElts; ++I)
2069    NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2070  for (unsigned I = OldElts; I != NewElts; ++I)
2071    NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2072  if (NewValue.hasArrayFiller())
2073    NewValue.getArrayFiller() = Array.getArrayFiller();
2074  Array.swap(NewValue);
2075}
2076
2077/// Kinds of access we can perform on an object, for diagnostics.
2078enum AccessKinds {
2079  AK_Read,
2080  AK_Assign,
2081  AK_Increment,
2082  AK_Decrement
2083};
2084
2085/// A handle to a complete object (an object that is not a subobject of
2086/// another object).
2087struct CompleteObject {
2088  /// The value of the complete object.
2089  APValue *Value;
2090  /// The type of the complete object.
2091  QualType Type;
2092
2093  CompleteObject() : Value(nullptr) {}
2094  CompleteObject(APValue *Value, QualType Type)
2095      : Value(Value), Type(Type) {
2096    assert(Value && "missing value for complete object");
2097  }
2098
2099  LLVM_EXPLICIT operator bool() const { return Value; }
2100};
2101
2102/// Find the designated sub-object of an rvalue.
2103template<typename SubobjectHandler>
2104typename SubobjectHandler::result_type
2105findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2106              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2107  if (Sub.Invalid)
2108    // A diagnostic will have already been produced.
2109    return handler.failed();
2110  if (Sub.isOnePastTheEnd()) {
2111    if (Info.getLangOpts().CPlusPlus11)
2112      Info.Diag(E, diag::note_constexpr_access_past_end)
2113        << handler.AccessKind;
2114    else
2115      Info.Diag(E);
2116    return handler.failed();
2117  }
2118
2119  APValue *O = Obj.Value;
2120  QualType ObjType = Obj.Type;
2121  const FieldDecl *LastField = nullptr;
2122
2123  // Walk the designator's path to find the subobject.
2124  for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2125    if (O->isUninit()) {
2126      if (!Info.checkingPotentialConstantExpression())
2127        Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2128      return handler.failed();
2129    }
2130
2131    if (I == N) {
2132      if (!handler.found(*O, ObjType))
2133        return false;
2134
2135      // If we modified a bit-field, truncate it to the right width.
2136      if (handler.AccessKind != AK_Read &&
2137          LastField && LastField->isBitField() &&
2138          !truncateBitfieldValue(Info, E, *O, LastField))
2139        return false;
2140
2141      return true;
2142    }
2143
2144    LastField = nullptr;
2145    if (ObjType->isArrayType()) {
2146      // Next subobject is an array element.
2147      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2148      assert(CAT && "vla in literal type?");
2149      uint64_t Index = Sub.Entries[I].ArrayIndex;
2150      if (CAT->getSize().ule(Index)) {
2151        // Note, it should not be possible to form a pointer with a valid
2152        // designator which points more than one past the end of the array.
2153        if (Info.getLangOpts().CPlusPlus11)
2154          Info.Diag(E, diag::note_constexpr_access_past_end)
2155            << handler.AccessKind;
2156        else
2157          Info.Diag(E);
2158        return handler.failed();
2159      }
2160
2161      ObjType = CAT->getElementType();
2162
2163      // An array object is represented as either an Array APValue or as an
2164      // LValue which refers to a string literal.
2165      if (O->isLValue()) {
2166        assert(I == N - 1 && "extracting subobject of character?");
2167        assert(!O->hasLValuePath() || O->getLValuePath().empty());
2168        if (handler.AccessKind != AK_Read)
2169          expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2170                              *O);
2171        else
2172          return handler.foundString(*O, ObjType, Index);
2173      }
2174
2175      if (O->getArrayInitializedElts() > Index)
2176        O = &O->getArrayInitializedElt(Index);
2177      else if (handler.AccessKind != AK_Read) {
2178        expandArray(*O, Index);
2179        O = &O->getArrayInitializedElt(Index);
2180      } else
2181        O = &O->getArrayFiller();
2182    } else if (ObjType->isAnyComplexType()) {
2183      // Next subobject is a complex number.
2184      uint64_t Index = Sub.Entries[I].ArrayIndex;
2185      if (Index > 1) {
2186        if (Info.getLangOpts().CPlusPlus11)
2187          Info.Diag(E, diag::note_constexpr_access_past_end)
2188            << handler.AccessKind;
2189        else
2190          Info.Diag(E);
2191        return handler.failed();
2192      }
2193
2194      bool WasConstQualified = ObjType.isConstQualified();
2195      ObjType = ObjType->castAs<ComplexType>()->getElementType();
2196      if (WasConstQualified)
2197        ObjType.addConst();
2198
2199      assert(I == N - 1 && "extracting subobject of scalar?");
2200      if (O->isComplexInt()) {
2201        return handler.found(Index ? O->getComplexIntImag()
2202                                   : O->getComplexIntReal(), ObjType);
2203      } else {
2204        assert(O->isComplexFloat());
2205        return handler.found(Index ? O->getComplexFloatImag()
2206                                   : O->getComplexFloatReal(), ObjType);
2207      }
2208    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2209      if (Field->isMutable() && handler.AccessKind == AK_Read) {
2210        Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
2211          << Field;
2212        Info.Note(Field->getLocation(), diag::note_declared_at);
2213        return handler.failed();
2214      }
2215
2216      // Next subobject is a class, struct or union field.
2217      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2218      if (RD->isUnion()) {
2219        const FieldDecl *UnionField = O->getUnionField();
2220        if (!UnionField ||
2221            UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2222          Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2223            << handler.AccessKind << Field << !UnionField << UnionField;
2224          return handler.failed();
2225        }
2226        O = &O->getUnionValue();
2227      } else
2228        O = &O->getStructField(Field->getFieldIndex());
2229
2230      bool WasConstQualified = ObjType.isConstQualified();
2231      ObjType = Field->getType();
2232      if (WasConstQualified && !Field->isMutable())
2233        ObjType.addConst();
2234
2235      if (ObjType.isVolatileQualified()) {
2236        if (Info.getLangOpts().CPlusPlus) {
2237          // FIXME: Include a description of the path to the volatile subobject.
2238          Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2239            << handler.AccessKind << 2 << Field;
2240          Info.Note(Field->getLocation(), diag::note_declared_at);
2241        } else {
2242          Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
2243        }
2244        return handler.failed();
2245      }
2246
2247      LastField = Field;
2248    } else {
2249      // Next subobject is a base class.
2250      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2251      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2252      O = &O->getStructBase(getBaseIndex(Derived, Base));
2253
2254      bool WasConstQualified = ObjType.isConstQualified();
2255      ObjType = Info.Ctx.getRecordType(Base);
2256      if (WasConstQualified)
2257        ObjType.addConst();
2258    }
2259  }
2260}
2261
2262namespace {
2263struct ExtractSubobjectHandler {
2264  EvalInfo &Info;
2265  APValue &Result;
2266
2267  static const AccessKinds AccessKind = AK_Read;
2268
2269  typedef bool result_type;
2270  bool failed() { return false; }
2271  bool found(APValue &Subobj, QualType SubobjType) {
2272    Result = Subobj;
2273    return true;
2274  }
2275  bool found(APSInt &Value, QualType SubobjType) {
2276    Result = APValue(Value);
2277    return true;
2278  }
2279  bool found(APFloat &Value, QualType SubobjType) {
2280    Result = APValue(Value);
2281    return true;
2282  }
2283  bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2284    Result = APValue(extractStringLiteralCharacter(
2285        Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2286    return true;
2287  }
2288};
2289} // end anonymous namespace
2290
2291const AccessKinds ExtractSubobjectHandler::AccessKind;
2292
2293/// Extract the designated sub-object of an rvalue.
2294static bool extractSubobject(EvalInfo &Info, const Expr *E,
2295                             const CompleteObject &Obj,
2296                             const SubobjectDesignator &Sub,
2297                             APValue &Result) {
2298  ExtractSubobjectHandler Handler = { Info, Result };
2299  return findSubobject(Info, E, Obj, Sub, Handler);
2300}
2301
2302namespace {
2303struct ModifySubobjectHandler {
2304  EvalInfo &Info;
2305  APValue &NewVal;
2306  const Expr *E;
2307
2308  typedef bool result_type;
2309  static const AccessKinds AccessKind = AK_Assign;
2310
2311  bool checkConst(QualType QT) {
2312    // Assigning to a const object has undefined behavior.
2313    if (QT.isConstQualified()) {
2314      Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2315      return false;
2316    }
2317    return true;
2318  }
2319
2320  bool failed() { return false; }
2321  bool found(APValue &Subobj, QualType SubobjType) {
2322    if (!checkConst(SubobjType))
2323      return false;
2324    // We've been given ownership of NewVal, so just swap it in.
2325    Subobj.swap(NewVal);
2326    return true;
2327  }
2328  bool found(APSInt &Value, QualType SubobjType) {
2329    if (!checkConst(SubobjType))
2330      return false;
2331    if (!NewVal.isInt()) {
2332      // Maybe trying to write a cast pointer value into a complex?
2333      Info.Diag(E);
2334      return false;
2335    }
2336    Value = NewVal.getInt();
2337    return true;
2338  }
2339  bool found(APFloat &Value, QualType SubobjType) {
2340    if (!checkConst(SubobjType))
2341      return false;
2342    Value = NewVal.getFloat();
2343    return true;
2344  }
2345  bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2346    llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2347  }
2348};
2349} // end anonymous namespace
2350
2351const AccessKinds ModifySubobjectHandler::AccessKind;
2352
2353/// Update the designated sub-object of an rvalue to the given value.
2354static bool modifySubobject(EvalInfo &Info, const Expr *E,
2355                            const CompleteObject &Obj,
2356                            const SubobjectDesignator &Sub,
2357                            APValue &NewVal) {
2358  ModifySubobjectHandler Handler = { Info, NewVal, E };
2359  return findSubobject(Info, E, Obj, Sub, Handler);
2360}
2361
2362/// Find the position where two subobject designators diverge, or equivalently
2363/// the length of the common initial subsequence.
2364static unsigned FindDesignatorMismatch(QualType ObjType,
2365                                       const SubobjectDesignator &A,
2366                                       const SubobjectDesignator &B,
2367                                       bool &WasArrayIndex) {
2368  unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2369  for (/**/; I != N; ++I) {
2370    if (!ObjType.isNull() &&
2371        (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2372      // Next subobject is an array element.
2373      if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2374        WasArrayIndex = true;
2375        return I;
2376      }
2377      if (ObjType->isAnyComplexType())
2378        ObjType = ObjType->castAs<ComplexType>()->getElementType();
2379      else
2380        ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2381    } else {
2382      if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2383        WasArrayIndex = false;
2384        return I;
2385      }
2386      if (const FieldDecl *FD = getAsField(A.Entries[I]))
2387        // Next subobject is a field.
2388        ObjType = FD->getType();
2389      else
2390        // Next subobject is a base class.
2391        ObjType = QualType();
2392    }
2393  }
2394  WasArrayIndex = false;
2395  return I;
2396}
2397
2398/// Determine whether the given subobject designators refer to elements of the
2399/// same array object.
2400static bool AreElementsOfSameArray(QualType ObjType,
2401                                   const SubobjectDesignator &A,
2402                                   const SubobjectDesignator &B) {
2403  if (A.Entries.size() != B.Entries.size())
2404    return false;
2405
2406  bool IsArray = A.MostDerivedArraySize != 0;
2407  if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2408    // A is a subobject of the array element.
2409    return false;
2410
2411  // If A (and B) designates an array element, the last entry will be the array
2412  // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2413  // of length 1' case, and the entire path must match.
2414  bool WasArrayIndex;
2415  unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2416  return CommonLength >= A.Entries.size() - IsArray;
2417}
2418
2419/// Find the complete object to which an LValue refers.
2420CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2421                                  const LValue &LVal, QualType LValType) {
2422  if (!LVal.Base) {
2423    Info.Diag(E, diag::note_constexpr_access_null) << AK;
2424    return CompleteObject();
2425  }
2426
2427  CallStackFrame *Frame = nullptr;
2428  if (LVal.CallIndex) {
2429    Frame = Info.getCallFrame(LVal.CallIndex);
2430    if (!Frame) {
2431      Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2432        << AK << LVal.Base.is<const ValueDecl*>();
2433      NoteLValueLocation(Info, LVal.Base);
2434      return CompleteObject();
2435    }
2436  }
2437
2438  // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2439  // is not a constant expression (even if the object is non-volatile). We also
2440  // apply this rule to C++98, in order to conform to the expected 'volatile'
2441  // semantics.
2442  if (LValType.isVolatileQualified()) {
2443    if (Info.getLangOpts().CPlusPlus)
2444      Info.Diag(E, diag::note_constexpr_access_volatile_type)
2445        << AK << LValType;
2446    else
2447      Info.Diag(E);
2448    return CompleteObject();
2449  }
2450
2451  // Compute value storage location and type of base object.
2452  APValue *BaseVal = nullptr;
2453  QualType BaseType = getType(LVal.Base);
2454
2455  if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2456    // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2457    // In C++11, constexpr, non-volatile variables initialized with constant
2458    // expressions are constant expressions too. Inside constexpr functions,
2459    // parameters are constant expressions even if they're non-const.
2460    // In C++1y, objects local to a constant expression (those with a Frame) are
2461    // both readable and writable inside constant expressions.
2462    // In C, such things can also be folded, although they are not ICEs.
2463    const VarDecl *VD = dyn_cast<VarDecl>(D);
2464    if (VD) {
2465      if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2466        VD = VDef;
2467    }
2468    if (!VD || VD->isInvalidDecl()) {
2469      Info.Diag(E);
2470      return CompleteObject();
2471    }
2472
2473    // Accesses of volatile-qualified objects are not allowed.
2474    if (BaseType.isVolatileQualified()) {
2475      if (Info.getLangOpts().CPlusPlus) {
2476        Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2477          << AK << 1 << VD;
2478        Info.Note(VD->getLocation(), diag::note_declared_at);
2479      } else {
2480        Info.Diag(E);
2481      }
2482      return CompleteObject();
2483    }
2484
2485    // Unless we're looking at a local variable or argument in a constexpr call,
2486    // the variable we're reading must be const.
2487    if (!Frame) {
2488      if (Info.getLangOpts().CPlusPlus1y &&
2489          VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2490        // OK, we can read and modify an object if we're in the process of
2491        // evaluating its initializer, because its lifetime began in this
2492        // evaluation.
2493      } else if (AK != AK_Read) {
2494        // All the remaining cases only permit reading.
2495        Info.Diag(E, diag::note_constexpr_modify_global);
2496        return CompleteObject();
2497      } else if (VD->isConstexpr()) {
2498        // OK, we can read this variable.
2499      } else if (BaseType->isIntegralOrEnumerationType()) {
2500        if (!BaseType.isConstQualified()) {
2501          if (Info.getLangOpts().CPlusPlus) {
2502            Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2503            Info.Note(VD->getLocation(), diag::note_declared_at);
2504          } else {
2505            Info.Diag(E);
2506          }
2507          return CompleteObject();
2508        }
2509      } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2510        // We support folding of const floating-point types, in order to make
2511        // static const data members of such types (supported as an extension)
2512        // more useful.
2513        if (Info.getLangOpts().CPlusPlus11) {
2514          Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2515          Info.Note(VD->getLocation(), diag::note_declared_at);
2516        } else {
2517          Info.CCEDiag(E);
2518        }
2519      } else {
2520        // FIXME: Allow folding of values of any literal type in all languages.
2521        if (Info.getLangOpts().CPlusPlus11) {
2522          Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2523          Info.Note(VD->getLocation(), diag::note_declared_at);
2524        } else {
2525          Info.Diag(E);
2526        }
2527        return CompleteObject();
2528      }
2529    }
2530
2531    if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2532      return CompleteObject();
2533  } else {
2534    const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2535
2536    if (!Frame) {
2537      if (const MaterializeTemporaryExpr *MTE =
2538              dyn_cast<MaterializeTemporaryExpr>(Base)) {
2539        assert(MTE->getStorageDuration() == SD_Static &&
2540               "should have a frame for a non-global materialized temporary");
2541
2542        // Per C++1y [expr.const]p2:
2543        //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2544        //   - a [...] glvalue of integral or enumeration type that refers to
2545        //     a non-volatile const object [...]
2546        //   [...]
2547        //   - a [...] glvalue of literal type that refers to a non-volatile
2548        //     object whose lifetime began within the evaluation of e.
2549        //
2550        // C++11 misses the 'began within the evaluation of e' check and
2551        // instead allows all temporaries, including things like:
2552        //   int &&r = 1;
2553        //   int x = ++r;
2554        //   constexpr int k = r;
2555        // Therefore we use the C++1y rules in C++11 too.
2556        const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2557        const ValueDecl *ED = MTE->getExtendingDecl();
2558        if (!(BaseType.isConstQualified() &&
2559              BaseType->isIntegralOrEnumerationType()) &&
2560            !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2561          Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2562          Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2563          return CompleteObject();
2564        }
2565
2566        BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2567        assert(BaseVal && "got reference to unevaluated temporary");
2568      } else {
2569        Info.Diag(E);
2570        return CompleteObject();
2571      }
2572    } else {
2573      BaseVal = Frame->getTemporary(Base);
2574      assert(BaseVal && "missing value for temporary");
2575    }
2576
2577    // Volatile temporary objects cannot be accessed in constant expressions.
2578    if (BaseType.isVolatileQualified()) {
2579      if (Info.getLangOpts().CPlusPlus) {
2580        Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2581          << AK << 0;
2582        Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2583      } else {
2584        Info.Diag(E);
2585      }
2586      return CompleteObject();
2587    }
2588  }
2589
2590  // During the construction of an object, it is not yet 'const'.
2591  // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2592  // and this doesn't do quite the right thing for const subobjects of the
2593  // object under construction.
2594  if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2595    BaseType = Info.Ctx.getCanonicalType(BaseType);
2596    BaseType.removeLocalConst();
2597  }
2598
2599  // In C++1y, we can't safely access any mutable state when we might be
2600  // evaluating after an unmodeled side effect or an evaluation failure.
2601  //
2602  // FIXME: Not all local state is mutable. Allow local constant subobjects
2603  // to be read here (but take care with 'mutable' fields).
2604  if (Frame && Info.getLangOpts().CPlusPlus1y &&
2605      (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
2606    return CompleteObject();
2607
2608  return CompleteObject(BaseVal, BaseType);
2609}
2610
2611/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2612/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2613/// glvalue referred to by an entity of reference type.
2614///
2615/// \param Info - Information about the ongoing evaluation.
2616/// \param Conv - The expression for which we are performing the conversion.
2617///               Used for diagnostics.
2618/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2619///               case of a non-class type).
2620/// \param LVal - The glvalue on which we are attempting to perform this action.
2621/// \param RVal - The produced value will be placed here.
2622static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2623                                           QualType Type,
2624                                           const LValue &LVal, APValue &RVal) {
2625  if (LVal.Designator.Invalid)
2626    return false;
2627
2628  // Check for special cases where there is no existing APValue to look at.
2629  const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2630  if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2631      !Type.isVolatileQualified()) {
2632    if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2633      // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2634      // initializer until now for such expressions. Such an expression can't be
2635      // an ICE in C, so this only matters for fold.
2636      assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2637      if (Type.isVolatileQualified()) {
2638        Info.Diag(Conv);
2639        return false;
2640      }
2641      APValue Lit;
2642      if (!Evaluate(Lit, Info, CLE->getInitializer()))
2643        return false;
2644      CompleteObject LitObj(&Lit, Base->getType());
2645      return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2646    } else if (isa<StringLiteral>(Base)) {
2647      // We represent a string literal array as an lvalue pointing at the
2648      // corresponding expression, rather than building an array of chars.
2649      // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2650      APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2651      CompleteObject StrObj(&Str, Base->getType());
2652      return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
2653    }
2654  }
2655
2656  CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2657  return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
2658}
2659
2660/// Perform an assignment of Val to LVal. Takes ownership of Val.
2661static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
2662                             QualType LValType, APValue &Val) {
2663  if (LVal.Designator.Invalid)
2664    return false;
2665
2666  if (!Info.getLangOpts().CPlusPlus1y) {
2667    Info.Diag(E);
2668    return false;
2669  }
2670
2671  CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2672  return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
2673}
2674
2675static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2676  return T->isSignedIntegerType() &&
2677         Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2678}
2679
2680namespace {
2681struct CompoundAssignSubobjectHandler {
2682  EvalInfo &Info;
2683  const Expr *E;
2684  QualType PromotedLHSType;
2685  BinaryOperatorKind Opcode;
2686  const APValue &RHS;
2687
2688  static const AccessKinds AccessKind = AK_Assign;
2689
2690  typedef bool result_type;
2691
2692  bool checkConst(QualType QT) {
2693    // Assigning to a const object has undefined behavior.
2694    if (QT.isConstQualified()) {
2695      Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2696      return false;
2697    }
2698    return true;
2699  }
2700
2701  bool failed() { return false; }
2702  bool found(APValue &Subobj, QualType SubobjType) {
2703    switch (Subobj.getKind()) {
2704    case APValue::Int:
2705      return found(Subobj.getInt(), SubobjType);
2706    case APValue::Float:
2707      return found(Subobj.getFloat(), SubobjType);
2708    case APValue::ComplexInt:
2709    case APValue::ComplexFloat:
2710      // FIXME: Implement complex compound assignment.
2711      Info.Diag(E);
2712      return false;
2713    case APValue::LValue:
2714      return foundPointer(Subobj, SubobjType);
2715    default:
2716      // FIXME: can this happen?
2717      Info.Diag(E);
2718      return false;
2719    }
2720  }
2721  bool found(APSInt &Value, QualType SubobjType) {
2722    if (!checkConst(SubobjType))
2723      return false;
2724
2725    if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2726      // We don't support compound assignment on integer-cast-to-pointer
2727      // values.
2728      Info.Diag(E);
2729      return false;
2730    }
2731
2732    APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2733                                    SubobjType, Value);
2734    if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2735      return false;
2736    Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2737    return true;
2738  }
2739  bool found(APFloat &Value, QualType SubobjType) {
2740    return checkConst(SubobjType) &&
2741           HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2742                                  Value) &&
2743           handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2744           HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
2745  }
2746  bool foundPointer(APValue &Subobj, QualType SubobjType) {
2747    if (!checkConst(SubobjType))
2748      return false;
2749
2750    QualType PointeeType;
2751    if (const PointerType *PT = SubobjType->getAs<PointerType>())
2752      PointeeType = PT->getPointeeType();
2753
2754    if (PointeeType.isNull() || !RHS.isInt() ||
2755        (Opcode != BO_Add && Opcode != BO_Sub)) {
2756      Info.Diag(E);
2757      return false;
2758    }
2759
2760    int64_t Offset = getExtValue(RHS.getInt());
2761    if (Opcode == BO_Sub)
2762      Offset = -Offset;
2763
2764    LValue LVal;
2765    LVal.setFrom(Info.Ctx, Subobj);
2766    if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2767      return false;
2768    LVal.moveInto(Subobj);
2769    return true;
2770  }
2771  bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2772    llvm_unreachable("shouldn't encounter string elements here");
2773  }
2774};
2775} // end anonymous namespace
2776
2777const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2778
2779/// Perform a compound assignment of LVal <op>= RVal.
2780static bool handleCompoundAssignment(
2781    EvalInfo &Info, const Expr *E,
2782    const LValue &LVal, QualType LValType, QualType PromotedLValType,
2783    BinaryOperatorKind Opcode, const APValue &RVal) {
2784  if (LVal.Designator.Invalid)
2785    return false;
2786
2787  if (!Info.getLangOpts().CPlusPlus1y) {
2788    Info.Diag(E);
2789    return false;
2790  }
2791
2792  CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2793  CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2794                                             RVal };
2795  return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2796}
2797
2798namespace {
2799struct IncDecSubobjectHandler {
2800  EvalInfo &Info;
2801  const Expr *E;
2802  AccessKinds AccessKind;
2803  APValue *Old;
2804
2805  typedef bool result_type;
2806
2807  bool checkConst(QualType QT) {
2808    // Assigning to a const object has undefined behavior.
2809    if (QT.isConstQualified()) {
2810      Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2811      return false;
2812    }
2813    return true;
2814  }
2815
2816  bool failed() { return false; }
2817  bool found(APValue &Subobj, QualType SubobjType) {
2818    // Stash the old value. Also clear Old, so we don't clobber it later
2819    // if we're post-incrementing a complex.
2820    if (Old) {
2821      *Old = Subobj;
2822      Old = nullptr;
2823    }
2824
2825    switch (Subobj.getKind()) {
2826    case APValue::Int:
2827      return found(Subobj.getInt(), SubobjType);
2828    case APValue::Float:
2829      return found(Subobj.getFloat(), SubobjType);
2830    case APValue::ComplexInt:
2831      return found(Subobj.getComplexIntReal(),
2832                   SubobjType->castAs<ComplexType>()->getElementType()
2833                     .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2834    case APValue::ComplexFloat:
2835      return found(Subobj.getComplexFloatReal(),
2836                   SubobjType->castAs<ComplexType>()->getElementType()
2837                     .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2838    case APValue::LValue:
2839      return foundPointer(Subobj, SubobjType);
2840    default:
2841      // FIXME: can this happen?
2842      Info.Diag(E);
2843      return false;
2844    }
2845  }
2846  bool found(APSInt &Value, QualType SubobjType) {
2847    if (!checkConst(SubobjType))
2848      return false;
2849
2850    if (!SubobjType->isIntegerType()) {
2851      // We don't support increment / decrement on integer-cast-to-pointer
2852      // values.
2853      Info.Diag(E);
2854      return false;
2855    }
2856
2857    if (Old) *Old = APValue(Value);
2858
2859    // bool arithmetic promotes to int, and the conversion back to bool
2860    // doesn't reduce mod 2^n, so special-case it.
2861    if (SubobjType->isBooleanType()) {
2862      if (AccessKind == AK_Increment)
2863        Value = 1;
2864      else
2865        Value = !Value;
2866      return true;
2867    }
2868
2869    bool WasNegative = Value.isNegative();
2870    if (AccessKind == AK_Increment) {
2871      ++Value;
2872
2873      if (!WasNegative && Value.isNegative() &&
2874          isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2875        APSInt ActualValue(Value, /*IsUnsigned*/true);
2876        HandleOverflow(Info, E, ActualValue, SubobjType);
2877      }
2878    } else {
2879      --Value;
2880
2881      if (WasNegative && !Value.isNegative() &&
2882          isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2883        unsigned BitWidth = Value.getBitWidth();
2884        APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2885        ActualValue.setBit(BitWidth);
2886        HandleOverflow(Info, E, ActualValue, SubobjType);
2887      }
2888    }
2889    return true;
2890  }
2891  bool found(APFloat &Value, QualType SubobjType) {
2892    if (!checkConst(SubobjType))
2893      return false;
2894
2895    if (Old) *Old = APValue(Value);
2896
2897    APFloat One(Value.getSemantics(), 1);
2898    if (AccessKind == AK_Increment)
2899      Value.add(One, APFloat::rmNearestTiesToEven);
2900    else
2901      Value.subtract(One, APFloat::rmNearestTiesToEven);
2902    return true;
2903  }
2904  bool foundPointer(APValue &Subobj, QualType SubobjType) {
2905    if (!checkConst(SubobjType))
2906      return false;
2907
2908    QualType PointeeType;
2909    if (const PointerType *PT = SubobjType->getAs<PointerType>())
2910      PointeeType = PT->getPointeeType();
2911    else {
2912      Info.Diag(E);
2913      return false;
2914    }
2915
2916    LValue LVal;
2917    LVal.setFrom(Info.Ctx, Subobj);
2918    if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2919                                     AccessKind == AK_Increment ? 1 : -1))
2920      return false;
2921    LVal.moveInto(Subobj);
2922    return true;
2923  }
2924  bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2925    llvm_unreachable("shouldn't encounter string elements here");
2926  }
2927};
2928} // end anonymous namespace
2929
2930/// Perform an increment or decrement on LVal.
2931static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2932                         QualType LValType, bool IsIncrement, APValue *Old) {
2933  if (LVal.Designator.Invalid)
2934    return false;
2935
2936  if (!Info.getLangOpts().CPlusPlus1y) {
2937    Info.Diag(E);
2938    return false;
2939  }
2940
2941  AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2942  CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2943  IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2944  return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2945}
2946
2947/// Build an lvalue for the object argument of a member function call.
2948static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2949                                   LValue &This) {
2950  if (Object->getType()->isPointerType())
2951    return EvaluatePointer(Object, This, Info);
2952
2953  if (Object->isGLValue())
2954    return EvaluateLValue(Object, This, Info);
2955
2956  if (Object->getType()->isLiteralType(Info.Ctx))
2957    return EvaluateTemporary(Object, This, Info);
2958
2959  Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
2960  return false;
2961}
2962
2963/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2964/// lvalue referring to the result.
2965///
2966/// \param Info - Information about the ongoing evaluation.
2967/// \param LV - An lvalue referring to the base of the member pointer.
2968/// \param RHS - The member pointer expression.
2969/// \param IncludeMember - Specifies whether the member itself is included in
2970///        the resulting LValue subobject designator. This is not possible when
2971///        creating a bound member function.
2972/// \return The field or method declaration to which the member pointer refers,
2973///         or 0 if evaluation fails.
2974static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2975                                                  QualType LVType,
2976                                                  LValue &LV,
2977                                                  const Expr *RHS,
2978                                                  bool IncludeMember = true) {
2979  MemberPtr MemPtr;
2980  if (!EvaluateMemberPointer(RHS, MemPtr, Info))
2981    return nullptr;
2982
2983  // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2984  // member value, the behavior is undefined.
2985  if (!MemPtr.getDecl()) {
2986    // FIXME: Specific diagnostic.
2987    Info.Diag(RHS);
2988    return nullptr;
2989  }
2990
2991  if (MemPtr.isDerivedMember()) {
2992    // This is a member of some derived class. Truncate LV appropriately.
2993    // The end of the derived-to-base path for the base object must match the
2994    // derived-to-base path for the member pointer.
2995    if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
2996        LV.Designator.Entries.size()) {
2997      Info.Diag(RHS);
2998      return nullptr;
2999    }
3000    unsigned PathLengthToMember =
3001        LV.Designator.Entries.size() - MemPtr.Path.size();
3002    for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3003      const CXXRecordDecl *LVDecl = getAsBaseClass(
3004          LV.Designator.Entries[PathLengthToMember + I]);
3005      const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3006      if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3007        Info.Diag(RHS);
3008        return nullptr;
3009      }
3010    }
3011
3012    // Truncate the lvalue to the appropriate derived class.
3013    if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3014                            PathLengthToMember))
3015      return nullptr;
3016  } else if (!MemPtr.Path.empty()) {
3017    // Extend the LValue path with the member pointer's path.
3018    LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3019                                  MemPtr.Path.size() + IncludeMember);
3020
3021    // Walk down to the appropriate base class.
3022    if (const PointerType *PT = LVType->getAs<PointerType>())
3023      LVType = PT->getPointeeType();
3024    const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3025    assert(RD && "member pointer access on non-class-type expression");
3026    // The first class in the path is that of the lvalue.
3027    for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3028      const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3029      if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3030        return nullptr;
3031      RD = Base;
3032    }
3033    // Finally cast to the class containing the member.
3034    if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3035                                MemPtr.getContainingRecord()))
3036      return nullptr;
3037  }
3038
3039  // Add the member. Note that we cannot build bound member functions here.
3040  if (IncludeMember) {
3041    if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3042      if (!HandleLValueMember(Info, RHS, LV, FD))
3043        return nullptr;
3044    } else if (const IndirectFieldDecl *IFD =
3045                 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3046      if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3047        return nullptr;
3048    } else {
3049      llvm_unreachable("can't construct reference to bound member function");
3050    }
3051  }
3052
3053  return MemPtr.getDecl();
3054}
3055
3056static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3057                                                  const BinaryOperator *BO,
3058                                                  LValue &LV,
3059                                                  bool IncludeMember = true) {
3060  assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3061
3062  if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3063    if (Info.keepEvaluatingAfterFailure()) {
3064      MemberPtr MemPtr;
3065      EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3066    }
3067    return nullptr;
3068  }
3069
3070  return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3071                                   BO->getRHS(), IncludeMember);
3072}
3073
3074/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3075/// the provided lvalue, which currently refers to the base object.
3076static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3077                                    LValue &Result) {
3078  SubobjectDesignator &D = Result.Designator;
3079  if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3080    return false;
3081
3082  QualType TargetQT = E->getType();
3083  if (const PointerType *PT = TargetQT->getAs<PointerType>())
3084    TargetQT = PT->getPointeeType();
3085
3086  // Check this cast lands within the final derived-to-base subobject path.
3087  if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3088    Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3089      << D.MostDerivedType << TargetQT;
3090    return false;
3091  }
3092
3093  // Check the type of the final cast. We don't need to check the path,
3094  // since a cast can only be formed if the path is unique.
3095  unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3096  const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3097  const CXXRecordDecl *FinalType;
3098  if (NewEntriesSize == D.MostDerivedPathLength)
3099    FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3100  else
3101    FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3102  if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3103    Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3104      << D.MostDerivedType << TargetQT;
3105    return false;
3106  }
3107
3108  // Truncate the lvalue to the appropriate derived class.
3109  return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3110}
3111
3112namespace {
3113enum EvalStmtResult {
3114  /// Evaluation failed.
3115  ESR_Failed,
3116  /// Hit a 'return' statement.
3117  ESR_Returned,
3118  /// Evaluation succeeded.
3119  ESR_Succeeded,
3120  /// Hit a 'continue' statement.
3121  ESR_Continue,
3122  /// Hit a 'break' statement.
3123  ESR_Break,
3124  /// Still scanning for 'case' or 'default' statement.
3125  ESR_CaseNotFound
3126};
3127}
3128
3129static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3130  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3131    // We don't need to evaluate the initializer for a static local.
3132    if (!VD->hasLocalStorage())
3133      return true;
3134
3135    LValue Result;
3136    Result.set(VD, Info.CurrentCall->Index);
3137    APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3138
3139    const Expr *InitE = VD->getInit();
3140    if (!InitE) {
3141      Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3142        << false << VD->getType();
3143      Val = APValue();
3144      return false;
3145    }
3146
3147    if (InitE->isValueDependent())
3148      return false;
3149
3150    if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3151      // Wipe out any partially-computed value, to allow tracking that this
3152      // evaluation failed.
3153      Val = APValue();
3154      return false;
3155    }
3156  }
3157
3158  return true;
3159}
3160
3161/// Evaluate a condition (either a variable declaration or an expression).
3162static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3163                         const Expr *Cond, bool &Result) {
3164  FullExpressionRAII Scope(Info);
3165  if (CondDecl && !EvaluateDecl(Info, CondDecl))
3166    return false;
3167  return EvaluateAsBooleanCondition(Cond, Result, Info);
3168}
3169
3170static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
3171                                   const Stmt *S,
3172                                   const SwitchCase *SC = nullptr);
3173
3174/// Evaluate the body of a loop, and translate the result as appropriate.
3175static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
3176                                       const Stmt *Body,
3177                                       const SwitchCase *Case = nullptr) {
3178  BlockScopeRAII Scope(Info);
3179  switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3180  case ESR_Break:
3181    return ESR_Succeeded;
3182  case ESR_Succeeded:
3183  case ESR_Continue:
3184    return ESR_Continue;
3185  case ESR_Failed:
3186  case ESR_Returned:
3187  case ESR_CaseNotFound:
3188    return ESR;
3189  }
3190  llvm_unreachable("Invalid EvalStmtResult!");
3191}
3192
3193/// Evaluate a switch statement.
3194static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3195                                     const SwitchStmt *SS) {
3196  BlockScopeRAII Scope(Info);
3197
3198  // Evaluate the switch condition.
3199  APSInt Value;
3200  {
3201    FullExpressionRAII Scope(Info);
3202    if (SS->getConditionVariable() &&
3203        !EvaluateDecl(Info, SS->getConditionVariable()))
3204      return ESR_Failed;
3205    if (!EvaluateInteger(SS->getCond(), Value, Info))
3206      return ESR_Failed;
3207  }
3208
3209  // Find the switch case corresponding to the value of the condition.
3210  // FIXME: Cache this lookup.
3211  const SwitchCase *Found = nullptr;
3212  for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3213       SC = SC->getNextSwitchCase()) {
3214    if (isa<DefaultStmt>(SC)) {
3215      Found = SC;
3216      continue;
3217    }
3218
3219    const CaseStmt *CS = cast<CaseStmt>(SC);
3220    APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3221    APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3222                              : LHS;
3223    if (LHS <= Value && Value <= RHS) {
3224      Found = SC;
3225      break;
3226    }
3227  }
3228
3229  if (!Found)
3230    return ESR_Succeeded;
3231
3232  // Search the switch body for the switch case and evaluate it from there.
3233  switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3234  case ESR_Break:
3235    return ESR_Succeeded;
3236  case ESR_Succeeded:
3237  case ESR_Continue:
3238  case ESR_Failed:
3239  case ESR_Returned:
3240    return ESR;
3241  case ESR_CaseNotFound:
3242    // This can only happen if the switch case is nested within a statement
3243    // expression. We have no intention of supporting that.
3244    Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3245    return ESR_Failed;
3246  }
3247  llvm_unreachable("Invalid EvalStmtResult!");
3248}
3249
3250// Evaluate a statement.
3251static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
3252                                   const Stmt *S, const SwitchCase *Case) {
3253  if (!Info.nextStep(S))
3254    return ESR_Failed;
3255
3256  // If we're hunting down a 'case' or 'default' label, recurse through
3257  // substatements until we hit the label.
3258  if (Case) {
3259    // FIXME: We don't start the lifetime of objects whose initialization we
3260    // jump over. However, such objects must be of class type with a trivial
3261    // default constructor that initialize all subobjects, so must be empty,
3262    // so this almost never matters.
3263    switch (S->getStmtClass()) {
3264    case Stmt::CompoundStmtClass:
3265      // FIXME: Precompute which substatement of a compound statement we
3266      // would jump to, and go straight there rather than performing a
3267      // linear scan each time.
3268    case Stmt::LabelStmtClass:
3269    case Stmt::AttributedStmtClass:
3270    case Stmt::DoStmtClass:
3271      break;
3272
3273    case Stmt::CaseStmtClass:
3274    case Stmt::DefaultStmtClass:
3275      if (Case == S)
3276        Case = nullptr;
3277      break;
3278
3279    case Stmt::IfStmtClass: {
3280      // FIXME: Precompute which side of an 'if' we would jump to, and go
3281      // straight there rather than scanning both sides.
3282      const IfStmt *IS = cast<IfStmt>(S);
3283
3284      // Wrap the evaluation in a block scope, in case it's a DeclStmt
3285      // preceded by our switch label.
3286      BlockScopeRAII Scope(Info);
3287
3288      EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3289      if (ESR != ESR_CaseNotFound || !IS->getElse())
3290        return ESR;
3291      return EvaluateStmt(Result, Info, IS->getElse(), Case);
3292    }
3293
3294    case Stmt::WhileStmtClass: {
3295      EvalStmtResult ESR =
3296          EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3297      if (ESR != ESR_Continue)
3298        return ESR;
3299      break;
3300    }
3301
3302    case Stmt::ForStmtClass: {
3303      const ForStmt *FS = cast<ForStmt>(S);
3304      EvalStmtResult ESR =
3305          EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3306      if (ESR != ESR_Continue)
3307        return ESR;
3308      if (FS->getInc()) {
3309        FullExpressionRAII IncScope(Info);
3310        if (!EvaluateIgnoredValue(Info, FS->getInc()))
3311          return ESR_Failed;
3312      }
3313      break;
3314    }
3315
3316    case Stmt::DeclStmtClass:
3317      // FIXME: If the variable has initialization that can't be jumped over,
3318      // bail out of any immediately-surrounding compound-statement too.
3319    default:
3320      return ESR_CaseNotFound;
3321    }
3322  }
3323
3324  switch (S->getStmtClass()) {
3325  default:
3326    if (const Expr *E = dyn_cast<Expr>(S)) {
3327      // Don't bother evaluating beyond an expression-statement which couldn't
3328      // be evaluated.
3329      FullExpressionRAII Scope(Info);
3330      if (!EvaluateIgnoredValue(Info, E))
3331        return ESR_Failed;
3332      return ESR_Succeeded;
3333    }
3334
3335    Info.Diag(S->getLocStart());
3336    return ESR_Failed;
3337
3338  case Stmt::NullStmtClass:
3339    return ESR_Succeeded;
3340
3341  case Stmt::DeclStmtClass: {
3342    const DeclStmt *DS = cast<DeclStmt>(S);
3343    for (const auto *DclIt : DS->decls()) {
3344      // Each declaration initialization is its own full-expression.
3345      // FIXME: This isn't quite right; if we're performing aggregate
3346      // initialization, each braced subexpression is its own full-expression.
3347      FullExpressionRAII Scope(Info);
3348      if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
3349        return ESR_Failed;
3350    }
3351    return ESR_Succeeded;
3352  }
3353
3354  case Stmt::ReturnStmtClass: {
3355    const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3356    FullExpressionRAII Scope(Info);
3357    if (RetExpr && !Evaluate(Result, Info, RetExpr))
3358      return ESR_Failed;
3359    return ESR_Returned;
3360  }
3361
3362  case Stmt::CompoundStmtClass: {
3363    BlockScopeRAII Scope(Info);
3364
3365    const CompoundStmt *CS = cast<CompoundStmt>(S);
3366    for (const auto *BI : CS->body()) {
3367      EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3368      if (ESR == ESR_Succeeded)
3369        Case = nullptr;
3370      else if (ESR != ESR_CaseNotFound)
3371        return ESR;
3372    }
3373    return Case ? ESR_CaseNotFound : ESR_Succeeded;
3374  }
3375
3376  case Stmt::IfStmtClass: {
3377    const IfStmt *IS = cast<IfStmt>(S);
3378
3379    // Evaluate the condition, as either a var decl or as an expression.
3380    BlockScopeRAII Scope(Info);
3381    bool Cond;
3382    if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3383      return ESR_Failed;
3384
3385    if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3386      EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3387      if (ESR != ESR_Succeeded)
3388        return ESR;
3389    }
3390    return ESR_Succeeded;
3391  }
3392
3393  case Stmt::WhileStmtClass: {
3394    const WhileStmt *WS = cast<WhileStmt>(S);
3395    while (true) {
3396      BlockScopeRAII Scope(Info);
3397      bool Continue;
3398      if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3399                        Continue))
3400        return ESR_Failed;
3401      if (!Continue)
3402        break;
3403
3404      EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3405      if (ESR != ESR_Continue)
3406        return ESR;
3407    }
3408    return ESR_Succeeded;
3409  }
3410
3411  case Stmt::DoStmtClass: {
3412    const DoStmt *DS = cast<DoStmt>(S);
3413    bool Continue;
3414    do {
3415      EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
3416      if (ESR != ESR_Continue)
3417        return ESR;
3418      Case = nullptr;
3419
3420      FullExpressionRAII CondScope(Info);
3421      if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3422        return ESR_Failed;
3423    } while (Continue);
3424    return ESR_Succeeded;
3425  }
3426
3427  case Stmt::ForStmtClass: {
3428    const ForStmt *FS = cast<ForStmt>(S);
3429    BlockScopeRAII Scope(Info);
3430    if (FS->getInit()) {
3431      EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3432      if (ESR != ESR_Succeeded)
3433        return ESR;
3434    }
3435    while (true) {
3436      BlockScopeRAII Scope(Info);
3437      bool Continue = true;
3438      if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3439                                         FS->getCond(), Continue))
3440        return ESR_Failed;
3441      if (!Continue)
3442        break;
3443
3444      EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3445      if (ESR != ESR_Continue)
3446        return ESR;
3447
3448      if (FS->getInc()) {
3449        FullExpressionRAII IncScope(Info);
3450        if (!EvaluateIgnoredValue(Info, FS->getInc()))
3451          return ESR_Failed;
3452      }
3453    }
3454    return ESR_Succeeded;
3455  }
3456
3457  case Stmt::CXXForRangeStmtClass: {
3458    const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3459    BlockScopeRAII Scope(Info);
3460
3461    // Initialize the __range variable.
3462    EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3463    if (ESR != ESR_Succeeded)
3464      return ESR;
3465
3466    // Create the __begin and __end iterators.
3467    ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3468    if (ESR != ESR_Succeeded)
3469      return ESR;
3470
3471    while (true) {
3472      // Condition: __begin != __end.
3473      {
3474        bool Continue = true;
3475        FullExpressionRAII CondExpr(Info);
3476        if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3477          return ESR_Failed;
3478        if (!Continue)
3479          break;
3480      }
3481
3482      // User's variable declaration, initialized by *__begin.
3483      BlockScopeRAII InnerScope(Info);
3484      ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3485      if (ESR != ESR_Succeeded)
3486        return ESR;
3487
3488      // Loop body.
3489      ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3490      if (ESR != ESR_Continue)
3491        return ESR;
3492
3493      // Increment: ++__begin
3494      if (!EvaluateIgnoredValue(Info, FS->getInc()))
3495        return ESR_Failed;
3496    }
3497
3498    return ESR_Succeeded;
3499  }
3500
3501  case Stmt::SwitchStmtClass:
3502    return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3503
3504  case Stmt::ContinueStmtClass:
3505    return ESR_Continue;
3506
3507  case Stmt::BreakStmtClass:
3508    return ESR_Break;
3509
3510  case Stmt::LabelStmtClass:
3511    return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3512
3513  case Stmt::AttributedStmtClass:
3514    // As a general principle, C++11 attributes can be ignored without
3515    // any semantic impact.
3516    return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3517                        Case);
3518
3519  case Stmt::CaseStmtClass:
3520  case Stmt::DefaultStmtClass:
3521    return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
3522  }
3523}
3524
3525/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3526/// default constructor. If so, we'll fold it whether or not it's marked as
3527/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3528/// so we need special handling.
3529static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
3530                                           const CXXConstructorDecl *CD,
3531                                           bool IsValueInitialization) {
3532  if (!CD->isTrivial() || !CD->isDefaultConstructor())
3533    return false;
3534
3535  // Value-initialization does not call a trivial default constructor, so such a
3536  // call is a core constant expression whether or not the constructor is
3537  // constexpr.
3538  if (!CD->isConstexpr() && !IsValueInitialization) {
3539    if (Info.getLangOpts().CPlusPlus11) {
3540      // FIXME: If DiagDecl is an implicitly-declared special member function,
3541      // we should be much more explicit about why it's not constexpr.
3542      Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3543        << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3544      Info.Note(CD->getLocation(), diag::note_declared_at);
3545    } else {
3546      Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3547    }
3548  }
3549  return true;
3550}
3551
3552/// CheckConstexprFunction - Check that a function can be called in a constant
3553/// expression.
3554static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3555                                   const FunctionDecl *Declaration,
3556                                   const FunctionDecl *Definition) {
3557  // Potential constant expressions can contain calls to declared, but not yet
3558  // defined, constexpr functions.
3559  if (Info.checkingPotentialConstantExpression() && !Definition &&
3560      Declaration->isConstexpr())
3561    return false;
3562
3563  // Bail out with no diagnostic if the function declaration itself is invalid.
3564  // We will have produced a relevant diagnostic while parsing it.
3565  if (Declaration->isInvalidDecl())
3566    return false;
3567
3568  // Can we evaluate this function call?
3569  if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3570    return true;
3571
3572  if (Info.getLangOpts().CPlusPlus11) {
3573    const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
3574    // FIXME: If DiagDecl is an implicitly-declared special member function, we
3575    // should be much more explicit about why it's not constexpr.
3576    Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3577      << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3578      << DiagDecl;
3579    Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3580  } else {
3581    Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3582  }
3583  return false;
3584}
3585
3586namespace {
3587typedef SmallVector<APValue, 8> ArgVector;
3588}
3589
3590/// EvaluateArgs - Evaluate the arguments to a function call.
3591static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3592                         EvalInfo &Info) {
3593  bool Success = true;
3594  for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
3595       I != E; ++I) {
3596    if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3597      // If we're checking for a potential constant expression, evaluate all
3598      // initializers even if some of them fail.
3599      if (!Info.keepEvaluatingAfterFailure())
3600        return false;
3601      Success = false;
3602    }
3603  }
3604  return Success;
3605}
3606
3607/// Evaluate a function call.
3608static bool HandleFunctionCall(SourceLocation CallLoc,
3609                               const FunctionDecl *Callee, const LValue *This,
3610                               ArrayRef<const Expr*> Args, const Stmt *Body,
3611                               EvalInfo &Info, APValue &Result) {
3612  ArgVector ArgValues(Args.size());
3613  if (!EvaluateArgs(Args, ArgValues, Info))
3614    return false;
3615
3616  if (!Info.CheckCallLimit(CallLoc))
3617    return false;
3618
3619  CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
3620
3621  // For a trivial copy or move assignment, perform an APValue copy. This is
3622  // essential for unions, where the operations performed by the assignment
3623  // operator cannot be represented as statements.
3624  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3625  if (MD && MD->isDefaulted() && MD->isTrivial()) {
3626    assert(This &&
3627           (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3628    LValue RHS;
3629    RHS.setFrom(Info.Ctx, ArgValues[0]);
3630    APValue RHSValue;
3631    if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3632                                        RHS, RHSValue))
3633      return false;
3634    if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3635                          RHSValue))
3636      return false;
3637    This->moveInto(Result);
3638    return true;
3639  }
3640
3641  EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
3642  if (ESR == ESR_Succeeded) {
3643    if (Callee->getReturnType()->isVoidType())
3644      return true;
3645    Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
3646  }
3647  return ESR == ESR_Returned;
3648}
3649
3650/// Evaluate a constructor call.
3651static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
3652                                  ArrayRef<const Expr*> Args,
3653                                  const CXXConstructorDecl *Definition,
3654                                  EvalInfo &Info, APValue &Result) {
3655  ArgVector ArgValues(Args.size());
3656  if (!EvaluateArgs(Args, ArgValues, Info))
3657    return false;
3658
3659  if (!Info.CheckCallLimit(CallLoc))
3660    return false;
3661
3662  const CXXRecordDecl *RD = Definition->getParent();
3663  if (RD->getNumVBases()) {
3664    Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3665    return false;
3666  }
3667
3668  CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
3669
3670  // If it's a delegating constructor, just delegate.
3671  if (Definition->isDelegatingConstructor()) {
3672    CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
3673    {
3674      FullExpressionRAII InitScope(Info);
3675      if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3676        return false;
3677    }
3678    return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
3679  }
3680
3681  // For a trivial copy or move constructor, perform an APValue copy. This is
3682  // essential for unions, where the operations performed by the constructor
3683  // cannot be represented by ctor-initializers.
3684  if (Definition->isDefaulted() &&
3685      ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3686       (Definition->isMoveConstructor() && Definition->isTrivial()))) {
3687    LValue RHS;
3688    RHS.setFrom(Info.Ctx, ArgValues[0]);
3689    return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3690                                          RHS, Result);
3691  }
3692
3693  // Reserve space for the struct members.
3694  if (!RD->isUnion() && Result.isUninit())
3695    Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3696                     std::distance(RD->field_begin(), RD->field_end()));
3697
3698  if (RD->isInvalidDecl()) return false;
3699  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3700
3701  // A scope for temporaries lifetime-extended by reference members.
3702  BlockScopeRAII LifetimeExtendedScope(Info);
3703
3704  bool Success = true;
3705  unsigned BasesSeen = 0;
3706#ifndef NDEBUG
3707  CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3708#endif
3709  for (const auto *I : Definition->inits()) {
3710    LValue Subobject = This;
3711    APValue *Value = &Result;
3712
3713    // Determine the subobject to initialize.
3714    FieldDecl *FD = nullptr;
3715    if (I->isBaseInitializer()) {
3716      QualType BaseType(I->getBaseClass(), 0);
3717#ifndef NDEBUG
3718      // Non-virtual base classes are initialized in the order in the class
3719      // definition. We have already checked for virtual base classes.
3720      assert(!BaseIt->isVirtual() && "virtual base for literal type");
3721      assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3722             "base class initializers not in expected order");
3723      ++BaseIt;
3724#endif
3725      if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
3726                                  BaseType->getAsCXXRecordDecl(), &Layout))
3727        return false;
3728      Value = &Result.getStructBase(BasesSeen++);
3729    } else if ((FD = I->getMember())) {
3730      if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
3731        return false;
3732      if (RD->isUnion()) {
3733        Result = APValue(FD);
3734        Value = &Result.getUnionValue();
3735      } else {
3736        Value = &Result.getStructField(FD->getFieldIndex());
3737      }
3738    } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
3739      // Walk the indirect field decl's chain to find the object to initialize,
3740      // and make sure we've initialized every step along it.
3741      for (auto *C : IFD->chain()) {
3742        FD = cast<FieldDecl>(C);
3743        CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3744        // Switch the union field if it differs. This happens if we had
3745        // preceding zero-initialization, and we're now initializing a union
3746        // subobject other than the first.
3747        // FIXME: In this case, the values of the other subobjects are
3748        // specified, since zero-initialization sets all padding bits to zero.
3749        if (Value->isUninit() ||
3750            (Value->isUnion() && Value->getUnionField() != FD)) {
3751          if (CD->isUnion())
3752            *Value = APValue(FD);
3753          else
3754            *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3755                             std::distance(CD->field_begin(), CD->field_end()));
3756        }
3757        if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
3758          return false;
3759        if (CD->isUnion())
3760          Value = &Value->getUnionValue();
3761        else
3762          Value = &Value->getStructField(FD->getFieldIndex());
3763      }
3764    } else {
3765      llvm_unreachable("unknown base initializer kind");
3766    }
3767
3768    FullExpressionRAII InitScope(Info);
3769    if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
3770        (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
3771                                                          *Value, FD))) {
3772      // If we're checking for a potential constant expression, evaluate all
3773      // initializers even if some of them fail.
3774      if (!Info.keepEvaluatingAfterFailure())
3775        return false;
3776      Success = false;
3777    }
3778  }
3779
3780  return Success &&
3781         EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
3782}
3783
3784//===----------------------------------------------------------------------===//
3785// Generic Evaluation
3786//===----------------------------------------------------------------------===//
3787namespace {
3788
3789template <class Derived>
3790class ExprEvaluatorBase
3791  : public ConstStmtVisitor<Derived, bool> {
3792private:
3793  bool DerivedSuccess(const APValue &V, const Expr *E) {
3794    return static_cast<Derived*>(this)->Success(V, E);
3795  }
3796  bool DerivedZeroInitialization(const Expr *E) {
3797    return static_cast<Derived*>(this)->ZeroInitialization(E);
3798  }
3799
3800  // Check whether a conditional operator with a non-constant condition is a
3801  // potential constant expression. If neither arm is a potential constant
3802  // expression, then the conditional operator is not either.
3803  template<typename ConditionalOperator>
3804  void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3805    assert(Info.checkingPotentialConstantExpression());
3806
3807    // Speculatively evaluate both arms.
3808    {
3809      SmallVector<PartialDiagnosticAt, 8> Diag;
3810      SpeculativeEvaluationRAII Speculate(Info, &Diag);
3811
3812      StmtVisitorTy::Visit(E->getFalseExpr());
3813      if (Diag.empty())
3814        return;
3815
3816      Diag.clear();
3817      StmtVisitorTy::Visit(E->getTrueExpr());
3818      if (Diag.empty())
3819        return;
3820    }
3821
3822    Error(E, diag::note_constexpr_conditional_never_const);
3823  }
3824
3825
3826  template<typename ConditionalOperator>
3827  bool HandleConditionalOperator(const ConditionalOperator *E) {
3828    bool BoolResult;
3829    if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3830      if (Info.checkingPotentialConstantExpression())
3831        CheckPotentialConstantConditional(E);
3832      return false;
3833    }
3834
3835    Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3836    return StmtVisitorTy::Visit(EvalExpr);
3837  }
3838
3839protected:
3840  EvalInfo &Info;
3841  typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
3842  typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3843
3844  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
3845    return Info.CCEDiag(E, D);
3846  }
3847
3848  bool ZeroInitialization(const Expr *E) { return Error(E); }
3849
3850public:
3851  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3852
3853  EvalInfo &getEvalInfo() { return Info; }
3854
3855  /// Report an evaluation error. This should only be called when an error is
3856  /// first discovered. When propagating an error, just return false.
3857  bool Error(const Expr *E, diag::kind D) {
3858    Info.Diag(E, D);
3859    return false;
3860  }
3861  bool Error(const Expr *E) {
3862    return Error(E, diag::note_invalid_subexpr_in_const_expr);
3863  }
3864
3865  bool VisitStmt(const Stmt *) {
3866    llvm_unreachable("Expression evaluator should not be called on stmts");
3867  }
3868  bool VisitExpr(const Expr *E) {
3869    return Error(E);
3870  }
3871
3872  bool VisitParenExpr(const ParenExpr *E)
3873    { return StmtVisitorTy::Visit(E->getSubExpr()); }
3874  bool VisitUnaryExtension(const UnaryOperator *E)
3875    { return StmtVisitorTy::Visit(E->getSubExpr()); }
3876  bool VisitUnaryPlus(const UnaryOperator *E)
3877    { return StmtVisitorTy::Visit(E->getSubExpr()); }
3878  bool VisitChooseExpr(const ChooseExpr *E)
3879    { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
3880  bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3881    { return StmtVisitorTy::Visit(E->getResultExpr()); }
3882  bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3883    { return StmtVisitorTy::Visit(E->getReplacement()); }
3884  bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3885    { return StmtVisitorTy::Visit(E->getExpr()); }
3886  bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
3887    // The initializer may not have been parsed yet, or might be erroneous.
3888    if (!E->getExpr())
3889      return Error(E);
3890    return StmtVisitorTy::Visit(E->getExpr());
3891  }
3892  // We cannot create any objects for which cleanups are required, so there is
3893  // nothing to do here; all cleanups must come from unevaluated subexpressions.
3894  bool VisitExprWithCleanups(const ExprWithCleanups *E)
3895    { return StmtVisitorTy::Visit(E->getSubExpr()); }
3896
3897  bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3898    CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3899    return static_cast<Derived*>(this)->VisitCastExpr(E);
3900  }
3901  bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3902    CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3903    return static_cast<Derived*>(this)->VisitCastExpr(E);
3904  }
3905
3906  bool VisitBinaryOperator(const BinaryOperator *E) {
3907    switch (E->getOpcode()) {
3908    default:
3909      return Error(E);
3910
3911    case BO_Comma:
3912      VisitIgnoredValue(E->getLHS());
3913      return StmtVisitorTy::Visit(E->getRHS());
3914
3915    case BO_PtrMemD:
3916    case BO_PtrMemI: {
3917      LValue Obj;
3918      if (!HandleMemberPointerAccess(Info, E, Obj))
3919        return false;
3920      APValue Result;
3921      if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
3922        return false;
3923      return DerivedSuccess(Result, E);
3924    }
3925    }
3926  }
3927
3928  bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
3929    // Evaluate and cache the common expression. We treat it as a temporary,
3930    // even though it's not quite the same thing.
3931    if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
3932                  Info, E->getCommon()))
3933      return false;
3934
3935    return HandleConditionalOperator(E);
3936  }
3937
3938  bool VisitConditionalOperator(const ConditionalOperator *E) {
3939    bool IsBcpCall = false;
3940    // If the condition (ignoring parens) is a __builtin_constant_p call,
3941    // the result is a constant expression if it can be folded without
3942    // side-effects. This is an important GNU extension. See GCC PR38377
3943    // for discussion.
3944    if (const CallExpr *CallCE =
3945          dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3946      if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
3947        IsBcpCall = true;
3948
3949    // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3950    // constant expression; we can't check whether it's potentially foldable.
3951    if (Info.checkingPotentialConstantExpression() && IsBcpCall)
3952      return false;
3953
3954    FoldConstant Fold(Info, IsBcpCall);
3955    if (!HandleConditionalOperator(E)) {
3956      Fold.keepDiagnostics();
3957      return false;
3958    }
3959
3960    return true;
3961  }
3962
3963  bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
3964    if (APValue *Value = Info.CurrentCall->getTemporary(E))
3965      return DerivedSuccess(*Value, E);
3966
3967    const Expr *Source = E->getSourceExpr();
3968    if (!Source)
3969      return Error(E);
3970    if (Source == E) { // sanity checking.
3971      assert(0 && "OpaqueValueExpr recursively refers to itself");
3972      return Error(E);
3973    }
3974    return StmtVisitorTy::Visit(Source);
3975  }
3976
3977  bool VisitCallExpr(const CallExpr *E) {
3978    const Expr *Callee = E->getCallee()->IgnoreParens();
3979    QualType CalleeType = Callee->getType();
3980
3981    const FunctionDecl *FD = nullptr;
3982    LValue *This = nullptr, ThisVal;
3983    ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
3984    bool HasQualifier = false;
3985
3986    // Extract function decl and 'this' pointer from the callee.
3987    if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
3988      const ValueDecl *Member = nullptr;
3989      if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3990        // Explicit bound member calls, such as x.f() or p->g();
3991        if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
3992          return false;
3993        Member = ME->getMemberDecl();
3994        This = &ThisVal;
3995        HasQualifier = ME->hasQualifier();
3996      } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3997        // Indirect bound member calls ('.*' or '->*').
3998        Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3999        if (!Member) return false;
4000        This = &ThisVal;
4001      } else
4002        return Error(Callee);
4003
4004      FD = dyn_cast<FunctionDecl>(Member);
4005      if (!FD)
4006        return Error(Callee);
4007    } else if (CalleeType->isFunctionPointerType()) {
4008      LValue Call;
4009      if (!EvaluatePointer(Callee, Call, Info))
4010        return false;
4011
4012      if (!Call.getLValueOffset().isZero())
4013        return Error(Callee);
4014      FD = dyn_cast_or_null<FunctionDecl>(
4015                             Call.getLValueBase().dyn_cast<const ValueDecl*>());
4016      if (!FD)
4017        return Error(Callee);
4018
4019      // Overloaded operator calls to member functions are represented as normal
4020      // calls with '*this' as the first argument.
4021      const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4022      if (MD && !MD->isStatic()) {
4023        // FIXME: When selecting an implicit conversion for an overloaded
4024        // operator delete, we sometimes try to evaluate calls to conversion
4025        // operators without a 'this' parameter!
4026        if (Args.empty())
4027          return Error(E);
4028
4029        if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4030          return false;
4031        This = &ThisVal;
4032        Args = Args.slice(1);
4033      }
4034
4035      // Don't call function pointers which have been cast to some other type.
4036      if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
4037        return Error(E);
4038    } else
4039      return Error(E);
4040
4041    if (This && !This->checkSubobject(Info, E, CSK_This))
4042      return false;
4043
4044    // DR1358 allows virtual constexpr functions in some cases. Don't allow
4045    // calls to such functions in constant expressions.
4046    if (This && !HasQualifier &&
4047        isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4048      return Error(E, diag::note_constexpr_virtual_call);
4049
4050    const FunctionDecl *Definition = nullptr;
4051    Stmt *Body = FD->getBody(Definition);
4052    APValue Result;
4053
4054    if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
4055        !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
4056                            Info, Result))
4057      return false;
4058
4059    return DerivedSuccess(Result, E);
4060  }
4061
4062  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4063    return StmtVisitorTy::Visit(E->getInitializer());
4064  }
4065  bool VisitInitListExpr(const InitListExpr *E) {
4066    if (E->getNumInits() == 0)
4067      return DerivedZeroInitialization(E);
4068    if (E->getNumInits() == 1)
4069      return StmtVisitorTy::Visit(E->getInit(0));
4070    return Error(E);
4071  }
4072  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4073    return DerivedZeroInitialization(E);
4074  }
4075  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4076    return DerivedZeroInitialization(E);
4077  }
4078  bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4079    return DerivedZeroInitialization(E);
4080  }
4081
4082  /// A member expression where the object is a prvalue is itself a prvalue.
4083  bool VisitMemberExpr(const MemberExpr *E) {
4084    assert(!E->isArrow() && "missing call to bound member function?");
4085
4086    APValue Val;
4087    if (!Evaluate(Val, Info, E->getBase()))
4088      return false;
4089
4090    QualType BaseTy = E->getBase()->getType();
4091
4092    const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4093    if (!FD) return Error(E);
4094    assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4095    assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4096           FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4097
4098    CompleteObject Obj(&Val, BaseTy);
4099    SubobjectDesignator Designator(BaseTy);
4100    Designator.addDeclUnchecked(FD);
4101
4102    APValue Result;
4103    return extractSubobject(Info, E, Obj, Designator, Result) &&
4104           DerivedSuccess(Result, E);
4105  }
4106
4107  bool VisitCastExpr(const CastExpr *E) {
4108    switch (E->getCastKind()) {
4109    default:
4110      break;
4111
4112    case CK_AtomicToNonAtomic: {
4113      APValue AtomicVal;
4114      if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4115        return false;
4116      return DerivedSuccess(AtomicVal, E);
4117    }
4118
4119    case CK_NoOp:
4120    case CK_UserDefinedConversion:
4121      return StmtVisitorTy::Visit(E->getSubExpr());
4122
4123    case CK_LValueToRValue: {
4124      LValue LVal;
4125      if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4126        return false;
4127      APValue RVal;
4128      // Note, we use the subexpression's type in order to retain cv-qualifiers.
4129      if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4130                                          LVal, RVal))
4131        return false;
4132      return DerivedSuccess(RVal, E);
4133    }
4134    }
4135
4136    return Error(E);
4137  }
4138
4139  bool VisitUnaryPostInc(const UnaryOperator *UO) {
4140    return VisitUnaryPostIncDec(UO);
4141  }
4142  bool VisitUnaryPostDec(const UnaryOperator *UO) {
4143    return VisitUnaryPostIncDec(UO);
4144  }
4145  bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4146    if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4147      return Error(UO);
4148
4149    LValue LVal;
4150    if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4151      return false;
4152    APValue RVal;
4153    if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4154                      UO->isIncrementOp(), &RVal))
4155      return false;
4156    return DerivedSuccess(RVal, UO);
4157  }
4158
4159  bool VisitStmtExpr(const StmtExpr *E) {
4160    // We will have checked the full-expressions inside the statement expression
4161    // when they were completed, and don't need to check them again now.
4162    if (Info.checkingForOverflow())
4163      return Error(E);
4164
4165    BlockScopeRAII Scope(Info);
4166    const CompoundStmt *CS = E->getSubStmt();
4167    for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4168                                           BE = CS->body_end();
4169         /**/; ++BI) {
4170      if (BI + 1 == BE) {
4171        const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4172        if (!FinalExpr) {
4173          Info.Diag((*BI)->getLocStart(),
4174                    diag::note_constexpr_stmt_expr_unsupported);
4175          return false;
4176        }
4177        return this->Visit(FinalExpr);
4178      }
4179
4180      APValue ReturnValue;
4181      EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4182      if (ESR != ESR_Succeeded) {
4183        // FIXME: If the statement-expression terminated due to 'return',
4184        // 'break', or 'continue', it would be nice to propagate that to
4185        // the outer statement evaluation rather than bailing out.
4186        if (ESR != ESR_Failed)
4187          Info.Diag((*BI)->getLocStart(),
4188                    diag::note_constexpr_stmt_expr_unsupported);
4189        return false;
4190      }
4191    }
4192  }
4193
4194  /// Visit a value which is evaluated, but whose value is ignored.
4195  void VisitIgnoredValue(const Expr *E) {
4196    EvaluateIgnoredValue(Info, E);
4197  }
4198};
4199
4200}
4201
4202//===----------------------------------------------------------------------===//
4203// Common base class for lvalue and temporary evaluation.
4204//===----------------------------------------------------------------------===//
4205namespace {
4206template<class Derived>
4207class LValueExprEvaluatorBase
4208  : public ExprEvaluatorBase<Derived> {
4209protected:
4210  LValue &Result;
4211  typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4212  typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4213
4214  bool Success(APValue::LValueBase B) {
4215    Result.set(B);
4216    return true;
4217  }
4218
4219public:
4220  LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4221    ExprEvaluatorBaseTy(Info), Result(Result) {}
4222
4223  bool Success(const APValue &V, const Expr *E) {
4224    Result.setFrom(this->Info.Ctx, V);
4225    return true;
4226  }
4227
4228  bool VisitMemberExpr(const MemberExpr *E) {
4229    // Handle non-static data members.
4230    QualType BaseTy;
4231    if (E->isArrow()) {
4232      if (!EvaluatePointer(E->getBase(), Result, this->Info))
4233        return false;
4234      BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4235    } else if (E->getBase()->isRValue()) {
4236      assert(E->getBase()->getType()->isRecordType());
4237      if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4238        return false;
4239      BaseTy = E->getBase()->getType();
4240    } else {
4241      if (!this->Visit(E->getBase()))
4242        return false;
4243      BaseTy = E->getBase()->getType();
4244    }
4245
4246    const ValueDecl *MD = E->getMemberDecl();
4247    if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4248      assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4249             FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4250      (void)BaseTy;
4251      if (!HandleLValueMember(this->Info, E, Result, FD))
4252        return false;
4253    } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
4254      if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4255        return false;
4256    } else
4257      return this->Error(E);
4258
4259    if (MD->getType()->isReferenceType()) {
4260      APValue RefValue;
4261      if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
4262                                          RefValue))
4263        return false;
4264      return Success(RefValue, E);
4265    }
4266    return true;
4267  }
4268
4269  bool VisitBinaryOperator(const BinaryOperator *E) {
4270    switch (E->getOpcode()) {
4271    default:
4272      return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4273
4274    case BO_PtrMemD:
4275    case BO_PtrMemI:
4276      return HandleMemberPointerAccess(this->Info, E, Result);
4277    }
4278  }
4279
4280  bool VisitCastExpr(const CastExpr *E) {
4281    switch (E->getCastKind()) {
4282    default:
4283      return ExprEvaluatorBaseTy::VisitCastExpr(E);
4284
4285    case CK_DerivedToBase:
4286    case CK_UncheckedDerivedToBase:
4287      if (!this->Visit(E->getSubExpr()))
4288        return false;
4289
4290      // Now figure out the necessary offset to add to the base LV to get from
4291      // the derived class to the base class.
4292      return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4293                                  Result);
4294    }
4295  }
4296};
4297}
4298
4299//===----------------------------------------------------------------------===//
4300// LValue Evaluation
4301//
4302// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4303// function designators (in C), decl references to void objects (in C), and
4304// temporaries (if building with -Wno-address-of-temporary).
4305//
4306// LValue evaluation produces values comprising a base expression of one of the
4307// following types:
4308// - Declarations
4309//  * VarDecl
4310//  * FunctionDecl
4311// - Literals
4312//  * CompoundLiteralExpr in C
4313//  * StringLiteral
4314//  * CXXTypeidExpr
4315//  * PredefinedExpr
4316//  * ObjCStringLiteralExpr
4317//  * ObjCEncodeExpr
4318//  * AddrLabelExpr
4319//  * BlockExpr
4320//  * CallExpr for a MakeStringConstant builtin
4321// - Locals and temporaries
4322//  * MaterializeTemporaryExpr
4323//  * Any Expr, with a CallIndex indicating the function in which the temporary
4324//    was evaluated, for cases where the MaterializeTemporaryExpr is missing
4325//    from the AST (FIXME).
4326//  * A MaterializeTemporaryExpr that has static storage duration, with no
4327//    CallIndex, for a lifetime-extended temporary.
4328// plus an offset in bytes.
4329//===----------------------------------------------------------------------===//
4330namespace {
4331class LValueExprEvaluator
4332  : public LValueExprEvaluatorBase<LValueExprEvaluator> {
4333public:
4334  LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4335    LValueExprEvaluatorBaseTy(Info, Result) {}
4336
4337  bool VisitVarDecl(const Expr *E, const VarDecl *VD);
4338  bool VisitUnaryPreIncDec(const UnaryOperator *UO);
4339
4340  bool VisitDeclRefExpr(const DeclRefExpr *E);
4341  bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
4342  bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
4343  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4344  bool VisitMemberExpr(const MemberExpr *E);
4345  bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4346  bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
4347  bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
4348  bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
4349  bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4350  bool VisitUnaryDeref(const UnaryOperator *E);
4351  bool VisitUnaryReal(const UnaryOperator *E);
4352  bool VisitUnaryImag(const UnaryOperator *E);
4353  bool VisitUnaryPreInc(const UnaryOperator *UO) {
4354    return VisitUnaryPreIncDec(UO);
4355  }
4356  bool VisitUnaryPreDec(const UnaryOperator *UO) {
4357    return VisitUnaryPreIncDec(UO);
4358  }
4359  bool VisitBinAssign(const BinaryOperator *BO);
4360  bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
4361
4362  bool VisitCastExpr(const CastExpr *E) {
4363    switch (E->getCastKind()) {
4364    default:
4365      return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4366
4367    case CK_LValueBitCast:
4368      this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4369      if (!Visit(E->getSubExpr()))
4370        return false;
4371      Result.Designator.setInvalid();
4372      return true;
4373
4374    case CK_BaseToDerived:
4375      if (!Visit(E->getSubExpr()))
4376        return false;
4377      return HandleBaseToDerivedCast(Info, E, Result);
4378    }
4379  }
4380};
4381} // end anonymous namespace
4382
4383/// Evaluate an expression as an lvalue. This can be legitimately called on
4384/// expressions which are not glvalues, in two cases:
4385///  * function designators in C, and
4386///  * "extern void" objects
4387static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4388  assert(E->isGLValue() || E->getType()->isFunctionType() ||
4389         E->getType()->isVoidType());
4390  return LValueExprEvaluator(Info, Result).Visit(E);
4391}
4392
4393bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
4394  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4395    return Success(FD);
4396  if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
4397    return VisitVarDecl(E, VD);
4398  return Error(E);
4399}
4400
4401bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
4402  CallStackFrame *Frame = nullptr;
4403  if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4404    Frame = Info.CurrentCall;
4405
4406  if (!VD->getType()->isReferenceType()) {
4407    if (Frame) {
4408      Result.set(VD, Frame->Index);
4409      return true;
4410    }
4411    return Success(VD);
4412  }
4413
4414  APValue *V;
4415  if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
4416    return false;
4417  if (V->isUninit()) {
4418    if (!Info.checkingPotentialConstantExpression())
4419      Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4420    return false;
4421  }
4422  return Success(*V, E);
4423}
4424
4425bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4426    const MaterializeTemporaryExpr *E) {
4427  // Walk through the expression to find the materialized temporary itself.
4428  SmallVector<const Expr *, 2> CommaLHSs;
4429  SmallVector<SubobjectAdjustment, 2> Adjustments;
4430  const Expr *Inner = E->GetTemporaryExpr()->
4431      skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
4432
4433  // If we passed any comma operators, evaluate their LHSs.
4434  for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4435    if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4436      return false;
4437
4438  // A materialized temporary with static storage duration can appear within the
4439  // result of a constant expression evaluation, so we need to preserve its
4440  // value for use outside this evaluation.
4441  APValue *Value;
4442  if (E->getStorageDuration() == SD_Static) {
4443    Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
4444    *Value = APValue();
4445    Result.set(E);
4446  } else {
4447    Value = &Info.CurrentCall->
4448        createTemporary(E, E->getStorageDuration() == SD_Automatic);
4449    Result.set(E, Info.CurrentCall->Index);
4450  }
4451
4452  QualType Type = Inner->getType();
4453
4454  // Materialize the temporary itself.
4455  if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4456      (E->getStorageDuration() == SD_Static &&
4457       !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4458    *Value = APValue();
4459    return false;
4460  }
4461
4462  // Adjust our lvalue to refer to the desired subobject.
4463  for (unsigned I = Adjustments.size(); I != 0; /**/) {
4464    --I;
4465    switch (Adjustments[I].Kind) {
4466    case SubobjectAdjustment::DerivedToBaseAdjustment:
4467      if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4468                                Type, Result))
4469        return false;
4470      Type = Adjustments[I].DerivedToBase.BasePath->getType();
4471      break;
4472
4473    case SubobjectAdjustment::FieldAdjustment:
4474      if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4475        return false;
4476      Type = Adjustments[I].Field->getType();
4477      break;
4478
4479    case SubobjectAdjustment::MemberPointerAdjustment:
4480      if (!HandleMemberPointerAccess(this->Info, Type, Result,
4481                                     Adjustments[I].Ptr.RHS))
4482        return false;
4483      Type = Adjustments[I].Ptr.MPT->getPointeeType();
4484      break;
4485    }
4486  }
4487
4488  return true;
4489}
4490
4491bool
4492LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4493  assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4494  // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4495  // only see this when folding in C, so there's no standard to follow here.
4496  return Success(E);
4497}
4498
4499bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
4500  if (!E->isPotentiallyEvaluated())
4501    return Success(E);
4502
4503  Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4504    << E->getExprOperand()->getType()
4505    << E->getExprOperand()->getSourceRange();
4506  return false;
4507}
4508
4509bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4510  return Success(E);
4511}
4512
4513bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
4514  // Handle static data members.
4515  if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4516    VisitIgnoredValue(E->getBase());
4517    return VisitVarDecl(E, VD);
4518  }
4519
4520  // Handle static member functions.
4521  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4522    if (MD->isStatic()) {
4523      VisitIgnoredValue(E->getBase());
4524      return Success(MD);
4525    }
4526  }
4527
4528  // Handle non-static data members.
4529  return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
4530}
4531
4532bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
4533  // FIXME: Deal with vectors as array subscript bases.
4534  if (E->getBase()->getType()->isVectorType())
4535    return Error(E);
4536
4537  if (!EvaluatePointer(E->getBase(), Result, Info))
4538    return false;
4539
4540  APSInt Index;
4541  if (!EvaluateInteger(E->getIdx(), Index, Info))
4542    return false;
4543
4544  return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4545                                     getExtValue(Index));
4546}
4547
4548bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
4549  return EvaluatePointer(E->getSubExpr(), Result, Info);
4550}
4551
4552bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4553  if (!Visit(E->getSubExpr()))
4554    return false;
4555  // __real is a no-op on scalar lvalues.
4556  if (E->getSubExpr()->getType()->isAnyComplexType())
4557    HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4558  return true;
4559}
4560
4561bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4562  assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4563         "lvalue __imag__ on scalar?");
4564  if (!Visit(E->getSubExpr()))
4565    return false;
4566  HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4567  return true;
4568}
4569
4570bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4571  if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4572    return Error(UO);
4573
4574  if (!this->Visit(UO->getSubExpr()))
4575    return false;
4576
4577  return handleIncDec(
4578      this->Info, UO, Result, UO->getSubExpr()->getType(),
4579      UO->isIncrementOp(), nullptr);
4580}
4581
4582bool LValueExprEvaluator::VisitCompoundAssignOperator(
4583    const CompoundAssignOperator *CAO) {
4584  if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4585    return Error(CAO);
4586
4587  APValue RHS;
4588
4589  // The overall lvalue result is the result of evaluating the LHS.
4590  if (!this->Visit(CAO->getLHS())) {
4591    if (Info.keepEvaluatingAfterFailure())
4592      Evaluate(RHS, this->Info, CAO->getRHS());
4593    return false;
4594  }
4595
4596  if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4597    return false;
4598
4599  return handleCompoundAssignment(
4600      this->Info, CAO,
4601      Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4602      CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
4603}
4604
4605bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
4606  if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4607    return Error(E);
4608
4609  APValue NewVal;
4610
4611  if (!this->Visit(E->getLHS())) {
4612    if (Info.keepEvaluatingAfterFailure())
4613      Evaluate(NewVal, this->Info, E->getRHS());
4614    return false;
4615  }
4616
4617  if (!Evaluate(NewVal, this->Info, E->getRHS()))
4618    return false;
4619
4620  return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
4621                          NewVal);
4622}
4623
4624//===----------------------------------------------------------------------===//
4625// Pointer Evaluation
4626//===----------------------------------------------------------------------===//
4627
4628namespace {
4629class PointerExprEvaluator
4630  : public ExprEvaluatorBase<PointerExprEvaluator> {
4631  LValue &Result;
4632
4633  bool Success(const Expr *E) {
4634    Result.set(E);
4635    return true;
4636  }
4637public:
4638
4639  PointerExprEvaluator(EvalInfo &info, LValue &Result)
4640    : ExprEvaluatorBaseTy(info), Result(Result) {}
4641
4642  bool Success(const APValue &V, const Expr *E) {
4643    Result.setFrom(Info.Ctx, V);
4644    return true;
4645  }
4646  bool ZeroInitialization(const Expr *E) {
4647    return Success((Expr*)nullptr);
4648  }
4649
4650  bool VisitBinaryOperator(const BinaryOperator *E);
4651  bool VisitCastExpr(const CastExpr* E);
4652  bool VisitUnaryAddrOf(const UnaryOperator *E);
4653  bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
4654      { return Success(E); }
4655  bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
4656      { return Success(E); }
4657  bool VisitAddrLabelExpr(const AddrLabelExpr *E)
4658      { return Success(E); }
4659  bool VisitCallExpr(const CallExpr *E);
4660  bool VisitBlockExpr(const BlockExpr *E) {
4661    if (!E->getBlockDecl()->hasCaptures())
4662      return Success(E);
4663    return Error(E);
4664  }
4665  bool VisitCXXThisExpr(const CXXThisExpr *E) {
4666    // Can't look at 'this' when checking a potential constant expression.
4667    if (Info.checkingPotentialConstantExpression())
4668      return false;
4669    if (!Info.CurrentCall->This) {
4670      if (Info.getLangOpts().CPlusPlus11)
4671        Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
4672      else
4673        Info.Diag(E);
4674      return false;
4675    }
4676    Result = *Info.CurrentCall->This;
4677    return true;
4678  }
4679
4680  // FIXME: Missing: @protocol, @selector
4681};
4682} // end anonymous namespace
4683
4684static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
4685  assert(E->isRValue() && E->getType()->hasPointerRepresentation());
4686  return PointerExprEvaluator(Info, Result).Visit(E);
4687}
4688
4689bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4690  if (E->getOpcode() != BO_Add &&
4691      E->getOpcode() != BO_Sub)
4692    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4693
4694  const Expr *PExp = E->getLHS();
4695  const Expr *IExp = E->getRHS();
4696  if (IExp->getType()->isPointerType())
4697    std::swap(PExp, IExp);
4698
4699  bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4700  if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
4701    return false;
4702
4703  llvm::APSInt Offset;
4704  if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
4705    return false;
4706
4707  int64_t AdditionalOffset = getExtValue(Offset);
4708  if (E->getOpcode() == BO_Sub)
4709    AdditionalOffset = -AdditionalOffset;
4710
4711  QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
4712  return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4713                                     AdditionalOffset);
4714}
4715
4716bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4717  return EvaluateLValue(E->getSubExpr(), Result, Info);
4718}
4719
4720bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4721  const Expr* SubExpr = E->getSubExpr();
4722
4723  switch (E->getCastKind()) {
4724  default:
4725    break;
4726
4727  case CK_BitCast:
4728  case CK_CPointerToObjCPointerCast:
4729  case CK_BlockPointerToObjCPointerCast:
4730  case CK_AnyPointerToBlockPointerCast:
4731    if (!Visit(SubExpr))
4732      return false;
4733    // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4734    // permitted in constant expressions in C++11. Bitcasts from cv void* are
4735    // also static_casts, but we disallow them as a resolution to DR1312.
4736    if (!E->getType()->isVoidPointerType()) {
4737      Result.Designator.setInvalid();
4738      if (SubExpr->getType()->isVoidPointerType())
4739        CCEDiag(E, diag::note_constexpr_invalid_cast)
4740          << 3 << SubExpr->getType();
4741      else
4742        CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4743    }
4744    return true;
4745
4746  case CK_DerivedToBase:
4747  case CK_UncheckedDerivedToBase:
4748    if (!EvaluatePointer(E->getSubExpr(), Result, Info))
4749      return false;
4750    if (!Result.Base && Result.Offset.isZero())
4751      return true;
4752
4753    // Now figure out the necessary offset to add to the base LV to get from
4754    // the derived class to the base class.
4755    return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4756                                  castAs<PointerType>()->getPointeeType(),
4757                                Result);
4758
4759  case CK_BaseToDerived:
4760    if (!Visit(E->getSubExpr()))
4761      return false;
4762    if (!Result.Base && Result.Offset.isZero())
4763      return true;
4764    return HandleBaseToDerivedCast(Info, E, Result);
4765
4766  case CK_NullToPointer:
4767    VisitIgnoredValue(E->getSubExpr());
4768    return ZeroInitialization(E);
4769
4770  case CK_IntegralToPointer: {
4771    CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4772
4773    APValue Value;
4774    if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
4775      break;
4776
4777    if (Value.isInt()) {
4778      unsigned Size = Info.Ctx.getTypeSize(E->getType());
4779      uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
4780      Result.Base = (Expr*)nullptr;
4781      Result.Offset = CharUnits::fromQuantity(N);
4782      Result.CallIndex = 0;
4783      Result.Designator.setInvalid();
4784      return true;
4785    } else {
4786      // Cast is of an lvalue, no need to change value.
4787      Result.setFrom(Info.Ctx, Value);
4788      return true;
4789    }
4790  }
4791  case CK_ArrayToPointerDecay:
4792    if (SubExpr->isGLValue()) {
4793      if (!EvaluateLValue(SubExpr, Result, Info))
4794        return false;
4795    } else {
4796      Result.set(SubExpr, Info.CurrentCall->Index);
4797      if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
4798                           Info, Result, SubExpr))
4799        return false;
4800    }
4801    // The result is a pointer to the first element of the array.
4802    if (const ConstantArrayType *CAT
4803          = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4804      Result.addArray(Info, E, CAT);
4805    else
4806      Result.Designator.setInvalid();
4807    return true;
4808
4809  case CK_FunctionToPointerDecay:
4810    return EvaluateLValue(SubExpr, Result, Info);
4811  }
4812
4813  return ExprEvaluatorBaseTy::VisitCastExpr(E);
4814}
4815
4816bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
4817  if (IsStringLiteralCall(E))
4818    return Success(E);
4819
4820  switch (E->getBuiltinCallee()) {
4821  case Builtin::BI__builtin_addressof:
4822    return EvaluateLValue(E->getArg(0), Result, Info);
4823
4824  default:
4825    return ExprEvaluatorBaseTy::VisitCallExpr(E);
4826  }
4827}
4828
4829//===----------------------------------------------------------------------===//
4830// Member Pointer Evaluation
4831//===----------------------------------------------------------------------===//
4832
4833namespace {
4834class MemberPointerExprEvaluator
4835  : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
4836  MemberPtr &Result;
4837
4838  bool Success(const ValueDecl *D) {
4839    Result = MemberPtr(D);
4840    return true;
4841  }
4842public:
4843
4844  MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4845    : ExprEvaluatorBaseTy(Info), Result(Result) {}
4846
4847  bool Success(const APValue &V, const Expr *E) {
4848    Result.setFrom(V);
4849    return true;
4850  }
4851  bool ZeroInitialization(const Expr *E) {
4852    return Success((const ValueDecl*)nullptr);
4853  }
4854
4855  bool VisitCastExpr(const CastExpr *E);
4856  bool VisitUnaryAddrOf(const UnaryOperator *E);
4857};
4858} // end anonymous namespace
4859
4860static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4861                                  EvalInfo &Info) {
4862  assert(E->isRValue() && E->getType()->isMemberPointerType());
4863  return MemberPointerExprEvaluator(Info, Result).Visit(E);
4864}
4865
4866bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4867  switch (E->getCastKind()) {
4868  default:
4869    return ExprEvaluatorBaseTy::VisitCastExpr(E);
4870
4871  case CK_NullToMemberPointer:
4872    VisitIgnoredValue(E->getSubExpr());
4873    return ZeroInitialization(E);
4874
4875  case CK_BaseToDerivedMemberPointer: {
4876    if (!Visit(E->getSubExpr()))
4877      return false;
4878    if (E->path_empty())
4879      return true;
4880    // Base-to-derived member pointer casts store the path in derived-to-base
4881    // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4882    // the wrong end of the derived->base arc, so stagger the path by one class.
4883    typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4884    for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4885         PathI != PathE; ++PathI) {
4886      assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4887      const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4888      if (!Result.castToDerived(Derived))
4889        return Error(E);
4890    }
4891    const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4892    if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
4893      return Error(E);
4894    return true;
4895  }
4896
4897  case CK_DerivedToBaseMemberPointer:
4898    if (!Visit(E->getSubExpr()))
4899      return false;
4900    for (CastExpr::path_const_iterator PathI = E->path_begin(),
4901         PathE = E->path_end(); PathI != PathE; ++PathI) {
4902      assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4903      const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4904      if (!Result.castToBase(Base))
4905        return Error(E);
4906    }
4907    return true;
4908  }
4909}
4910
4911bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4912  // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4913  // member can be formed.
4914  return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4915}
4916
4917//===----------------------------------------------------------------------===//
4918// Record Evaluation
4919//===----------------------------------------------------------------------===//
4920
4921namespace {
4922  class RecordExprEvaluator
4923  : public ExprEvaluatorBase<RecordExprEvaluator> {
4924    const LValue &This;
4925    APValue &Result;
4926  public:
4927
4928    RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4929      : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4930
4931    bool Success(const APValue &V, const Expr *E) {
4932      Result = V;
4933      return true;
4934    }
4935    bool ZeroInitialization(const Expr *E);
4936
4937    bool VisitCastExpr(const CastExpr *E);
4938    bool VisitInitListExpr(const InitListExpr *E);
4939    bool VisitCXXConstructExpr(const CXXConstructExpr *E);
4940    bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
4941  };
4942}
4943
4944/// Perform zero-initialization on an object of non-union class type.
4945/// C++11 [dcl.init]p5:
4946///  To zero-initialize an object or reference of type T means:
4947///    [...]
4948///    -- if T is a (possibly cv-qualified) non-union class type,
4949///       each non-static data member and each base-class subobject is
4950///       zero-initialized
4951static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4952                                          const RecordDecl *RD,
4953                                          const LValue &This, APValue &Result) {
4954  assert(!RD->isUnion() && "Expected non-union class type");
4955  const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4956  Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4957                   std::distance(RD->field_begin(), RD->field_end()));
4958
4959  if (RD->isInvalidDecl()) return false;
4960  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4961
4962  if (CD) {
4963    unsigned Index = 0;
4964    for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
4965           End = CD->bases_end(); I != End; ++I, ++Index) {
4966      const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4967      LValue Subobject = This;
4968      if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4969        return false;
4970      if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
4971                                         Result.getStructBase(Index)))
4972        return false;
4973    }
4974  }
4975
4976  for (const auto *I : RD->fields()) {
4977    // -- if T is a reference type, no initialization is performed.
4978    if (I->getType()->isReferenceType())
4979      continue;
4980
4981    LValue Subobject = This;
4982    if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
4983      return false;
4984
4985    ImplicitValueInitExpr VIE(I->getType());
4986    if (!EvaluateInPlace(
4987          Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
4988      return false;
4989  }
4990
4991  return true;
4992}
4993
4994bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4995  const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
4996  if (RD->isInvalidDecl()) return false;
4997  if (RD->isUnion()) {
4998    // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4999    // object's first non-static named data member is zero-initialized
5000    RecordDecl::field_iterator I = RD->field_begin();
5001    if (I == RD->field_end()) {
5002      Result = APValue((const FieldDecl*)nullptr);
5003      return true;
5004    }
5005
5006    LValue Subobject = This;
5007    if (!HandleLValueMember(Info, E, Subobject, *I))
5008      return false;
5009    Result = APValue(*I);
5010    ImplicitValueInitExpr VIE(I->getType());
5011    return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
5012  }
5013
5014  if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
5015    Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
5016    return false;
5017  }
5018
5019  return HandleClassZeroInitialization(Info, E, RD, This, Result);
5020}
5021
5022bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5023  switch (E->getCastKind()) {
5024  default:
5025    return ExprEvaluatorBaseTy::VisitCastExpr(E);
5026
5027  case CK_ConstructorConversion:
5028    return Visit(E->getSubExpr());
5029
5030  case CK_DerivedToBase:
5031  case CK_UncheckedDerivedToBase: {
5032    APValue DerivedObject;
5033    if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
5034      return false;
5035    if (!DerivedObject.isStruct())
5036      return Error(E->getSubExpr());
5037
5038    // Derived-to-base rvalue conversion: just slice off the derived part.
5039    APValue *Value = &DerivedObject;
5040    const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5041    for (CastExpr::path_const_iterator PathI = E->path_begin(),
5042         PathE = E->path_end(); PathI != PathE; ++PathI) {
5043      assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5044      const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5045      Value = &Value->getStructBase(getBaseIndex(RD, Base));
5046      RD = Base;
5047    }
5048    Result = *Value;
5049    return true;
5050  }
5051  }
5052}
5053
5054bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5055  const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
5056  if (RD->isInvalidDecl()) return false;
5057  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5058
5059  if (RD->isUnion()) {
5060    const FieldDecl *Field = E->getInitializedFieldInUnion();
5061    Result = APValue(Field);
5062    if (!Field)
5063      return true;
5064
5065    // If the initializer list for a union does not contain any elements, the
5066    // first element of the union is value-initialized.
5067    // FIXME: The element should be initialized from an initializer list.
5068    //        Is this difference ever observable for initializer lists which
5069    //        we don't build?
5070    ImplicitValueInitExpr VIE(Field->getType());
5071    const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5072
5073    LValue Subobject = This;
5074    if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5075      return false;
5076
5077    // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5078    ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5079                                  isa<CXXDefaultInitExpr>(InitExpr));
5080
5081    return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
5082  }
5083
5084  assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5085         "initializer list for class with base classes");
5086  Result = APValue(APValue::UninitStruct(), 0,
5087                   std::distance(RD->field_begin(), RD->field_end()));
5088  unsigned ElementNo = 0;
5089  bool Success = true;
5090  for (const auto *Field : RD->fields()) {
5091    // Anonymous bit-fields are not considered members of the class for
5092    // purposes of aggregate initialization.
5093    if (Field->isUnnamedBitfield())
5094      continue;
5095
5096    LValue Subobject = This;
5097
5098    bool HaveInit = ElementNo < E->getNumInits();
5099
5100    // FIXME: Diagnostics here should point to the end of the initializer
5101    // list, not the start.
5102    if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
5103                            Subobject, Field, &Layout))
5104      return false;
5105
5106    // Perform an implicit value-initialization for members beyond the end of
5107    // the initializer list.
5108    ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
5109    const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
5110
5111    // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5112    ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5113                                  isa<CXXDefaultInitExpr>(Init));
5114
5115    APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5116    if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5117        (Field->isBitField() && !truncateBitfieldValue(Info, Init,
5118                                                       FieldVal, Field))) {
5119      if (!Info.keepEvaluatingAfterFailure())
5120        return false;
5121      Success = false;
5122    }
5123  }
5124
5125  return Success;
5126}
5127
5128bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5129  const CXXConstructorDecl *FD = E->getConstructor();
5130  if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5131
5132  bool ZeroInit = E->requiresZeroInitialization();
5133  if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
5134    // If we've already performed zero-initialization, we're already done.
5135    if (!Result.isUninit())
5136      return true;
5137
5138    // We can get here in two different ways:
5139    //  1) We're performing value-initialization, and should zero-initialize
5140    //     the object, or
5141    //  2) We're performing default-initialization of an object with a trivial
5142    //     constexpr default constructor, in which case we should start the
5143    //     lifetimes of all the base subobjects (there can be no data member
5144    //     subobjects in this case) per [basic.life]p1.
5145    // Either way, ZeroInitialization is appropriate.
5146    return ZeroInitialization(E);
5147  }
5148
5149  const FunctionDecl *Definition = nullptr;
5150  FD->getBody(Definition);
5151
5152  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5153    return false;
5154
5155  // Avoid materializing a temporary for an elidable copy/move constructor.
5156  if (E->isElidable() && !ZeroInit)
5157    if (const MaterializeTemporaryExpr *ME
5158          = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5159      return Visit(ME->GetTemporaryExpr());
5160
5161  if (ZeroInit && !ZeroInitialization(E))
5162    return false;
5163
5164  ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
5165  return HandleConstructorCall(E->getExprLoc(), This, Args,
5166                               cast<CXXConstructorDecl>(Definition), Info,
5167                               Result);
5168}
5169
5170bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5171    const CXXStdInitializerListExpr *E) {
5172  const ConstantArrayType *ArrayType =
5173      Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5174
5175  LValue Array;
5176  if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5177    return false;
5178
5179  // Get a pointer to the first element of the array.
5180  Array.addArray(Info, E, ArrayType);
5181
5182  // FIXME: Perform the checks on the field types in SemaInit.
5183  RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5184  RecordDecl::field_iterator Field = Record->field_begin();
5185  if (Field == Record->field_end())
5186    return Error(E);
5187
5188  // Start pointer.
5189  if (!Field->getType()->isPointerType() ||
5190      !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5191                            ArrayType->getElementType()))
5192    return Error(E);
5193
5194  // FIXME: What if the initializer_list type has base classes, etc?
5195  Result = APValue(APValue::UninitStruct(), 0, 2);
5196  Array.moveInto(Result.getStructField(0));
5197
5198  if (++Field == Record->field_end())
5199    return Error(E);
5200
5201  if (Field->getType()->isPointerType() &&
5202      Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5203                           ArrayType->getElementType())) {
5204    // End pointer.
5205    if (!HandleLValueArrayAdjustment(Info, E, Array,
5206                                     ArrayType->getElementType(),
5207                                     ArrayType->getSize().getZExtValue()))
5208      return false;
5209    Array.moveInto(Result.getStructField(1));
5210  } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5211    // Length.
5212    Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5213  else
5214    return Error(E);
5215
5216  if (++Field != Record->field_end())
5217    return Error(E);
5218
5219  return true;
5220}
5221
5222static bool EvaluateRecord(const Expr *E, const LValue &This,
5223                           APValue &Result, EvalInfo &Info) {
5224  assert(E->isRValue() && E->getType()->isRecordType() &&
5225         "can't evaluate expression as a record rvalue");
5226  return RecordExprEvaluator(Info, This, Result).Visit(E);
5227}
5228
5229//===----------------------------------------------------------------------===//
5230// Temporary Evaluation
5231//
5232// Temporaries are represented in the AST as rvalues, but generally behave like
5233// lvalues. The full-object of which the temporary is a subobject is implicitly
5234// materialized so that a reference can bind to it.
5235//===----------------------------------------------------------------------===//
5236namespace {
5237class TemporaryExprEvaluator
5238  : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5239public:
5240  TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5241    LValueExprEvaluatorBaseTy(Info, Result) {}
5242
5243  /// Visit an expression which constructs the value of this temporary.
5244  bool VisitConstructExpr(const Expr *E) {
5245    Result.set(E, Info.CurrentCall->Index);
5246    return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5247                           Info, Result, E);
5248  }
5249
5250  bool VisitCastExpr(const CastExpr *E) {
5251    switch (E->getCastKind()) {
5252    default:
5253      return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5254
5255    case CK_ConstructorConversion:
5256      return VisitConstructExpr(E->getSubExpr());
5257    }
5258  }
5259  bool VisitInitListExpr(const InitListExpr *E) {
5260    return VisitConstructExpr(E);
5261  }
5262  bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5263    return VisitConstructExpr(E);
5264  }
5265  bool VisitCallExpr(const CallExpr *E) {
5266    return VisitConstructExpr(E);
5267  }
5268};
5269} // end anonymous namespace
5270
5271/// Evaluate an expression of record type as a temporary.
5272static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
5273  assert(E->isRValue() && E->getType()->isRecordType());
5274  return TemporaryExprEvaluator(Info, Result).Visit(E);
5275}
5276
5277//===----------------------------------------------------------------------===//
5278// Vector Evaluation
5279//===----------------------------------------------------------------------===//
5280
5281namespace {
5282  class VectorExprEvaluator
5283  : public ExprEvaluatorBase<VectorExprEvaluator> {
5284    APValue &Result;
5285  public:
5286
5287    VectorExprEvaluator(EvalInfo &info, APValue &Result)
5288      : ExprEvaluatorBaseTy(info), Result(Result) {}
5289
5290    bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5291      assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5292      // FIXME: remove this APValue copy.
5293      Result = APValue(V.data(), V.size());
5294      return true;
5295    }
5296    bool Success(const APValue &V, const Expr *E) {
5297      assert(V.isVector());
5298      Result = V;
5299      return true;
5300    }
5301    bool ZeroInitialization(const Expr *E);
5302
5303    bool VisitUnaryReal(const UnaryOperator *E)
5304      { return Visit(E->getSubExpr()); }
5305    bool VisitCastExpr(const CastExpr* E);
5306    bool VisitInitListExpr(const InitListExpr *E);
5307    bool VisitUnaryImag(const UnaryOperator *E);
5308    // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
5309    //                 binary comparisons, binary and/or/xor,
5310    //                 shufflevector, ExtVectorElementExpr
5311  };
5312} // end anonymous namespace
5313
5314static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
5315  assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
5316  return VectorExprEvaluator(Info, Result).Visit(E);
5317}
5318
5319bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5320  const VectorType *VTy = E->getType()->castAs<VectorType>();
5321  unsigned NElts = VTy->getNumElements();
5322
5323  const Expr *SE = E->getSubExpr();
5324  QualType SETy = SE->getType();
5325
5326  switch (E->getCastKind()) {
5327  case CK_VectorSplat: {
5328    APValue Val = APValue();
5329    if (SETy->isIntegerType()) {
5330      APSInt IntResult;
5331      if (!EvaluateInteger(SE, IntResult, Info))
5332         return false;
5333      Val = APValue(IntResult);
5334    } else if (SETy->isRealFloatingType()) {
5335       APFloat F(0.0);
5336       if (!EvaluateFloat(SE, F, Info))
5337         return false;
5338       Val = APValue(F);
5339    } else {
5340      return Error(E);
5341    }
5342
5343    // Splat and create vector APValue.
5344    SmallVector<APValue, 4> Elts(NElts, Val);
5345    return Success(Elts, E);
5346  }
5347  case CK_BitCast: {
5348    // Evaluate the operand into an APInt we can extract from.
5349    llvm::APInt SValInt;
5350    if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5351      return false;
5352    // Extract the elements
5353    QualType EltTy = VTy->getElementType();
5354    unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5355    bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5356    SmallVector<APValue, 4> Elts;
5357    if (EltTy->isRealFloatingType()) {
5358      const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
5359      unsigned FloatEltSize = EltSize;
5360      if (&Sem == &APFloat::x87DoubleExtended)
5361        FloatEltSize = 80;
5362      for (unsigned i = 0; i < NElts; i++) {
5363        llvm::APInt Elt;
5364        if (BigEndian)
5365          Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5366        else
5367          Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
5368        Elts.push_back(APValue(APFloat(Sem, Elt)));
5369      }
5370    } else if (EltTy->isIntegerType()) {
5371      for (unsigned i = 0; i < NElts; i++) {
5372        llvm::APInt Elt;
5373        if (BigEndian)
5374          Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5375        else
5376          Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5377        Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5378      }
5379    } else {
5380      return Error(E);
5381    }
5382    return Success(Elts, E);
5383  }
5384  default:
5385    return ExprEvaluatorBaseTy::VisitCastExpr(E);
5386  }
5387}
5388
5389bool
5390VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5391  const VectorType *VT = E->getType()->castAs<VectorType>();
5392  unsigned NumInits = E->getNumInits();
5393  unsigned NumElements = VT->getNumElements();
5394
5395  QualType EltTy = VT->getElementType();
5396  SmallVector<APValue, 4> Elements;
5397
5398  // The number of initializers can be less than the number of
5399  // vector elements. For OpenCL, this can be due to nested vector
5400  // initialization. For GCC compatibility, missing trailing elements
5401  // should be initialized with zeroes.
5402  unsigned CountInits = 0, CountElts = 0;
5403  while (CountElts < NumElements) {
5404    // Handle nested vector initialization.
5405    if (CountInits < NumInits
5406        && E->getInit(CountInits)->getType()->isVectorType()) {
5407      APValue v;
5408      if (!EvaluateVector(E->getInit(CountInits), v, Info))
5409        return Error(E);
5410      unsigned vlen = v.getVectorLength();
5411      for (unsigned j = 0; j < vlen; j++)
5412        Elements.push_back(v.getVectorElt(j));
5413      CountElts += vlen;
5414    } else if (EltTy->isIntegerType()) {
5415      llvm::APSInt sInt(32);
5416      if (CountInits < NumInits) {
5417        if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
5418          return false;
5419      } else // trailing integer zero.
5420        sInt = Info.Ctx.MakeIntValue(0, EltTy);
5421      Elements.push_back(APValue(sInt));
5422      CountElts++;
5423    } else {
5424      llvm::APFloat f(0.0);
5425      if (CountInits < NumInits) {
5426        if (!EvaluateFloat(E->getInit(CountInits), f, Info))
5427          return false;
5428      } else // trailing float zero.
5429        f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5430      Elements.push_back(APValue(f));
5431      CountElts++;
5432    }
5433    CountInits++;
5434  }
5435  return Success(Elements, E);
5436}
5437
5438bool
5439VectorExprEvaluator::ZeroInitialization(const Expr *E) {
5440  const VectorType *VT = E->getType()->getAs<VectorType>();
5441  QualType EltTy = VT->getElementType();
5442  APValue ZeroElement;
5443  if (EltTy->isIntegerType())
5444    ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5445  else
5446    ZeroElement =
5447        APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5448
5449  SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
5450  return Success(Elements, E);
5451}
5452
5453bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5454  VisitIgnoredValue(E->getSubExpr());
5455  return ZeroInitialization(E);
5456}
5457
5458//===----------------------------------------------------------------------===//
5459// Array Evaluation
5460//===----------------------------------------------------------------------===//
5461
5462namespace {
5463  class ArrayExprEvaluator
5464  : public ExprEvaluatorBase<ArrayExprEvaluator> {
5465    const LValue &This;
5466    APValue &Result;
5467  public:
5468
5469    ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5470      : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
5471
5472    bool Success(const APValue &V, const Expr *E) {
5473      assert((V.isArray() || V.isLValue()) &&
5474             "expected array or string literal");
5475      Result = V;
5476      return true;
5477    }
5478
5479    bool ZeroInitialization(const Expr *E) {
5480      const ConstantArrayType *CAT =
5481          Info.Ctx.getAsConstantArrayType(E->getType());
5482      if (!CAT)
5483        return Error(E);
5484
5485      Result = APValue(APValue::UninitArray(), 0,
5486                       CAT->getSize().getZExtValue());
5487      if (!Result.hasArrayFiller()) return true;
5488
5489      // Zero-initialize all elements.
5490      LValue Subobject = This;
5491      Subobject.addArray(Info, E, CAT);
5492      ImplicitValueInitExpr VIE(CAT->getElementType());
5493      return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
5494    }
5495
5496    bool VisitInitListExpr(const InitListExpr *E);
5497    bool VisitCXXConstructExpr(const CXXConstructExpr *E);
5498    bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5499                               const LValue &Subobject,
5500                               APValue *Value, QualType Type);
5501  };
5502} // end anonymous namespace
5503
5504static bool EvaluateArray(const Expr *E, const LValue &This,
5505                          APValue &Result, EvalInfo &Info) {
5506  assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
5507  return ArrayExprEvaluator(Info, This, Result).Visit(E);
5508}
5509
5510bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5511  const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5512  if (!CAT)
5513    return Error(E);
5514
5515  // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5516  // an appropriately-typed string literal enclosed in braces.
5517  if (E->isStringLiteralInit()) {
5518    LValue LV;
5519    if (!EvaluateLValue(E->getInit(0), LV, Info))
5520      return false;
5521    APValue Val;
5522    LV.moveInto(Val);
5523    return Success(Val, E);
5524  }
5525
5526  bool Success = true;
5527
5528  assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5529         "zero-initialized array shouldn't have any initialized elts");
5530  APValue Filler;
5531  if (Result.isArray() && Result.hasArrayFiller())
5532    Filler = Result.getArrayFiller();
5533
5534  unsigned NumEltsToInit = E->getNumInits();
5535  unsigned NumElts = CAT->getSize().getZExtValue();
5536  const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
5537
5538  // If the initializer might depend on the array index, run it for each
5539  // array element. For now, just whitelist non-class value-initialization.
5540  if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))