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